diff --git a/ios/HEXMobile/CustomVocabularyEditor.swift b/ios/HEXMobile/CustomVocabularyEditor.swift index d10e154d1..bb88cf602 100644 --- a/ios/HEXMobile/CustomVocabularyEditor.swift +++ b/ios/HEXMobile/CustomVocabularyEditor.swift @@ -1,8 +1,11 @@ import SwiftUI -/// The custom vocabulary list shown under its switch in Settings › Dictation. +/// The custom vocabulary list shown under its switch in Settings › Dictation, and on +/// Settings › Keyboard › Vocabulary: one list, which dictation spells (with its switch on) and +/// the full keyboard never autocorrects away, completes and swipes. struct CustomVocabularyEditor: View { private let settings = CustomVocabularySettings() + var footer = String(localized: "Fixes spelling, not words Hex mishears") @State private var terms: [String] = [] @State private var draft = "" @@ -82,7 +85,7 @@ struct CustomVocabularyEditor: View { .fixedSize(horizontal: false, vertical: true) } - Text("Fixes spelling, not words Hex mishears") + Text(footer) .font(.system(size: 12)) .foregroundStyle(HexTheme.textMuted) .fixedSize(horizontal: false, vertical: true) @@ -127,3 +130,47 @@ struct CustomVocabularyEditor: View { notice = nil } } + +/// Settings › Keyboard › Vocabulary: how many words the list holds, opening its page. +struct KeyboardVocabularyRow: View { + @State private var count = CustomVocabularySettings().terms.count + @State private var showsPage = false + + var body: some View { + Button { + showsPage = true + } label: { + HStack(spacing: 12) { + SettingsRowLabel( + title: String(localized: "Vocabulary"), + detail: count == 0 + ? String(localized: "Words autocorrect keeps and suggests") + : String(localized: "\(count) words autocorrect keeps and suggests") + ) + Spacer(minLength: 8) + Image(systemName: "chevron.right") + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(HexTheme.textMuted) + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 50) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .navigationDestination(isPresented: $showsPage) { + SettingsPageScaffold(title: "Vocabulary") { + SettingsCard { + CustomVocabularyEditor( + footer: String(localized: "Hold a word you typed in the keyboard's suggestions to add it. Dictation spells these too while Custom vocabulary is on.") + ) + .padding(16) + } + } + } + .onAppear { count = CustomVocabularySettings().terms.count } + .onChange(of: showsPage) { _, shown in + if !shown { count = CustomVocabularySettings().terms.count } + } + } +} diff --git a/ios/HEXMobile/FullKeyboardSnapshotStage.swift b/ios/HEXMobile/FullKeyboardSnapshotStage.swift index b0b35f346..b7d63c574 100644 --- a/ios/HEXMobile/FullKeyboardSnapshotStage.swift +++ b/ios/HEXMobile/FullKeyboardSnapshotStage.swift @@ -5,7 +5,7 @@ import UIKit /// `--snap-state full-keyboard-[-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|pl|ro|ru|uk|el|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|cs|ro|ru|uk|el|sr-Latn|en` pins it; drafts are in the layout's language. /// `--keyboard-letters qwerty|qwertz|azerty|dvorak|own` arranges its letters (its own without it). /// `--accent-key ø` (or Cyrillic `е`, `ь`, `ʼ`, Greek `α`, `σ`, or `t` on Romanian) 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 @@ -128,6 +128,15 @@ struct FullKeyboardSnapshotStage: View { case "accents": Self.accentKey == "e" ? "Prosz" : "Za" default: "Spóźnię się dziesięć minut, " } + case .czech: + return switch state { + case "inserted": "Přijdu o deset minut později, doma budu v 19:30. Začněte beze mě." + case "numbers": "Přijdu o deset minut později, doma budu v 19:3" + case "shift": "Přijdu o deset minut později. " + case "typing": "Přijdu o deset minut pozd" + case "accents": Self.accentKey == "r" ? "P" : "Ka" + default: "Přijdu o deset minut později, " + } case .romanian: return switch state { case "inserted": "Întârzii zece minute, ajung acasă la 19:30. Începeți fără mine." @@ -314,6 +323,7 @@ private struct FullKeyboardFixture: UIViewRepresentable { let ownLetters: [String: String] = switch FullKeyboardSnapshotStage.layout { case .polish: ["e": "ę", "a": "ą", "c": "ć", "l": "ł", "n": "ń", "o": "ó", "s": "ś", "z": "ż"] case .romanian: ["a": "ă", "i": "î", "s": "ș", "t": "ț"] + case .czech: ["e": "ě", "r": "ř", "u": "ů", "a": "á", "c": "č", "s": "š", "z": "ž", "y": "ý", "n": "ň"] case .greek: ["ε": "έ", "α": "ά", "ο": "ό", "η": "ή", "ι": "ί", "υ": "ύ", "ω": "ώ", "σ": "ς", "κ": "ϗ"] default: [:] } diff --git a/ios/HEXMobile/Localizable.xcstrings b/ios/HEXMobile/Localizable.xcstrings index 34bab2bf3..2ad38180a 100644 --- a/ios/HEXMobile/Localizable.xcstrings +++ b/ios/HEXMobile/Localizable.xcstrings @@ -930,6 +930,54 @@ } } }, + "Vocabulary" : { + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "词汇表" + } + } + } + }, + "Words autocorrect keeps and suggests" : { + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "自动更正会保留并推荐的词" + } + } + } + }, + "%lld words autocorrect keeps and suggests" : { + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld word autocorrect keeps and suggests" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld words autocorrect keeps and suggests" + } + } + } + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "自动更正会保留并推荐的 %lld 个词" + } + } + } + }, "Delete" : { "localizations" : { "zh-Hans" : { @@ -1260,6 +1308,16 @@ } } }, + "Hold a word you typed in the keyboard's suggestions to add it. Dictation spells these too while Custom vocabulary is on." : { + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在键盘的建议栏中按住你输入的词即可添加。打开“自定词汇”时,听写也会按这些拼写。" + } + } + } + }, "Fixes typos when you press space" : { "localizations" : { "zh-Hans" : { @@ -2409,6 +2467,26 @@ } } }, + "Add to vocabulary" : { + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "添加到词汇表" + } + } + } + }, + "Never autocorrected" : { + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "不会被自动更正" + } + } + } + }, "So Hex can hear you dictate" : { "localizations" : { "zh-Hans" : { diff --git a/ios/HEXMobile/SettingsPages.swift b/ios/HEXMobile/SettingsPages.swift index c4efe3d1a..41caf631e 100644 --- a/ios/HEXMobile/SettingsPages.swift +++ b/ios/HEXMobile/SettingsPages.swift @@ -222,7 +222,8 @@ private enum HexKeySide: CaseIterable { /// Settings › Keyboard: Full or Dictation bar, the full keyboard's rows (only while it's /// chosen; Auto-capitalization, on by default as Apple's, sits above Autocorrect; Spatial autocorrect only while Autocorrect is on, and Suggest swear words off by -/// default, as Apple's keyboard never offers them; Hex key, Right by default, under Languages), +/// default, as Apple's keyboard never offers them, then Vocabulary, Hex's list of your own +/// words; Hex key, Right by default, under Languages), /// and haptics, which the dictation bar uses too. Below, Swipe typing, which says it needs /// the full keyboard while the dictation bar is chosen, and Emoji (on by default, with Clear /// emoji history while it's on), the bar's emoji key too. @@ -335,6 +336,10 @@ struct KeyboardSettingsPage: View { SettingsDivider() + KeyboardVocabularyRow() + + SettingsDivider() + SettingsToggleRow( title: String(localized: "Key pop-ups"), detail: String(localized: "Shows the letter above your finger"), diff --git a/ios/HEXMobileTests/AutocorrectEngineTests.swift b/ios/HEXMobileTests/AutocorrectEngineTests.swift index 622390428..815572e54 100644 --- a/ios/HEXMobileTests/AutocorrectEngineTests.swift +++ b/ios/HEXMobileTests/AutocorrectEngineTests.swift @@ -160,6 +160,74 @@ final class AutocorrectEngineTests: XCTestCase { XCTAssertEqual(target.text, "i think i'm here ") } + /// TestFlight (build 56): "Even with auto-capitalization off, many suggested words are + /// capitalized." With it off the strip offers no capital you didn't type either, as space + /// puts none in: a guess or completion iOS knows capitalised ("Mandy", "Monday") and + /// "I'd" for "id" come lowercase; your own spellings (a vocabulary word, a contact) and a + /// capital you typed keep theirs. + func testAutoCapitalizationOffSuggestsNoCapitals() { + let engine = stubbed { + $0.valid = ["id", "money"] + $0.capitalised = ["Monday", "Mandy"] + $0.guessTable = ["mondy": ["Monday", "Mandy"]] + $0.completionTable = ["mon": ["Monday", "money"]] + } + engine.loadLexiconEntries([("Kimberly", "Kimberly")]) + engine.setVocabulary(["GitHub"]) + func strip(_ typed: String) -> [String] { + engine.suggestions(beforeInput: typed, field: .text, autocorrectionType: .default).dropFirst().map(\.replacement) + } + XCTAssertEqual(strip("mondy"), ["Monday", "Mandy"], "on: as the dictionary spells them") + engine.addsCapitals = false + XCTAssertEqual(strip("mondy"), ["monday", "mandy"]) + XCTAssertEqual(strip("id"), ["i'd"]) + XCTAssertEqual(Set(strip("mon")), ["money", "monday"]) + XCTAssertEqual(strip("git"), ["GitHub"], "your vocabulary's spelling") + XCTAssertEqual(strip("kim"), ["Kimberly"], "a contact's") + XCTAssertEqual(strip("Mondy"), ["Monday", "Mandy"], "a capital you typed") + func predictions(_ before: String) -> [String] { + engine.suggestions(beforeInput: before, field: .text, autocorrectionType: .default, capitalizesNext: true).map(\.replacement) + } + XCTAssertEqual(predictions(""), ["I", "the", "I'm"], "sentence starters: only \"I\", which always has one (#2135)") + XCTAssertEqual(predictions("well, "), ["I", "but", "and"], "clause starters") + engine.addsCapitals = true + XCTAssertEqual(predictions(""), ["I", "The", "I'm"]) + } + + /// TestFlight (build 56): "Custom dictionary for uncommon programmer slang." Hex's + /// vocabulary list (Settings › Keyboard › Vocabulary, the one dictation spells) reaches the + /// keys: its words are never autocorrected away, are spelled your way, are completed in + /// the strip, and a bilingual partner shares them. + func testVocabularyWordsAreKeptSpelledYourWayAndCompleted() { + let engine = stubbed { + $0.valid = ["deduce", "the"] + $0.guessTable = ["dedupe": ["deduce"]] + $0.completionTable = ["ded": ["deduce"]] + } + engine.setLanguage(.english, available: ["en_US", "fr_FR"]) + XCTAssertEqual(fix(engine, "dedupe"), "deduce", "not yet in the vocabulary") + engine.setVocabulary(["dedupe", "GitHub", "Claude Code"]) + XCTAssertNil(fix(engine, "dedupe")) + XCTAssertNil(fix(engine, "Dedupe")) + XCTAssertEqual(fix(engine, "github"), "GitHub") + XCTAssertNil(fix(engine, "GitHub")) + XCTAssertNil(fix(engine, "GITHUB")) + XCTAssertEqual(fix(engine, "claude"), "Claude", "a word of a phrase") + func strip(_ typed: String) -> [String] { + engine.suggestions(beforeInput: typed, field: .text, autocorrectionType: .default).map(\.replacement) + } + XCTAssertEqual(strip("dedupe"), ["dedupe"], "no guess for your word") + XCTAssertEqual(strip("ded").dropFirst().first, "dedupe", "completed before the dictionary's words") + XCTAssertEqual(strip("Cla").dropFirst().first, "Claude Code") + XCTAssertTrue(engine.ownWords.contains("dedupe"), "Swipe typing reads it") + let french = StubChecker() + french.valid = ["deduire"] + engine.setPartner(.french, available: ["en_US", "fr_FR"], checker: french) + XCTAssertEqual(engine.partner?.vocabulary, ["dedupe", "GitHub", "Claude Code"]) + XCTAssertNil(fix(engine, "dedupe"), "kept beside a partner") + XCTAssertEqual(fix(engine, "github"), "GitHub") + } + func testAmbiguousContractionsSuggestWithoutAutoReplacing() { let slots = engine.autocorrect.suggestions( beforeInput: "well", @@ -548,6 +616,64 @@ final class AutocorrectEngineTests: XCTestCase { XCTAssertNil(fix(greek, "και"), "a word stays") } + /// Czech types with iOS's cs dictionary, and háčky and čárky left out are the cheapest fix + /// there is, however many ("cesky" -> "český", "prilis" -> "příliš", "kun" -> "kůň"), as + /// Polish diacritics are; other languages keep one edit. The fixes run against a stub + /// dictionary answering as an iPhone's would. + func testCzechRestoresMissingDiacritics() { + XCTAssertEqual(AutocorrectEngine.singleEditKeyboardCost(from: "cesky", to: "český", language: .czech)!, 0.20, accuracy: 0.001) + XCTAssertEqual(AutocorrectEngine.singleEditKeyboardCost(from: "prilis", to: "příliš", language: .czech)!, 0.25, accuracy: 0.001) + XCTAssertEqual(AutocorrectEngine.singleEditKeyboardCost(from: "kun", to: "kůň", language: .czech)!, 0.20, accuracy: 0.001) + XCTAssertNil(AutocorrectEngine.singleEditKeyboardCost(from: "prilis", to: "příliš", language: .english), "three edits elsewhere") + engine.language = .czech + XCTAssertEqual(engine.autocorrect.language, .czech) + XCTAssertNil(engine.autocorrect.decoder, "no Czech typing model") + + let czech = stubbed { + $0.valid = ["český", "příliš", "kůň", "žluťoučký", "děkuji", "jsem", "dobrý", "den", "kun", "cesta"] + // "cesta" is one far key from "cesky" and listed first; "český" only lacks its čárka and háček. + $0.guessTable = ["cesky": ["cesta", "český"], "prilis": ["příliš"], "zlutoucky": ["žluťoučký"], "dekuji": ["děkuji"]] + } + czech.setLanguage(.czech, available: ["cs", "en_US"]) + XCTAssertEqual(fix(czech, "cesky"), "český") + XCTAssertEqual(fix(czech, "Cesky"), "Český") + XCTAssertEqual(fix(czech, "prilis"), "příliš") + XCTAssertEqual(fix(czech, "zlutoucky"), "žluťoučký") + XCTAssertEqual(fix(czech, "dekuji"), "děkuji") + XCTAssertNil(fix(czech, "jsem"), "a word stays") + XCTAssertEqual(AutocorrectEngine.sentenceStarters(.czech).count, 3) + } + + /// TestFlight (build 56): "Autocomplete suggests English words in Czech too." With Czech + /// and English chosen, a sentence the words before show is Czech (`languageLean`) gets + /// Czech completions only, none of English's even where Czech has none, and an English + /// sentence English's only; with nothing before, both languages' in turn, as before + /// (#2186). Autocorrect is #2186's: an English word stays as typed in a Czech sentence. + func testEnglishSuggestionsStayOutOfACzechSentence() { + let available = ["cs", "en_US"] + let czech = stubbed { + $0.valid = ["dobrý", "den", "jsem", "doma", "dnes", "děkuji", "dobře", "a", "do"] + $0.completionTable = ["do": ["doma", "dobře", "dobrý"], "de": ["den", "děkuji"]] + } + czech.setLanguage(.czech, available: available) + let english = StubChecker() + english.valid = ["i", "am", "at", "home", "today", "do", "dog", "done", "door", "the", "a"] + english.completionTable = ["do": ["dog", "done", "door"], "de": ["deal"], "kur": ["kurtosis", "kudos"]] + english.guessTable = ["dorr": ["door"]] + czech.setPartner(.english, available: available, checker: english) + XCTAssertEqual(czech.partner?.language, .english) + func strip(_ before: String) -> [String] { + Array(czech.suggestions(beforeInput: before, field: .text, autocorrectionType: .default).dropFirst().map(\.replacement)) + } + XCTAssertEqual(strip("dobrý den jsem do"), ["doma", "dobře"], "a Czech sentence: Czech words") + XCTAssertEqual(strip("dobrý den jsem kur"), [], "and no English ones where Czech has none") + XCTAssertEqual(strip("i am at home do"), ["dog", "done"], "an English sentence: English words") + XCTAssertEqual(strip("do"), ["doma", "dog"], "nothing before: both, in turn") + XCTAssertEqual(fix(czech, before: "i am at home dorr"), "door") + XCTAssertEqual(fix(czech, before: "dorr"), "door") + XCTAssertNil(fix(czech, before: "dobrý den jsem home"), "an English word stays as typed") + } + /// Serbian (Latin) has no dictionary on iOS: nothing is "corrected", into English or anything else. func testSerbianLatinWithoutADictionaryCorrectsNothing() { engine.language = .serbianLatin diff --git a/ios/HEXMobileTests/DictationControllerTests.swift b/ios/HEXMobileTests/DictationControllerTests.swift index 714df7981..1762f75a7 100644 --- a/ios/HEXMobileTests/DictationControllerTests.swift +++ b/ios/HEXMobileTests/DictationControllerTests.swift @@ -2274,6 +2274,30 @@ final class SpeechLanguagePickerTests: XCTestCase { XCTAssertEqual(SpeechLanguagePicker.shortNames(for: ["el-GR"], in: Locale(identifier: "en-US"))["el-GR"], "Greek") } + /// Czech is `DictationTranscriber`'s only (macOS 27.2.1 lists cs-CZ there and not in + /// `SpeechTranscriber`): picked by hand, by a Czech iPhone, or by the keyboard showing + /// Čeština, it dictates in Czech through Apple Speech, never English-only Parakeet. + func testCzechComesFromDictationTranscriber() async { + let speech = lookup(speechLocales) + let dictation = lookup(dictationLocales + ["cs-CZ"]) + let chosen = await SpeechLanguagePicker.pick( + explicit: "cs-CZ", candidates: ["en-US"], speech: speech, dictation: dictation + ) + XCTAssertEqual(chosen?.identifier, "cs-CZ") + XCTAssertEqual(chosen?.module, .dictation) + let automatic = await SpeechLanguagePicker.pick( + explicit: nil, + candidates: SpeechLanguagePicker.automaticCandidates(preferred: ["cs-CZ", "en-US"], current: "cs_CZ"), + speech: speech, + dictation: dictation + ) + XCTAssertEqual(automatic?.identifier, "cs-CZ") + XCTAssertEqual(automatic?.module, .dictation) + XCTAssertFalse(SpeechLanguagePicker.isEnglish("cs-CZ"), "Apple Speech, never English-only Parakeet") + XCTAssertEqual(SpeechLanguagePicker.shortNames(for: ["cs-CZ"], in: Locale(identifier: "en-US"))["cs-CZ"], "Czech") + XCTAssertEqual(KeyboardLanguage.czech.dictationLanguage(supported: ["en-US", "cs-CZ"], preferred: ["en-US"]), "cs-CZ") + } + func testThePreferredOrderWinsOverTheModule() async { // Hebrew first: DictationTranscriber's Hebrew beats SpeechTranscriber's English. let picked = await pick(preferred: ["he-IL", "en-US"]) diff --git a/ios/HEXMobileTests/FullKeyboardEngineTests.swift b/ios/HEXMobileTests/FullKeyboardEngineTests.swift index 70e2c52ce..978491a68 100644 --- a/ios/HEXMobileTests/FullKeyboardEngineTests.swift +++ b/ios/HEXMobileTests/FullKeyboardEngineTests.swift @@ -595,6 +595,86 @@ final class FullKeyboardEngineTests: XCTestCase { XCTAssertFalse(AutocorrectEngine.isSentenceStart("first; ")) } + /// TestFlight (build 56): "I use Czech and English." Settings › Keyboard › Languages with + /// English and Czech: the space bar says "Čeština", the keys are the system Czech keyboard's + /// (QWERTZ, the ´ and ˇ keys), and they type as observed there with real touches: ´ and ˇ + /// accent the letter before them (rˇ is ř, uˇ is ů, A´ is Á, but aˇ stays aˇ), and after + /// anything else type themselves; a held ˇ's ˚ makes ů and å; delete takes the accented letter whole. + /// English is its bilingual partner, and Switch dictation too dictates cs-CZ. + func testCzechTypesAndSwitches() { + let settings = LanguageSettings(defaults: defaults) + settings.keyboardLanguages = [.english, .czech] + settings.dictationFollowsKeyboard = true + settings.supportedDictationLanguages = ["en-US", "cs-CZ"] + 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.engine.autocorrect.isEnabled = false + view.switchLanguage(by: 1) + XCTAssertEqual(view.engine.language, .czech) + XCTAssertEqual(view.plane.spaceLabel, "Čeština") + XCTAssertNil(view.engine.autocorrect.decoder, "no Czech typing model: the dictionary engine") + XCTAssertEqual(settings.keyboardDictationLanguage(), "cs-CZ") + XCTAssertEqual(picked, [], "Automatic already follows") + var id = 600 + func tap(_ kind: KeyKind) { + let key = view.engine.layout.key(kind)! + 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 type(_ keys: String) { + for character in keys { tap(character == " " ? .space : .character(String(character))) } + } + 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)) + } + tap(.shift) + type("prˇi´lisˇ zˇlutˇoucˇky´ ku") + hold("ˇ", pick: "˚") + type("nˇ") + XCTAssertEqual(field.text, "Příliš žluťoučký kůň") + XCTAssertEqual(field.text.unicodeScalars.count, field.text.count, "precomposed letters, no combining marks") + tap(.delete) + XCTAssertEqual(field.text, "Příliš žluťoučký ků", "delete takes ň whole") + while field.hasText { tap(.delete) } + type("´ x´ aˇ e´´ ") + XCTAssertEqual(field.text, "´ x´ aˇ é´ ", "a mark with nothing to accent types itself") + type("a") + hold("ˇ", pick: "˚") + type("c") + hold("ˇ", pick: "ˇ") + type(" uˇ") + XCTAssertEqual(field.text, "´ x´ aˇ é´ åč ů") + tap(.shift) + type("a´") + tap(.shift) + type("uˇ") + XCTAssertTrue(field.text.hasSuffix("ÁŮ"), field.text) + // Apple's other Czech layout, "QWERTY – Czech/Slovak", keeps both keys and their rules. + XCTAssertEqual(KeyboardLanguage.czech.letterRows(.qwerty)[2].last, "ˇ") + view.switchLanguage(by: 1) + XCTAssertEqual(view.engine.language, .english) + XCTAssertEqual(view.plane.spaceLabel, "English") + XCTAssertNil(view.engine.layout.key(.character("ˇ")), "English has no ˇ key") + } + /// Settings › Keyboard › Languages with English, French and Russian: the space bar names /// the keyboard's language, switching changes the letters (AZERTY, ЙЦУКЕН), the accents and /// autocorrect (French with English beside it, Russian alone), and the keyboard comes back @@ -1468,12 +1548,13 @@ final class FullKeyboardEngineTests: XCTestCase { view.plane.ended(id: id + 10, sample: sample) } // Serbian's and Romanian's e hold nothing, as on the system keyboard; Serbian's c - // holds č and ć, Romanian's s ș. + // holds č and ć, Romanian's s ș. Czech's e opens with ě before e, so its r (ř). let held: String = switch language { case .ukrainian: "ʼ" case .russian: "е" case .serbianLatin: "c" case .romanian: "s" + case .czech: "r" case .greek: "ε" default: "e" } @@ -1785,6 +1866,18 @@ final class FullKeyboardEngineTests: XCTestCase { return (field, plane) } + /// Hex's vocabulary list reaches Swipe typing: a word no dictionary or model has + /// ("kubectl") is swiped once it's in the list. + func testSwipeTypesYourVocabularyWords() throws { + let (before, beforePlane) = try swipeKeyboard() + swipe("kubectl", on: beforePlane) + XCTAssertNotEqual(before.text, "kubectl", "not a word Swipe typing knows") + let (field, plane) = try swipeKeyboard() + plane.engine.autocorrect.setVocabulary(["kubectl"]) + swipe("kubectl", on: plane) + XCTAssertEqual(field.text, "kubectl") + } + private func sample(_ point: CGPoint) -> TypingLogTouchSample { TypingLogTouchSample(point: point, timestamp: 0) } diff --git a/ios/HEXMobileTests/KeyboardLayoutTests.swift b/ios/HEXMobileTests/KeyboardLayoutTests.swift index 53a2a3abe..5cc49c31f 100644 --- a/ios/HEXMobileTests/KeyboardLayoutTests.swift +++ b/ios/HEXMobileTests/KeyboardLayoutTests.swift @@ -574,6 +574,7 @@ final class KeyboardLayoutTests: XCTestCase { .ukrainian: ["йцукенгшщзхї", "фівапролджєʼ", "ячсмитьбюґ"], .greek: ["ερτυθιοπ´", "ασδφγηξκλ", "ζχψωβνμ"], .serbianLatin: ["qwertzuiop", "asdfghjkl", "yxcvbnm"], + .czech: ["qwertzuiop", "asdfghjkl´", "yxcvbnmˇ"], ] for (language, expected) in rows { let layout = KeyboardLayout(width: 402, language: language) @@ -604,6 +605,7 @@ final class KeyboardLayoutTests: XCTestCase { .russian: [.own], .ukrainian: [.own], .greek: [.own], + .czech: [.own, .qwerty], ] for language in KeyboardLanguage.allCases { XCTAssertEqual(language.letterLayouts, offered[language], "\(language)") @@ -614,17 +616,21 @@ final class KeyboardLayoutTests: XCTestCase { XCTAssertEqual(KeyboardLanguage.german.layoutName(.own), "QWERTZ – Deutsch") XCTAssertEqual(KeyboardLanguage.spanish.layoutName(.own), "QWERTY – Español") XCTAssertEqual(KeyboardLanguage.english.layoutName(.dvorak), "Dvorak") + XCTAssertEqual(KeyboardLanguage.czech.layoutName(.own), "QWERTZ – Čeština") + XCTAssertEqual(KeyboardLanguage.czech.layoutName(.qwerty), "QWERTY – Čeština") + XCTAssertEqual(KeyboardLanguage.polish.layoutName(.qwerty), "QWERTY") } /// The plain layouts are the same 26 letters in every language (iOS 27.0 simulator: English, - /// German, French, Spanish, Italian, Portuguese, Polish, Serbian and Romanian alike). + /// German, French, Spanish, Italian, Portuguese, Polish, Serbian and Romanian alike), but + /// Czech, whose QWERTY is its own with Z and Y swapped (`testCzechsRowsAndPagesMatchApples`). func testPlainLayoutsAreApplesInEveryLanguage() { let plain: [KeyboardLetterLayout: [String]] = [ .qwerty: ["qwertyuiop", "asdfghjkl", "zxcvbnm"], .qwertz: ["qwertzuiop", "asdfghjkl", "yxcvbnm"], .azerty: ["azertyuiop", "qsdfghjklm", "wxcvbn"], ] - for language in KeyboardLanguage.allCases { + for language in KeyboardLanguage.allCases where language != .czech { for letters in language.letterLayouts where letters != .own && letters != .dvorak { let layout = KeyboardLayout(width: 402, language: language, letters: letters) for row in 0..<3 { @@ -906,6 +912,42 @@ final class KeyboardLayoutTests: XCTestCase { } } + /// The standard Czech layout in the rows the system Czech keyboard ("QWERTZ – Czech/Slovak") + /// shows on an iPhone 17 Pro (iOS 27.2 simulator, 402 pt, read through accessibility): rows + /// 1 and 2 are ten letter-wide keys edge to edge, the ´ key ending row 2 under P; row 3 is + /// shift, Y to M and the ˇ key, and delete, each a letter wide, Y under S. Its 123 and #+= + /// pages are English's. "QWERTY – Czech/Slovak" is the same with Z and Y swapped. + @MainActor + func testCzechsRowsAndPagesMatchApples() throws { + for width in portraitWidths { + let layout = KeyboardLayout(width: width, language: .czech) + let english = KeyboardLayout(width: width) + XCTAssertEqual(layout.characterWidth, english.characterWidth, accuracy: 0.001) + for row in 0..<2 { + let keys = layout.keys.filter { $0.row == row }.sorted { $0.frame.minX < $1.frame.minX } + XCTAssertEqual(keys.count, 10, "\(width)") + XCTAssertEqual(keys.first!.frame.minX, layout.metrics.side, accuracy: 0.001) + XCTAssertEqual(keys.last!.frame.maxX, width - layout.metrics.side, accuracy: 0.001) + } + XCTAssertEqual(layout.key(.character("´"))!.frame.minX, layout.key(.character("p"))!.frame.minX, accuracy: 0.001) + XCTAssertEqual(layout.key(.character("y"))!.frame.minX, layout.key(.character("s"))!.frame.minX, accuracy: 0.001) + XCTAssertEqual(layout.key(.character("ˇ"))!.frame.minX, layout.key(.character("o"))!.frame.minX, accuracy: 0.001) + XCTAssertEqual(layout.key(.shift)!.frame.width, layout.characterWidth, accuracy: 0.001) + XCTAssertEqual(layout.key(.delete)!.frame.maxX, width - layout.metrics.side, accuracy: 0.001) + XCTAssertEqual(layout.keys.filter { $0.row == 3 }.map(\.frame), english.keys.filter { $0.row == 3 }.map(\.frame)) + } + XCTAssertEqual(Array("´ˇ˚".unicodeScalars).map(\.value), [0x00B4, 0x02C7, 0x02DA]) + let qwerty = KeyboardLayout(width: 402, language: .czech, letters: .qwerty) + XCTAssertEqual((0..<3).map { letters(qwerty, row: $0).joined() }, ["qwertyuiop", "asdfghjkl´", "zxcvbnmˇ"]) + XCTAssertTrue(AutocorrectEngine.areAdjacentKeys("z", "t", language: .czech)) + XCTAssertTrue(AutocorrectEngine.areAdjacentKeys("y", "s", language: .czech)) + XCTAssertFalse(AutocorrectEngine.areAdjacentKeys("y", "t", language: .czech)) + XCTAssertTrue(AutocorrectEngine.areAdjacentKeys("y", "t", language: .czech, letters: .qwerty)) + for layer in [KeyboardLayer.numbers, .symbols] { + XCTAssertEqual(KeyboardLayout(width: 402, layer: layer, language: .czech).keys, KeyboardLayout(width: 402, layer: layer).keys) + } + } + /// Apple's AZERTY on the tester's iPhone 17 Pro (402 pt; their French and English /// keyboard): rows 1 and 2 run edge to edge, W to N sit under E to I, and shift and /// delete keep their English size with a gap beside them. A tap in that gap goes to the @@ -1115,6 +1157,29 @@ final class KeyboardLayoutTests: XCTestCase { ["\"", "„", "”", "»", "«", "“"] ) XCTAssertEqual(AccentCatalog.options(for: "$", uppercase: false, language: .romanian), AccentCatalog.options(for: "$", uppercase: false)) + // Czech: every Czech letter held on its base (á č ď é ě í ň ó ř š ť ú ů ý ž), the ring ˚ + // on the ˇ key, nothing on the ´ key or the letters not listed; callouts laid out as + // the system's, and every symbol's hold English's. + XCTAssertEqual(AccentCatalog.options(for: "e", uppercase: false, language: .czech), ["e", "ě", "é", "ê", "è", "ę", "ë", "ē", "ė"]) + XCTAssertEqual(AccentCatalog.options(for: "u", uppercase: true, language: .czech), ["U", "Ú", "Ů", "Û", "Ü", "Ù", "Ū"]) + XCTAssertEqual(AccentCatalog.options(for: "ˇ", uppercase: false, language: .czech), ["ˇ", "˚"]) + XCTAssertNil(AccentCatalog.options(for: "´", uppercase: false, language: .czech)) + let czech: Set = ["e", "r", "t", "z", "u", "i", "o", "a", "s", "d", "l", "y", "c", "n", "ˇ"] + for letter in KeyboardLanguage.czech.letterRows.joined() where !czech.contains(letter) { + XCTAssertNil(AccentCatalog.options(for: letter, uppercase: false, language: .czech), letter) + } + for word in ["á", "č", "ď", "é", "ě", "í", "ň", "ó", "ř", "š", "ť", "ú", "ů", "ý", "ž"] { + let base = String(word.decomposedStringWithCanonicalMapping.unicodeScalars.prefix(1).map(Character.init)) + XCTAssertTrue(AccentCatalog.options(for: base, uppercase: false, language: .czech)?.contains(word) == true, word) + } + XCTAssertEqual(AccentCatalog.arrangement(for: "e", uppercase: false, language: .czech), AccentArrangement(rows: [["ě", "e", "é", "ê", "è", "ę", "ë", "ē", "ė"]], baseRow: 0, baseColumn: 1)) + XCTAssertEqual(AccentCatalog.arrangement(for: "z", uppercase: false, language: .czech)?.rows, [["z", "ž", "ź", "ż"]]) + XCTAssertEqual(AccentCatalog.arrangement(for: "n", uppercase: true, language: .czech), AccentArrangement(rows: [["Ń", "Ñ", "Ň", "N"]], baseRow: 0, baseColumn: 3)) + XCTAssertEqual(AccentCatalog.arrangement(for: "ˇ", uppercase: false, language: .czech)?.rows, [["ˇ", "˚"]]) + for symbol in ["$", "\"", "'", "0", "&", "-", "?"] { + XCTAssertEqual(AccentCatalog.options(for: symbol, uppercase: false, language: .czech), AccentCatalog.options(for: symbol, uppercase: false), symbol) + XCTAssertEqual(AccentCatalog.arrangement(for: symbol, uppercase: false, language: .czech), AccentCatalog.arrangement(for: symbol, uppercase: false), symbol) + } } func testAccentMenusOnTheNewKeysStayInside() { @@ -1128,6 +1193,7 @@ final class KeyboardLayoutTests: XCTestCase { .polish: ["a", "c", "e", "l", "n", "o", "s", "z"], .romanian: ["a", "i", "s", "t"], .greek: ["ε", "υ", "ι", "ο", "α", "σ", "η", "κ", "ω"], + .czech: ["e", "r", "t", "z", "u", "i", "o", "a", "s", "d", "l", "y", "c", "n", "ˇ"], ] for width in portraitWidths { for (language, characters) in keys { @@ -1189,6 +1255,13 @@ final class KeyboardLayoutTests: XCTestCase { XCTAssertEqual(automatic("el_GR"), .greek) XCTAssertEqual(automatic(nil, modes: ["emoji", "el_GR", "en-US"]), .greek) XCTAssertEqual(automatic("en-US", modes: ["el-GR"]), .english, "the dictation language still wins") + XCTAssertEqual(automatic("cs-CZ", modes: ["en-US"]), .czech) + XCTAssertEqual(automatic("cs_CZ"), .czech) + XCTAssertEqual(automatic(nil, modes: ["emoji", "cs_CZ", "en-US"]), .czech) + XCTAssertEqual(automatic(nil, preferred: ["cs-CZ", "en-US"]), .czech) + XCTAssertEqual(automatic("sk-SK"), .english, "Slovak has no layout of its own here") + XCTAssertEqual(KeyboardLanguage.czech.dictationLanguage(supported: ["en-US", "cs-CZ"], preferred: ["cs-CZ"]), "cs-CZ") + XCTAssertEqual(KeyboardLanguage.czech.dictationLanguage(supported: [], preferred: []), "cs-CZ") // 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) @@ -1250,6 +1323,9 @@ final class KeyboardLayoutTests: XCTestCase { 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") + XCTAssertEqual(partner([.czech, .english], .czech, ["en_US", "cs"]), .english, "Czech has Latin letters") + XCTAssertEqual(partner([.english, .czech], .english, ["en_US", "cs"]), .czech) + XCTAssertEqual(KeyboardLanguageList.resolve(chosen: [.english, .czech], stored: .czech, automatic: .english).layout, .czech, "Czech types on its own keys") XCTAssertNil(partner([.english], .english)) } diff --git a/ios/HEXMobileTests/TranscriptCleanupTests.swift b/ios/HEXMobileTests/TranscriptCleanupTests.swift index e42e92bec..37a20f23d 100644 --- a/ios/HEXMobileTests/TranscriptCleanupTests.swift +++ b/ios/HEXMobileTests/TranscriptCleanupTests.swift @@ -567,6 +567,26 @@ final class SpokenCleanupRulesTests: XCTestCase { ) } + /// Czech as `DictationTranscriber` writes it (macOS 27.2.1, Zuzana voice: háčky and čárky + /// kept, no punctuation, numbers as digits): Polished capitalizes and ends it, Casual + /// starts each sentence lowercase, and Lowercase lowers Á Č Ď É Ě Í Ň Ó Ř Š Ť Ú Ů Ý Ž. + func testCzechStylesAndLowercase() { + let heard = "dobrý den přijdu o 10 minut později budu doma v 19:30 začněte beze mne" + XCTAssertEqual( + TranscriptFormatter.format(heard, style: .polished, language: "cs-CZ"), + "Dobrý den přijdu o 10 minut později budu doma v 19:30 začněte beze mne." + ) + XCTAssertEqual(TranscriptFormatter.format("příliš žluťoučký kůň", style: .polished, language: "cs-CZ"), "Příliš žluťoučký kůň.") + XCTAssertEqual(TranscriptFormatter.format("Čau. Úterý.", style: .casual, language: "cs-CZ"), "čau. úterý") + XCTAssertEqual(TranscriptFormatter.format("Žluťoučký kůň.", style: .verbatim, language: "cs-CZ"), "Žluťoučký kůň.") + var pipeline = DictationPipeline(style: .polished, language: "cs-CZ", vocabulary: []) + pipeline.lowercase = true + XCTAssertEqual( + pipeline.format("ÁČĎ ÉĚÍ ŇÓŘ ŠŤÚ ŮÝŽ", language: "cs-CZ"), + "áčď éěí ňóř šťú ůýž." + ) + } + /// Greek as `DictationTranscriber` writes it (macOS 27.2, Melina voice: tonos kept, no /// punctuation, numbers as digits): Polished capitalizes and ends it, Casual starts each /// sentence lowercase, and Lowercase lowers accented capitals (Ά Έ Ή Ί Ό Ύ Ώ Ϊ Ϋ) and diff --git a/ios/HEXShared/FullKeyboard/AccentPicker.swift b/ios/HEXShared/FullKeyboard/AccentPicker.swift index 1cb734b25..3042515f2 100644 --- a/ios/HEXShared/FullKeyboard/AccentPicker.swift +++ b/ios/HEXShared/FullKeyboard/AccentPicker.swift @@ -111,11 +111,20 @@ nonisolated enum AccentCatalog { "η": "η ή", "κ": "κ ϗ", "ω": "ω ώ", "\"": "„ “ ” « » \"", ]) { _, greek in greek } + /// The Czech keyboard's (iOS 27.2 simulator, QWERTZ – Czech/Slovak), one row each; its + /// symbols are English's. + private static let czechOrder: [String: String] = englishOrder.filter { $0.key.first?.isLetter != true }.merging([ + "e": "ě e é ê è ę ë ē ė", "r": "r ř ŕ", "t": "t ť", "z": "z ž ź ż", "u": "ū ù ü û ů ú u", + "i": "ī į ì ï î í i", "o": "ō ø œ õ ò ö ô ó o", "a": "a á à ą â ä æ ã å ā", "s": "s š ß ś", + "d": "d ď", "l": "ĺ ľ ł l", "y": "y ý ÿ", "c": "c č ç ć", "n": "ń ñ ň n", "\u{02C7}": "\u{02C7} \u{02DA}", + ]) { _, czech in czech } + private static func displayOrder(for language: KeyboardLanguage) -> [String: String] { switch language { case .english: englishOrder case .spanish: spanishOrder case .greek: greekOrder + case .czech: czechOrder default: [:] } } diff --git a/ios/HEXShared/FullKeyboard/AutocorrectEngine+Distance.swift b/ios/HEXShared/FullKeyboard/AutocorrectEngine+Distance.swift index 2e0ff9c8e..290dd43c8 100644 --- a/ios/HEXShared/FullKeyboard/AutocorrectEngine+Distance.swift +++ b/ios/HEXShared/FullKeyboard/AutocorrectEngine+Distance.swift @@ -1,8 +1,9 @@ import Foundation -/// Case matching and the keyboard-distance cost of a one-edit typo: what cautious autocorrect, -/// bilingual choices, and the strip's spelling guesses measure a slip by. Kept beside the -/// engine so its own file stays under the cap. +/// Case matching (with the strip's and a fix's capitals, and the word before a token) and the +/// keyboard-distance cost of a one-edit typo: what cautious autocorrect, bilingual choices, +/// and the strip's spelling guesses measure a slip by. Kept beside the engine so its own file +/// stays under the cap. @MainActor extension AutocorrectEngine { // MARK: - Case matching & QWERTY distance @@ -25,6 +26,47 @@ extension AutocorrectEngine { return target } + /// `word` without a capital first letter it only has from where it was learned: a fix + /// you picked at the start of a sentence ("Helli" to "Hello"), a guess iOS knows + /// capitalised, a Contacts name that is also a common word ("Bell", "Will"). When `typed` + /// starts in lowercase and the dictionary knows the word in lowercase, it is written in + /// lowercase, as Apple's keyboard writes "bell" mid-sentence beside a contact Kate Bell + /// (black box, iOS 27.2). Names the dictionary knows only capitalised ("Taylor"), "I" and + /// its contractions, words with more capitals ("iPhone") and German, whose nouns take + /// capitals, keep theirs. + func withoutStrayCapital(_ word: String, typed: String) -> String { + guard language != .german, hasDictionary, typed.first?.isUppercase != true, word.count >= 2, + let first = word.first, first.isUppercase, !word.dropFirst().contains(where: \.isUppercase), + !word.contains(" ") else { return word } + let lower = first.lowercased() + word.dropFirst() + if language.usesEnglishFixes, lower.hasPrefix("i'") || lower.hasPrefix("i\u{2019}") { return word } + return checker.isWordValid(lower) ? lower : word + } + + /// The word before `token` in `before`, lowercased, when only spaces separate them + /// (nil at the start of a sentence or after punctuation). + static func previousWord(_ before: String, token: String) -> String? { + var rest = before.hasSuffix(token) ? before.dropLast(token.count) : Substring(before) + guard rest.last == " " else { return nil } + while rest.last == " " { rest = rest.dropLast() } + var word = "" + while let c = rest.last, c.isLetter || c == "'" { + word.insert(c, at: word.startIndex) + rest = rest.dropLast() + } + return word.isEmpty ? nil : word.lowercased() + } + + /// The strip's words for `token` with Auto-capitalization off: no capital you didn't type, + /// as space puts none in ("Mandy" and "I'd" come "mandy" and "i'd"), except your own + /// spellings; a word that is then what you typed, or twice there, goes. + func withoutAddedCapitals(_ pool: [String], typed token: String) -> [String] { + guard !addsCapitals, !token.contains(where: \.isUppercase) else { return pool } + return pool.map { isOwnSpelling($0) ? $0 : $0.lowercased() }.reduce(into: []) { kept, item in + if item != token, !kept.contains(item) { kept.append(item) } + } + } + /// Returns a weighted cost if `source` and `target` are within 1 Damerau-Levenshtein edit; `nil` otherwise. static func singleEditKeyboardCost( from source: String, @@ -38,9 +80,10 @@ extension AutocorrectEngine { // 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. Greek // likewise: a tonos or diaeresis left out ("καλημερα" -> "καλημέρα", "αυπνια" -> - // "αϋπνία"), or σ where the word ends in ς ("λογοσ" -> "λόγος"). - if language == .polish || language == .greek, s.count == t.count { - let same = language == .polish ? samePolishLetterIgnoringDiacritics : sameGreekLetterIgnoringAccents + // "αϋπνία"), or σ where the word ends in ς ("λογοσ" -> "λόγος"). Czech too: háčky and + // čárky left out ("cesky" -> "český", "prilis" -> "příliš"). + if language == .polish || language == .greek || language == .czech, s.count == t.count { + let same = language == .greek ? sameGreekLetterIgnoringAccents : samePolishLetterIgnoringDiacritics let missed = zip(s, t).filter { $0 != $1 } if !missed.isEmpty, missed.allSatisfy({ same($0, $1) }) { return 0.15 + 0.05 * Double(missed.count - 1) diff --git a/ios/HEXShared/FullKeyboard/AutocorrectEngine+Vocabulary.swift b/ios/HEXShared/FullKeyboard/AutocorrectEngine+Vocabulary.swift new file mode 100644 index 000000000..f6f334003 --- /dev/null +++ b/ios/HEXShared/FullKeyboard/AutocorrectEngine+Vocabulary.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Hex's vocabulary list (`CustomVocabularySettings.terms`) as the keys use it: programmer +/// slang, names and other words the dictionary doesn't know are kept as typed, spelled your +/// way ("github" -> "GitHub"), completed in the strip and read by Swipe typing. +@MainActor +extension AutocorrectEngine { + /// The words your vocabulary adds to your own: each term, and each word of a phrase. + static func vocabularyWords(_ terms: [String]) -> [String] { + var words: [String] = [] + for term in terms { + words.append(term) + if term.contains(" ") { words += term.split(separator: " ").map(String.init) } + } + return words + } + + /// The vocabulary word `token` spells, whatever its capitals; nil when it isn't one. + func vocabularyTerm(for token: String) -> String? { + guard !vocabulary.isEmpty else { return nil } + return Self.vocabularyWords(vocabulary).first { $0.caseInsensitiveCompare(token) == .orderedSame } + } + + /// What space puts in for `token`, a vocabulary word: your spelling, with a capital you + /// typed first ("github" -> "GitHub", "Kubectl" stays); nil when that is what you typed. + static func vocabularySpelling(of token: String, as term: String) -> String? { + let spelled = matchCase(of: token, onto: term) + return spelled == token ? nil : spelled + } + + /// Your vocabulary's first term that starts with `token` (two letters or more) and is + /// longer, cased as `token` starts. + func vocabularyCompletion(for token: String) -> String? { + guard token.count >= 2, !vocabulary.isEmpty else { return nil } + let lower = token.lowercased() + guard let term = vocabulary.first(where: { $0.count > token.count && $0.lowercased().hasPrefix(lower) }) else { return nil } + return Self.matchCase(of: token, onto: term) + } +} diff --git a/ios/HEXShared/FullKeyboard/AutocorrectEngine.swift b/ios/HEXShared/FullKeyboard/AutocorrectEngine.swift index 9d5e44894..0b5a78a44 100644 --- a/ios/HEXShared/FullKeyboard/AutocorrectEngine.swift +++ b/ios/HEXShared/FullKeyboard/AutocorrectEngine.swift @@ -198,7 +198,10 @@ final class AutocorrectEngine { private(set) var layoutLanguage: KeyboardLanguage = .english private(set) var layoutLetters: KeyboardLetterLayout? private var lexiconShortcuts: [String: String] = [:] - private var lexiconTerms: [String] = [] + /// Your `UILexicon` terms, then your vocabulary's words (`AutocorrectEngine+Vocabulary`). + private(set) var lexiconTerms: [String] = [] + private var systemLexiconTerms: [String] = [] + private(set) var vocabulary: [String] = [] private var suppressedInSession: Set = [] /// Learn how I type: typos you fixed the same way twice and words you turned down twice. private(set) var learning = TypingLearning() @@ -313,11 +316,22 @@ final class AutocorrectEngine { } } lexiconShortcuts = shortcuts - lexiconTerms = terms + systemLexiconTerms = terms + lexiconTerms = terms + Self.vocabularyWords(vocabulary) userWordsRevision += 1 partner?.loadLexiconEntries(entries) } + /// Hex's vocabulary list for typing (`AutocorrectEngine+Vocabulary`). + func setVocabulary(_ terms: [String]) { + guard terms != vocabulary else { return } + vocabulary = terms + lexiconTerms = systemLexiconTerms + Self.vocabularyWords(terms) + userWordsRevision += 1 + decoderCache = nil + partner?.setVocabulary(terms) + } + /// Your text replacement for `token`, cased as Apple's keyboard writes it (black box, iOS /// 27.2): a shortcut typed with a leading capital, yours or auto-capitalisation's ("Brb"), /// capitalises the replacement's first letter ("Be right back"); one typed in lowercase or @@ -424,6 +438,8 @@ final class AutocorrectEngine { engine.layoutLanguage = layoutLanguage engine.layoutLetters = layoutLetters engine.lexiconShortcuts = lexiconShortcuts + engine.systemLexiconTerms = systemLexiconTerms + engine.vocabulary = vocabulary engine.lexiconTerms = lexiconTerms if !learnsPerLanguage { engine.learning = learning } engine.allowsSwearing = allowsSwearing @@ -541,6 +557,7 @@ final class AutocorrectEngine { case .italian: ["io", "il", "la"] case .portuguese: ["eu", "o", "a"] case .polish: ["ja", "to", "nie"] + case .czech: ["to", "já", "ale"] case .romanian: ["eu", "nu", "am"] case .norwegian: ["jeg", "det", "vi"] case .russian: ["я", "это", "мы"] @@ -563,6 +580,7 @@ final class AutocorrectEngine { case .italian: ["e", "ma", "che"] case .portuguese: ["e", "mas", "que"] case .polish: ["a", "ale", "że"] + case .czech: ["a", "ale", "že"] case .romanian: ["și", "dar", "că"] case .norwegian: ["og", "men", "jeg"] case .russian: ["и", "но", "что"] @@ -582,6 +600,7 @@ final class AutocorrectEngine { 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 .czech: ["a", "se", "je", "v", "na", "to"] case .romanian: ["de", "și", "în", "nu", "să", "la"] case .norwegian: ["og", "i", "det", "er", "på", "som"] case .russian: ["и", "в", "не", "на", "я", "что"] @@ -671,18 +690,21 @@ final class AutocorrectEngine { // first; spelling guesses only for a word neither knows. let mine = candidates(for: token, autoFix: autoFix, guesses: !partner.knowsAsTyped(token), limit: 2, model: predictionModel, corrects: isEnabled) let theirs = partner.candidates(for: token, autoFix: autoFix, guesses: !knowsAsTyped(token), limit: 2, model: partner.decoder?.model, corrects: isEnabled) - let leansPartner = languageLean(partner, token: token) > 0 - let (first, second) = leansPartner ? (theirs, mine) : (mine, theirs) - for index in 0.. 0 ? [theirs] + : (0..= 2 { - let valid = Self.shorthandAllowlist.contains(lower) || learnedWords.contains(lower) || checker.isWordValid(token) - if !valid { + if !knowsAsTyped(token) { for guess in rankedGuesses(for: token) { let fixed = cased(guess, typed: token) if fixed.caseInsensitiveCompare(token) != .orderedSame, mayOffer(guess, replacing: token), !has(fixed) { @@ -842,6 +865,10 @@ final class AutocorrectEngine { lastFixLanguage = nil return shortcut } + if let term = vocabularyTerm(for: token) { + lastFixLanguage = nil + return Self.vocabularySpelling(of: token, as: term) + } // This language's own accented spelling decides before any partner logic: the table // only holds plain spellings that are no word of this language ("perche" -> "perché"), // so an English lean must not hand it to the other dictionary's guess. @@ -1126,23 +1153,6 @@ final class AutocorrectEngine { withoutStrayCapital(Self.matchCase(of: token, onto: candidate), typed: token) } - /// `word` without a capital first letter it only has from where it was learned: a fix - /// you picked at the start of a sentence ("Helli" to "Hello"), a guess iOS knows - /// capitalised, a Contacts name that is also a common word ("Bell", "Will"). When `typed` - /// starts in lowercase and the dictionary knows the word in lowercase, it is written in - /// lowercase, as Apple's keyboard writes "bell" mid-sentence beside a contact Kate Bell - /// (black box, iOS 27.2). Names the dictionary knows only capitalised ("Taylor"), "I" and - /// its contractions, words with more capitals ("iPhone") and German, whose nouns take - /// capitals, keep theirs. - func withoutStrayCapital(_ word: String, typed: String) -> String { - guard language != .german, hasDictionary, typed.first?.isUppercase != true, word.count >= 2, - let first = word.first, first.isUppercase, !word.dropFirst().contains(where: \.isUppercase), - !word.contains(" ") else { return word } - let lower = first.lowercased() + word.dropFirst() - if language.usesEnglishFixes, lower.hasPrefix("i'") || lower.hasPrefix("i\u{2019}") { return word } - return checker.isWordValid(lower) ? lower : word - } - /// `fix` for `token` as autocorrect puts it in: with `addsCapitals` off and nothing /// typed in capitals, all lowercase unless it is your own spelling; nil when that leaves /// just what you typed ("i"). @@ -1409,20 +1419,6 @@ final class AutocorrectEngine { decoderCache = nil } - /// The word before `token` in `before`, lowercased, when only spaces separate them - /// (nil at the start of a sentence or after punctuation). - static func previousWord(_ before: String, token: String) -> String? { - var rest = before.hasSuffix(token) ? before.dropLast(token.count) : Substring(before) - guard rest.last == " " else { return nil } - while rest.last == " " { rest = rest.dropLast() } - var word = "" - while let c = rest.last, c.isLetter || c == "'" { - word.insert(c, at: word.startIndex) - rest = rest.dropLast() - } - return word.isEmpty ? nil : word.lowercased() - } - /// A `UITextChecker` guess as autocorrect and the strip may use it, or nil. A guess adds /// no character you didn't type but letters and a contraction's apostrophe (never "t.b." /// for "tb"). One that splits what you typed into two words ("up-to" or "up to" for diff --git a/ios/HEXShared/FullKeyboard/CzechTyping.swift b/ios/HEXShared/FullKeyboard/CzechTyping.swift new file mode 100644 index 000000000..f2544c0d9 --- /dev/null +++ b/ios/HEXShared/FullKeyboard/CzechTyping.swift @@ -0,0 +1,67 @@ +import Foundation + +/// The Czech layout's ´ and ˇ keys, as the system Czech keyboard was observed to apply them +/// (iOS 27.2 simulator, real touches in Messages, every letter followed by each key, black box). +/// Neither is a dead key: each accents the letter right before it, as Greek's tonos key does, +/// and after anything else (another letter, an accented one, a space, nothing) types itself. +/// ´ gives á ć é í ĺ ń ó ŕ ś ú ý ź; ˇ gives č ď ě ľ ň ř š ť ž, and ů after u; the ring ˚, held on +/// ˇ, gives ů and å. Capitals take theirs (Á, Č, Ů). Delete takes the accented letter whole. +nonisolated enum CzechTyping { + static let acuteKey = "\u{00B4}" + static let caronKey = "\u{02C7}" + static let ringKey = "\u{02DA}" + + private static let marks: [String: [Character: Character]] = [ + acuteKey: [ + "a": "á", "c": "ć", "e": "é", "i": "í", "l": "ĺ", "n": "ń", "o": "ó", "r": "ŕ", "s": "ś", + "u": "ú", "y": "ý", "z": "ź", + ], + caronKey: [ + "c": "č", "d": "ď", "e": "ě", "l": "ľ", "n": "ň", "r": "ř", "s": "š", "t": "ť", "z": "ž", + "u": "ů", + ], + ringKey: ["a": "å", "u": "ů"], + ] + + /// The letter `before` ends with, accented by the mark `text` types after it; nil when + /// the key types the mark itself. + static func accenting(_ text: String, after before: String?) -> String? { + guard let table = marks[text], let last = before?.last else { return nil } + let lower = Character(last.lowercased()) + guard let accented = table[lower] else { return nil } + return last.isUppercase ? accented.uppercased() : String(accented) + } +} + +@MainActor +extension FullKeyboardEngine { + /// The layout's own keys' typing rules: Greek's tonos key and final sigma (`GreekTyping`), + /// Czech's ´ and ˇ (`CzechTyping`). True when the key already did all it does; else + /// `text` is what to type. + func typeLayoutRules(_ text: inout String) -> Bool { + switch layout.language { + case .greek: typeGreek(&text) + case .czech: typeCzech(text) + default: false + } + } + + /// Czech: a held ˇ's ˇ or ˚ accents the letter before it, as a tapped ˇ does. True when it + /// did; else the held key's choice goes in as it is. + func typeHeldMark(_ chosen: String) -> Bool { + guard layout.language == .czech else { return false } + var mark = chosen + return typeLayoutRules(&mark) + } + + /// ´, ˇ or ˚ after a letter it accents: puts the accented letter in its place. False + /// otherwise, and the mark is typed as itself. + private func typeCzech(_ text: String) -> Bool { + guard let accented = CzechTyping.accenting(text, after: target.documentContextBeforeInput) else { return false } + target.deleteBackward() + target.insertText(accented) + didEdit() + logState("typed") + return true + } +} diff --git a/ios/HEXShared/FullKeyboard/FullKeyboardEngine.swift b/ios/HEXShared/FullKeyboard/FullKeyboardEngine.swift index bf0ebc6e4..5afbee783 100644 --- a/ios/HEXShared/FullKeyboard/FullKeyboardEngine.swift +++ b/ios/HEXShared/FullKeyboard/FullKeyboardEngine.swift @@ -989,7 +989,7 @@ final class FullKeyboardEngine { if layerState.layer == .letters { shift.didType() } - if layerState.layer == .letters, layout.language == .greek, typeGreek(&text) { return } + if layerState.layer == .letters, typeLayoutRules(&text) { return } if dropsSuggestionSpace(before: text) || !correctWord(endingWith: text) { insert(text, source: "key", at: point) } @@ -1197,6 +1197,7 @@ final class FullKeyboardEngine { if layerState.layer == .letters { shift.didType() } + if layerState.layer == .letters, typeHeldMark(chosen) { return } insert(chosen, source: "accent") logState("typed") } diff --git a/ios/HEXShared/FullKeyboard/FullKeyboardView+Vocabulary.swift b/ios/HEXShared/FullKeyboard/FullKeyboardView+Vocabulary.swift new file mode 100644 index 000000000..db40f6edc --- /dev/null +++ b/ios/HEXShared/FullKeyboard/FullKeyboardView+Vocabulary.swift @@ -0,0 +1,45 @@ +import UIKit + +/// Add to vocabulary from the strip: hold the word you typed (the strip's left slot) and the +/// strip offers it; the chip adds it to Hex's vocabulary list (`CustomVocabularySettings`, +/// the one Settings › Keyboard › Vocabulary and Settings › Dictation edit), which the keys +/// then never autocorrect away, complete and swipe. +@MainActor +extension FullKeyboardView { + func offerVocabulary(_ suggestion: KeyboardSuggestion) { + var word = suggestion.replacement + // A capital only the sentence's start gave it ("Kubectl" opening a message) isn't its own. + if let first = word.first, first.isUppercase, !word.dropFirst().contains(where: \.isUppercase), + AutocorrectEngine.startsSentence(before: engine.target.documentContextBeforeInput ?? "", token: word) { + word = first.lowercased() + word.dropFirst() + } + guard suggestion.kind == .keepLiteral, engine.autocorrect.vocabularyTerm(for: word) == nil, + VocabularySpelling.normalizedKey(word).count >= 2 else { return } + typingLog?.ui("vocabulary_offer") + selectionFeedback() + vocabularyOffer = word + refreshStrip() + } + + var vocabularyNotice: KeyboardStripNotice? { + guard let word = vocabularyOffer else { return nil } + return KeyboardStripNotice( + title: "“\(word)”", + detail: String(localized: "Never autocorrected"), + button: String(localized: "Add to vocabulary") + ) + } + + /// Saves `word` in the App Group (kept for this session too where the keyboard can't + /// write there, without Full Access) and uses it at once. + func addToVocabulary(_ word: String) { + typingLog?.ui("vocabulary_add") + let settings = CustomVocabularySettings() + let terms = CustomVocabularySettings.sanitize(settings.terms + engine.autocorrect.vocabulary + [word]) + settings.terms = terms + engine.autocorrect.setVocabulary(terms) + vocabularyOffer = nil + engine.refreshSuggestions() + refreshStrip() + } +} diff --git a/ios/HEXShared/FullKeyboard/FullKeyboardView.swift b/ios/HEXShared/FullKeyboard/FullKeyboardView.swift index f476ce73a..7904753ad 100644 --- a/ios/HEXShared/FullKeyboard/FullKeyboardView.swift +++ b/ios/HEXShared/FullKeyboard/FullKeyboardView.swift @@ -51,6 +51,9 @@ final class FullKeyboardView: UIView { /// The Hex key's last tap or hold started a dictation here (not by opening Hex). private var dictatingFromHexKey = false private var lastDictation: String? + /// A word you typed whose slot you held: the strip offers Add to vocabulary until the text + /// changes (`FullKeyboardView+Vocabulary`). + var vocabularyOffer: String? private var undoHideWork: DispatchWorkItem? /// The Hex key was tapped without Full Access: the strip says what dictation needs. private(set) var showsFullAccessHint = false @@ -142,12 +145,18 @@ final class FullKeyboardView: UIView { } self.engine.acceptSuggestion(suggestion) } + stripView.onHoldSuggestion = { [weak self] suggestion in self?.offerVocabulary(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) + guard let self else { return } + self.keyFeedback() + if let word = self.vocabularyOffer { + self.addToVocabulary(word) + return + } + self.model.onOpenURL?(KeyboardLaunchRequest.translationSettings.url) } stripView.onNextKeyboard = { [weak self] in self?.typingLog?.ui("next_keyboard") @@ -187,6 +196,7 @@ final class FullKeyboardView: UIView { return } self.hideUndo() + self.vocabularyOffer = nil self.hideFullAccessHint() self.hideAllowPasteHint() self.refreshReturnKey() @@ -213,6 +223,7 @@ final class FullKeyboardView: UIView { engine.autocorrect.isEnabled = FullKeyboardSettings().autocorrect engine.autocorrect.allowsSwearing = FullKeyboardSettings().suggestSwearWords + engine.autocorrect.setVocabulary(CustomVocabularySettings().terms) engine.autoCapitalizes = FullKeyboardSettings().autoCapitalization engine.showsKeyPopups = FullKeyboardSettings().keyPopups syncHexPlacement() @@ -461,6 +472,11 @@ final class FullKeyboardView: UIView { engine.autocorrect.isEnabled = wantsAutocorrect engine.refreshSuggestions() } + let vocabulary = CustomVocabularySettings().terms + if engine.autocorrect.vocabulary != vocabulary { + engine.autocorrect.setVocabulary(vocabulary) + engine.refreshSuggestions() + } let wantsSwearing = FullKeyboardSettings().suggestSwearWords if engine.autocorrect.allowsSwearing != wantsSwearing { engine.autocorrect.allowsSwearing = wantsSwearing @@ -782,7 +798,7 @@ final class FullKeyboardView: UIView { statusText: status, clipboard: clipboardOffer, fullAccessHint: showsFullAccessHint && !model.hasFullAccess, - notice: translationNotice + notice: vocabularyNotice ?? translationNotice ) } diff --git a/ios/HEXShared/FullKeyboard/KeyboardLanguage.swift b/ios/HEXShared/FullKeyboard/KeyboardLanguage.swift index adf42fb61..a8d18e699 100644 --- a/ios/HEXShared/FullKeyboard/KeyboardLanguage.swift +++ b/ios/HEXShared/FullKeyboard/KeyboardLanguage.swift @@ -16,7 +16,9 @@ import Foundation /// the cedilla ş ţ), as on Apple's iPhone keyboard; Apple's Romanian layout with keys of its own /// for them is the iPad's. Greek matches the standard Greek layout and the system keyboard's /// observed long-press options, in the iPhone's rows (no ; or ς keys, the tonos key ending row -/// 1; its typing rules are `GreekTyping`). +/// 1; its typing rules are `GreekTyping`). Czech matches the standard Czech layout and the +/// system keyboard's observed long-press options: QWERTZ, with the ´ and ˇ keys that accent the +/// letter before them (`CzechTyping`) and every other Czech letter on a held key. nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { case english = "en" case norwegian = "nb" @@ -28,6 +30,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { case frenchSwiss = "fr-CH" case portuguese = "pt" case polish = "pl" + case czech = "cs" case romanian = "ro" case russian = "ru" case ukrainian = "uk" @@ -47,6 +50,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { case .frenchSwiss: "Français (Suisse)" case .portuguese: "Português" case .polish: "Polski" + case .czech: "Čeština" case .romanian: "Română" case .russian: "Русский" case .ukrainian: "Українська" @@ -85,6 +89,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { case .frenchSwiss: "fr-CH" case .portuguese: "pt-BR" case .polish: "pl-PL" + case .czech: "cs-CZ" case .romanian: "ro-RO" case .russian: "ru-RU" case .ukrainian: "uk-UA" @@ -154,6 +159,8 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { func letterRows(_ letters: KeyboardLetterLayout) -> [[String]] { let rows: [String] = switch offered(letters) { case .own: ownLetterRows + // Apple's Czech layouts are both its own, the ´ and ˇ keys kept: QWERTY only swaps Z and Y. + case .qwerty where self == .czech: ["qwertyuiop", "asdfghjkl\u{00B4}", "zxcvbnm\u{02C7}"] case .qwerty: ["qwertyuiop", "asdfghjkl", "zxcvbnm"] case .qwertz: ["qwertzuiop", "asdfghjkl", "yxcvbnm"] case .azerty: ["azertyuiop", "qsdfghjklm", "wxcvbn"] @@ -178,6 +185,9 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { case .frenchSwiss: [.qwertz, .azerty, .qwerty] case .italian, .portuguese: [.qwerty, .azerty, .qwertz] case .polish, .romanian: [.qwerty, .qwertz, .azerty] + // Apple's "QWERTZ – Czech/Slovak" (its default) and "QWERTY – Czech/Slovak", nothing else + // (iOS 27.2 simulator, Add New Keyboard › Czech › Layout). + case .czech: [.own, .qwerty] // Apple lists QWERTY first for Serbian (Latin) and adds it as QWERTY; Hex keeps the // QWERTZ it always typed on as the default. case .serbianLatin: [.qwertz, .qwerty, .azerty] @@ -198,13 +208,14 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { /// own layout with letters of its own, its arrangement and the language ("QWERTZ – Deutsch"). func layoutName(_ letters: KeyboardLetterLayout) -> String { switch letters { + case .qwerty where self == .czech: "QWERTY – \(displayName)" case .qwerty: "QWERTY" case .qwertz: "QWERTZ" case .azerty: "AZERTY" case .dvorak: "Dvorak" case .own: switch self { - case .german: "QWERTZ – \(displayName)" + case .german, .czech: "QWERTZ – \(displayName)" case .spanish, .norwegian: "QWERTY – \(displayName)" default: displayName } @@ -234,6 +245,10 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { // keys ending in the tonos key ´, over row 2's nine. case .greek: ["ερτυθιοπ\u{00B4}", "ασδφγηξκλ", "ζχψωβνμ"] case .serbianLatin: ["qwertzuiop", "asdfghjkl", "yxcvbnm"] + // The standard Czech layout (QWERTZ) in the rows the iPhone's own Czech keyboard shows + // (iOS 27.2 simulator): the ´ key (U+00B4) ends row 2, ten keys edge to edge, and the ˇ + // key (U+02C7) ends row 3, so shift and delete are one letter wide. + case .czech: ["qwertzuiop", "asdfghjkl\u{00B4}", "yxcvbnm\u{02C7}"] } } @@ -356,6 +371,26 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { "c": ["c", "ć", "ç", "č"], "n": ["n", "ń", "ñ"], ] + case .czech: + // Every Czech letter (á č ď é ě í ň ó ř š ť ú ů ý ž) and its neighbours'; the ˇ key + // holds the ring ˚ (ů, å), the ´ key nothing, and so does every letter not listed. + [ + "e": ["e", "ě", "é", "ê", "è", "ę", "ë", "ē", "ė"], + "r": ["r", "ř", "ŕ"], + "t": ["t", "ť"], + "z": ["z", "ż", "ź", "ž"], + "u": ["u", "ú", "ů", "û", "ü", "ù", "ū"], + "i": ["i", "í", "î", "ï", "ì", "į", "ī"], + "o": ["o", "ó", "ô", "ö", "ò", "õ", "œ", "ø", "ō"], + "a": ["a", "á", "à", "ą", "â", "ä", "æ", "ã", "å", "ā"], + "s": ["s", "š", "ß", "ś"], + "d": ["d", "ď"], + "l": ["l", "ł", "ľ", "ĺ"], + "y": ["y", "ý", "ÿ"], + "c": ["c", "č", "ç", "ć"], + "n": ["n", "ň", "ñ", "ń"], + "\u{02C7}": ["\u{02C7}", "\u{02DA}"], + ] case .romanian: // Romanian's own letters right after the base: ă and â on A, î on I, ș on S and ț on // T (comma-below, never the cedilla ş ţ); every other letter holds nothing. Its held @@ -490,6 +525,9 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { "8": ["8", "8ª", "8º"], "9": ["9", "9º", "9ª"], ] + case .czech: + // The system Czech keyboard's 123 and #+= pages, and every held symbol, are English's. + [:] case .polish: // Its currency key is € (no zł), held for € $ £ ¥ ₩ ₽; Hex's 123 page keeps $. [ @@ -533,6 +571,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { // Brazil's spelling first, Portugal's where only it is installed. case .portuguese: ["pt_BR", "pt", "pt_PT"] case .polish: ["pl", "pl_PL"] + case .czech: ["cs", "cs_CZ"] case .romanian: ["ro", "ro_RO"] case .russian: ["ru", "ru_RU"] case .ukrainian: ["uk", "uk_UA"] @@ -578,7 +617,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { ["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, .polish, - .romanian, .russian, .ukrainian, .greek, .serbianLatin: + .czech, .romanian, .russian, .ukrainian, .greek, .serbianLatin: [] } } @@ -607,7 +646,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { "giovedi": "giovedì", "venerdi": "venerdì", ] case .english, .norwegian, .spanish, .german, .french, .frenchCanadian, .frenchSwiss, - .portuguese, .polish, .romanian, .russian, .ukrainian, .greek, .serbianLatin: + .portuguese, .polish, .czech, .romanian, .russian, .ukrainian, .greek, .serbianLatin: [:] } } @@ -619,7 +658,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { switch self { case .italian: ["e": "è", "ce": "c'è"] case .english, .norwegian, .spanish, .german, .french, .frenchCanadian, .frenchSwiss, - .portuguese, .polish, .romanian, .russian, .ukrainian, .greek, .serbianLatin: + .portuguese, .polish, .czech, .romanian, .russian, .ukrainian, .greek, .serbianLatin: [:] } } @@ -631,13 +670,15 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { let letters = offered(letters) // AZERTY's row 2 runs edge to edge, and its row 3 starts under e (W under E). // Ukrainian's rows 1 and 2 are both twelve keys, and its row 3 starts under ц; Greek's - // are both nine (row 1 ending in the tonos key), and its row 3 starts under σ. + // are both nine (row 1 ending in the tonos key), and its row 3 starts under σ; Czech's + // both ten (row 2 ending in ´), its row 3 starting under s. // Dvorak's row 2 runs from the edge, its row 1 ends at delete (P over U's left half) and // its row 3 starts after shift (Q under O's right half). let offsets = switch letters { case .azerty: [0.0, 0.0, 2.0] case .dvorak: [1.85, 0.0, 1.33] - case .own where self == .ukrainian || self == .greek: [0.0, 0.0, 1.0] + case .own where self == .ukrainian || self == .greek || self == .czech: [0.0, 0.0, 1.0] + case .qwerty where self == .czech: [0.0, 0.0, 1.0] default: [0.0, 0.5, 1.5] } for (row, letters) in letterRows(letters).enumerated() { @@ -670,6 +711,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { return .french case "pt": return .portuguese case "pl": return .polish + case "cs": return .czech case "ro": return .romanian case "ru": return .russian case "uk": return .ukrainian @@ -713,7 +755,9 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable { /// Apple's Keyboard Layout list offers them for it. The plain ones hold only the 26 letters, in /// every language (iOS 27.0 simulator: the same rows, bottom row and 123 pages as the language's /// own layout, which is English's QWERTY, French's AZERTY, Swiss French's and Serbian's QWERTZ); -/// a language's other letters are then held on their base letter (`letterHolds(on:)`). +/// a language's other letters are then held on their base letter (`letterHolds(on:)`). Czech's +/// QWERTY is Apple's "QWERTY – Czech/Slovak": its own rows, ´ and ˇ keys kept, Z and Y swapped +/// (iOS 27.2 simulator). nonisolated enum KeyboardLetterLayout: String, CaseIterable, Sendable { /// The language's own keys, with letters of their own (German's ü ö ä, Spanish's ñ). case own diff --git a/ios/HEXShared/FullKeyboard/KeyboardStripView.swift b/ios/HEXShared/FullKeyboard/KeyboardStripView.swift index ab555bc33..fea8bcf20 100644 --- a/ios/HEXShared/FullKeyboard/KeyboardStripView.swift +++ b/ios/HEXShared/FullKeyboard/KeyboardStripView.swift @@ -40,6 +40,8 @@ final class KeyboardStripView: UIView { } } var onSelectSuggestion: ((KeyboardSuggestion) -> Void)? + /// A slot was held (half a second): the word you typed offers Add to vocabulary. + var onHoldSuggestion: ((KeyboardSuggestion) -> Void)? var onUndoDictation: (() -> Void)? var onPaste: (() -> Void)? var onNextKeyboard: (() -> Void)? @@ -150,6 +152,7 @@ final class KeyboardStripView: UIView { for (index, button) in slotButtons.enumerated() { button.tag = index button.addTarget(self, action: #selector(handleSlotTap(_:)), for: .touchUpInside) + button.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handleSlotHold(_:)))) addSubview(button) } applyPalette() @@ -416,6 +419,12 @@ final class KeyboardStripView: UIView { onSelectSuggestion?(currentSuggestions[item]) } + @objc private func handleSlotHold(_ recognizer: UILongPressGestureRecognizer) { + guard recognizer.state == .began, let slot = recognizer.view?.tag, + let item = Self.slots(for: currentSuggestions).firstIndex(of: slot) else { return } + onHoldSuggestion?(currentSuggestions[item]) + } + /// One suggestion slot. A word that changes swaps letter by letter, as Apple's bar does /// (iOS 27.2, recorded at 60 fps): the letters both words share stay, the old word's other /// letters fade from its end and the new word's from its start, each in 0.1 s, staggered diff --git a/ios/README.md b/ios/README.md index e40a9eac1..22290f3e7 100644 --- a/ios/README.md +++ b/ios/README.md @@ -324,7 +324,18 @@ never at a launch by itself. heard. - **Custom vocabulary (Settings › Dictation › Custom vocabulary):** Off by default. A local list of up to 100 names and phrases, applied to every engine, in the - app and in-keyboard dictation. After + app and in-keyboard dictation. The full keyboard uses the same list whether or not the + switch is on (Settings › Keyboard › Vocabulary edits it too; TestFlight build 56: + "custom dictionary for uncommon programmer slang"): its words, and each word of a + phrase, are never autocorrected away, a different case is put right on space ("github" + → "GitHub"), the strip completes them before the dictionary's words ("kub" → + "kubectl") with no spelling guesses for them, Swipe typing reads them as your own words, + and a bilingual partner shares them. Holding the word you typed in the strip's left slot + offers **Add to vocabulary** there (`FullKeyboardView+Vocabulary`; a capital only a + sentence's start gave the word is left out); without Full Access + the keyboard can't write the App Group, so the word is kept for that session only. + Before this the keys knew only iOS's text replacements and Contacts names + (`requestSupplementaryLexicon`), never Hex's list. After transcription, matching words are rewritten to the listed spelling across case, spaces, tabs, a single hyphen, and possessive apostrophes, before cleanup and again after formatting, so a style cannot undo a spelling. The @@ -397,8 +408,12 @@ never at a launch by itself. capital you didn't type: "i" stays "i", "im" becomes "i'm", "mary" stays "mary" and "mondya" becomes "monday", as Apple's keyboard does with Auto-Capitalization off (seen on the iOS 27.2 simulator). Words you typed with a capital, and your own spellings (text - replacements, Contacts names, words you kept, fixes Hex learned), keep theirs; shift and - caps lock work as before, and the strip may still offer a capitalised word to pick. + replacements, Contacts names, words you kept, fixes Hex learned, your vocabulary), keep + theirs; shift and caps lock work as before. The strip offers no capital you didn't type + either (TestFlight build 56: "even with auto-capitalization off, many suggested words are + capitalized"): a spelling guess or completion iOS knows capitalised ("Mandy", "Monday") + and the contraction "I'd" for "id" come lowercase there; sentence and clause starters + keep "I" and "I'm" (#2135), and next words and swipe readings already had no capital. Dictation has its own switch (Settings › Dictation › Lowercase). - **Spatial autocorrect (Settings › Keyboard › Spatial autocorrect):** On by default, shown under Autocorrect while it's on (it needs the full keyboard @@ -613,7 +628,8 @@ never at a launch by itself. the dictation bar, so testers who turned that experiment off keep the bar; on an iPad, where the keyboard always shows the dictation bar, the row says so: "On iPad, Hex shows the dictation bar"), then Languages, Auto-capitalization, Autocorrect (with Spatial autocorrect below it while it's - on), Suggest swear words and Key pop-ups only while Full is chosen, Haptics (the dictation bar uses it too), + on), Suggest swear words, Vocabulary (Hex's custom vocabulary list, how many words it + holds) and Key pop-ups only while Full is chosen, Haptics (the dictation bar uses it too), then Swipe typing and Emoji (Clear emoji history while it's on), which say they need the full keyboard while the dictation bar is chosen, and a field to try the keyboard in. - **Privacy:** "Everything stays on this iPhone", Learn how I type (what it @@ -824,11 +840,15 @@ never at a launch by itself. word either language knows as typed is never changed, a typo only one can fix gets that fix ("teh" → "the" while French types), and when both can, the language of the last words only one dictionary knows wins, else the clearly cheaper slip, else the keyboard's own; - the strip shows both languages' fixes and completions. In the simulator the English + the strip shows fixes and completions in the language the words before are in, never the + other's, even where that language has none (TestFlight build 56, Čeština and English: + "autocomplete suggests English words in Czech too"; the iOS 27.2 simulator's Czech + dictionary completes nothing, and English filled the strip), and with nothing before to + tell, both languages', in turn. In the simulator the English keyboard alone changed 34 of 77 common French words and the French keyboard alone 27 of 80 English words; with both chosen, none. Any two Latin-script languages with an iOS dictionary pair this way (English with Français, Deutsch, Italiano, Português, Polski, - Norsk, Română, Español, or two of those), whatever their order; Polski's simulator + Čeština, Norsk, Română, Español, or two of those), whatever their order; Polski's simulator dictionary takes every word, so the any-word guard (#2143) leaves it out there. The words before count for a language when only its dictionary knows them, or, from three letters, when both do but only its typing model has them among its commonest (iOS's French and German @@ -864,8 +884,10 @@ never at a launch by itself. "QWERTY – Español" (with ñ), QWERTY, AZERTY, QWERTZ; Français (France) AZERTY, QWERTY, QWERTZ, (Canada) QWERTY, AZERTY, QWERTZ, (Suisse) QWERTZ, AZERTY, QWERTY (Apple's "– French" variants add only the ´ key Hex leaves out); Italiano and Português QWERTY, - AZERTY, QWERTZ; Polski and Română QWERTY, QWERTZ, AZERTY; Srpski QWERTZ (Hex's, though - Apple now adds it as QWERTY), QWERTY, AZERTY. Norsk, Русский, Українська and Ελληνικά keep their + AZERTY, QWERTZ; Polski and Română QWERTY, QWERTZ, AZERTY; Čeština "QWERTZ – Čeština" and + "QWERTY – Čeština", Apple's "QWERTZ – Czech/Slovak" and "QWERTY – Czech/Slovak" (iOS 27.2 + simulator), both its own rows with the ´ and ˇ keys, Z and Y swapped on the second; Srpski + QWERTZ (Hex's, though Apple now adds it as QWERTY), QWERTY, AZERTY. Norsk, Русский, Українська and Ελληνικά keep their one layout (Apple also offers a phonetic "Russian – QWERTY", not built). The plain layouts are the same 26 letters in every language, with the language's bottom row and 123 pages; only the letters move (`KeyboardLetterLayout`, `KeyboardLanguage.letterRows(_:)`). @@ -918,7 +940,19 @@ never at a launch by itself. turns back into σ when another letter follows, as the system keyboard does; its 123 page has the ano teleia · in ;'s place and ; (the Greek question mark, which also starts the next sentence with a capital) in ?'s, its #+= page ? in |'s, its currency key is $ held as - English's, and its held " offers French's order) and Srpski (Latin: Apple's QWERTZ option for it; Apple's iPhone + English's, and its held " offers French's order), Čeština (it matches the standard Czech + layout and the system keyboard's observed long-press options, in the rows the iOS 27.2 + simulator's own Czech keyboard, "QWERTZ – Czech/Slovak", shows: `qwertzuiop`, `asdfghjkl´`, + `yxcvbnmˇ`, ten keys edge to edge on rows 1 and 2 and shift and delete a letter wide on row + 3; the ´ (U+00B4) and ˇ (U+02C7) keys are no dead keys: with real touches in Messages, each + accents the letter right before it, ´ giving á ć é í ĺ ń ó ŕ ś ú ý ź and ˇ č ď ě ľ ň ř š ť ž + and ů after u, capitals too (A´ → Á, Uˇ → Ů), and after anything else, an accented letter + included, types itself ("aˇ", "á´"); delete then takes the accented letter whole + (`CzechTyping`); held, E offers ě é ê è ę ë ē ė, R ř ŕ, T ť, Z ž ź ż, U ú ů û ü ù ū, I í î ï + ì į ī, O ó ô ö ò õ œ ø ō, A á à ą â ä æ ã å ā, S š ß ś, D ď, L ł ľ ĺ, Y ý ÿ, C č ç ć, N ň ñ ń + and the ˇ key the ring ˚ (which makes ů and å), each callout laid out as the system's + (`AccentCatalog.arrangement`), and every other key, ´ included, nothing; its 123 and #+= + pages and their held keys are English'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). @@ -941,7 +975,7 @@ never at a launch by itself. 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`, `pl`, `ro`, `ru`, `uk`, `el`; Serbian would use `sr_Latn`, which iOS 27.2 doesn't have, nor a + `pt_PT`, `pl`, `cs`, `ro`, `ru`, `uk`, `el`; 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 @@ -958,7 +992,9 @@ never at a launch by itself. iOS 27.2 simulator lists `pl_PL` but its checker flags no word, so Polish fixes are checked against a stub dictionary there. Greek likewise: every tonos or diaeresis left out counts as one such fix, and so does σ where the word ends in ς ("καλημερα" → "καλημέρα", - "λογοσ" → "λόγος"); Greek fixes are checked against a stub dictionary too. A two-letter non-word one + "λογοσ" → "λόγος"); Greek fixes are checked against a stub dictionary too. Czech likewise: + every háček or čárka left out counts as one such fix ("cesky" → "český", "prilis" → + "příliš"), checked against a stub dictionary. 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. @@ -1298,6 +1334,10 @@ from `ci_scripts/ci_post_clone.sh`. A new model gets a new release tag and hash. 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. + Czech is too (macOS 27.2.1 lists `cs-CZ` for `DictationTranscriber` only, a 12 s model + download): `say -v Zuzana` clips came back with every háček and čárka ("Příliš žluťoučký kůň + úpěl"), numbers and times as digits ("10 min.", "19:30", "8:15") and no punctuation. It + never goes to Parakeet, which is English-only. Greek is too (macOS 27.2 lists `el-GR` for `DictationTranscriber` only): `say -v Melina` clips came back with every tonos, final ς, numbers as digits ("10 λεπτά", "7:30"), and no punctuation. Lowercase lowers with Unicode's context-aware mapping, so a word-final Σ