From d5ef6b960319422d325aa0cf16b5657cf41d2e13 Mon Sep 17 00:00:00 2001 From: mtgto Date: Thu, 12 Nov 2026 20:55:49 +0900 Subject: [PATCH] =?UTF-8?q?=E5=A4=89=E6=8F=9B=E5=80=99=E8=A3=9C=E3=81=AE?= =?UTF-8?q?=E9=81=B8=E6=8A=9E=E3=82=AD=E3=83=BC=E3=82=92=E4=BB=BB=E6=84=8F?= =?UTF-8?q?=E3=81=AE9=E6=96=87=E5=AD=97=E3=81=AB=E8=A8=AD=E5=AE=9A?= =?UTF-8?q?=E3=81=A7=E3=81=8D=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB=E3=81=99?= =?UTF-8?q?=E3=82=8B=20(#549)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 設定画面のPickerに「カスタム…」を追加し、シートでスペースを除くASCII文字9文字を 重複なし (大文字小文字は区別しない) で入力できるようにする。 --- macSKK.xcodeproj/project.pbxproj | 12 +++ macSKK/Settings/GeneralView.swift | 35 ++++++- macSKK/Settings/SelectCandidateKeys.swift | 64 +++++++++++++ macSKK/Settings/SelectCandidateKeysView.swift | 93 +++++++++++++++++++ macSKK/Settings/SettingsViewModel.swift | 9 +- macSKK/en.lproj/Localizable.strings | 6 ++ macSKK/ja.lproj/Localizable.strings | 6 ++ macSKKTests/SelectCandidateKeysTests.swift | 69 ++++++++++++++ macSKKTests/SettingsSyncTests.swift | 30 ++++++ 9 files changed, 315 insertions(+), 9 deletions(-) create mode 100644 macSKK/Settings/SelectCandidateKeys.swift create mode 100644 macSKK/Settings/SelectCandidateKeysView.swift create mode 100644 macSKKTests/SelectCandidateKeysTests.swift diff --git a/macSKK.xcodeproj/project.pbxproj b/macSKK.xcodeproj/project.pbxproj index e0ad678b..91bd3d5e 100644 --- a/macSKK.xcodeproj/project.pbxproj +++ b/macSKK.xcodeproj/project.pbxproj @@ -134,6 +134,9 @@ CE8871462E63ECB700E20BFB /* kana-rule-azik-us.conf in Resources */ = {isa = PBXBuildFile; fileRef = CE8871452E63ECB700E20BFB /* kana-rule-azik-us.conf */; }; CE8DFE092CBEAA2900A24230 /* Character+AdditionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE8DFE082CBEAA1F00A24230 /* Character+AdditionsTests.swift */; }; CE97887B2A9B93EB00F9B196 /* DirectModeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE97887A2A9B93EB00F9B196 /* DirectModeView.swift */; }; + CEA0C37F30A5E118001AF9B3 /* SelectCandidateKeys.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA0C37E30A5E118001AF9B3 /* SelectCandidateKeys.swift */; }; + CEA0C38130A5E118001AF9B3 /* SelectCandidateKeysView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA0C38030A5E118001AF9B3 /* SelectCandidateKeysView.swift */; }; + CEA0C38330A5E118001AF9B3 /* SelectCandidateKeysTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA0C38230A5E118001AF9B3 /* SelectCandidateKeysTests.swift */; }; CEA253942E228E2000618E64 /* SKKServDictSettingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA253932E228E2000618E64 /* SKKServDictSettingTests.swift */; }; CEA253962E2290AC00618E64 /* SKKServDictSetting.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA253952E2290AC00618E64 /* SKKServDictSetting.swift */; }; CEA253982E23AB7600618E64 /* DictSetting.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA253972E23AB7600618E64 /* DictSetting.swift */; }; @@ -365,6 +368,9 @@ CE8871452E63ECB700E20BFB /* kana-rule-azik-us.conf */ = {isa = PBXFileReference; lastKnownFileType = text; path = "kana-rule-azik-us.conf"; sourceTree = ""; }; CE8DFE082CBEAA1F00A24230 /* Character+AdditionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Character+AdditionsTests.swift"; sourceTree = ""; }; CE97887A2A9B93EB00F9B196 /* DirectModeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectModeView.swift; sourceTree = ""; }; + CEA0C37E30A5E118001AF9B3 /* SelectCandidateKeys.swift */ = {isa = PBXFileReference; path = SelectCandidateKeys.swift; sourceTree = ""; }; + CEA0C38030A5E118001AF9B3 /* SelectCandidateKeysView.swift */ = {isa = PBXFileReference; path = SelectCandidateKeysView.swift; sourceTree = ""; }; + CEA0C38230A5E118001AF9B3 /* SelectCandidateKeysTests.swift */ = {isa = PBXFileReference; path = SelectCandidateKeysTests.swift; sourceTree = ""; }; CEA253932E228E2000618E64 /* SKKServDictSettingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SKKServDictSettingTests.swift; sourceTree = ""; }; CEA253952E2290AC00618E64 /* SKKServDictSetting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SKKServDictSetting.swift; sourceTree = ""; }; CEA253972E23AB7600618E64 /* DictSetting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DictSetting.swift; sourceTree = ""; }; @@ -694,6 +700,7 @@ CED7CA572A83BFE9004EF988 /* fixture */, CE1E7BAA2E406B6700C2E410 /* URL+AdditionsTests.swift */, CE25D7DA307A95290080B25E /* MockTextInput.swift */, + CEA0C38230A5E118001AF9B3 /* SelectCandidateKeysTests.swift */, ); path = macSKKTests; sourceTree = ""; @@ -759,6 +766,8 @@ CE2157652B2EA985006E4C41 /* UserDefaultsKeys.swift */, CE420SYNC2F00000100000001 /* SettingsSync.swift */, CEA602AB2F02CFB000E605F2 /* OptionalBackgroundModifier.swift */, + CEA0C37E30A5E118001AF9B3 /* SelectCandidateKeys.swift */, + CEA0C38030A5E118001AF9B3 /* SelectCandidateKeysView.swift */, ); path = Settings; sourceTree = ""; @@ -1088,6 +1097,7 @@ CEB52CC62E080B030025542F /* DateConversionsView.swift in Sources */, CED7F51F2AB5F4A7007FC6BD /* Character+Additions.swift in Sources */, CE2157662B2EA985006E4C41 /* UserDefaultsKeys.swift in Sources */, + CEA0C38130A5E118001AF9B3 /* SelectCandidateKeysView.swift in Sources */, CE420SYNC2F00000100000002 /* SettingsSync.swift in Sources */, CE420CSV2F00000100000002 /* CloudSyncView.swift in Sources */, CE84A3B929570C37009394C4 /* InputController.swift in Sources */, @@ -1116,6 +1126,7 @@ 4B8E87D42CE05C40004E7461 /* CurrentInput.swift in Sources */, CE7F9AD92AADEBF9001B1877 /* AppDelegate.swift in Sources */, CEF0825B296D8FF000646366 /* CandidatesView.swift in Sources */, + CEA0C37F30A5E118001AF9B3 /* SelectCandidateKeys.swift in Sources */, CED098512B95F32600F2E844 /* WorkaroundView.swift in Sources */, CE84A3E0295717CB009394C4 /* StateMachine.swift in Sources */, CED7CA3C2A839603004EF988 /* UpdateChecker.swift in Sources */, @@ -1188,6 +1199,7 @@ 7A1B2C3D4E5F60718293A001 /* ReadonlyMemoryDictMemoryTests.swift in Sources */, CE06CA342AAC199500E80E5E /* UserDict+Utilities.swift in Sources */, CE84A3E9295DA504009394C4 /* RomajiTests.swift in Sources */, + CEA0C38330A5E118001AF9B3 /* SelectCandidateKeysTests.swift in Sources */, CE4CB5CE2AD55DF90046FA34 /* NumberEntryTests.swift in Sources */, CE49A2782C19E07800D53CFE /* KeyBindingSetTests.swift in Sources */, CEA253942E228E2000618E64 /* SKKServDictSettingTests.swift in Sources */, diff --git a/macSKK/Settings/GeneralView.swift b/macSKK/Settings/GeneralView.swift index 6027de36..7563ff40 100644 --- a/macSKK/Settings/GeneralView.swift +++ b/macSKK/Settings/GeneralView.swift @@ -6,6 +6,23 @@ import SwiftUI struct GeneralView: View { @StateObject var settingsViewModel: SettingsViewModel @State private var isShowingInputModeSettings = false + @State private var isShowingSelectCandidateKeysSheet = false + + /// Pickerで「カスタム…」を表すタグ。空文字列は選択キーとして不正なので実際の値と衝突しない + private static let customSelectCandidateKeysTag = "" + + /// 「カスタム…」が選ばれたときは値を変えずにシートを開く。キャンセルされたらPickerは元の値のまま + private var selectCandidateKeysSelection: Binding { + Binding { + settingsViewModel.selectCandidateKeys + } set: { newValue in + if newValue == Self.customSelectCandidateKeysTag { + isShowingSelectCandidateKeysSheet = true + } else { + settingsViewModel.selectCandidateKeys = newValue + } + } + } var body: some View { VStack { @@ -35,10 +52,20 @@ struct GeneralView: View { Text("SystemDictDaijirin").tag(SystemDict.Kind.daijirin) Text("SystemDictWisdom").tag(SystemDict.Kind.wisdom) }.disabled(!settingsViewModel.showAnnotation) - Picker("Keys of selecting candidates", selection: $settingsViewModel.selectCandidateKeys) { - Text("123456789").tag("123456789") - Text("ASDFGHJKL").tag("ASDFGHJKL") - Text("AOEUIDHTN").tag("AOEUIDHTN") + Picker("Keys of selecting candidates", selection: selectCandidateKeysSelection) { + ForEach(SelectCandidateKeys.presets, id: \.self) { keys in + Text(keys).tag(keys) + } + if !SelectCandidateKeys.presets.contains(settingsViewModel.selectCandidateKeys) { + Divider() + Text(settingsViewModel.selectCandidateKeys).tag(settingsViewModel.selectCandidateKeys) + } + Divider() + Text("Custom…").tag(Self.customSelectCandidateKeysTag) + } + .sheet(isPresented: $isShowingSelectCandidateKeysSheet) { + SelectCandidateKeysView(settingsViewModel: settingsViewModel, + keys: settingsViewModel.selectCandidateKeys) } Picker("Behavior of Comma", selection: $settingsViewModel.comma) { ForEach(Punctuation.Comma.allCases, id: \.id) { comma in diff --git a/macSKK/Settings/SelectCandidateKeys.swift b/macSKK/Settings/SelectCandidateKeys.swift new file mode 100644 index 00000000..e800dd09 --- /dev/null +++ b/macSKK/Settings/SelectCandidateKeys.swift @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +/// 変換候補の選択に使うキーの文字列のバリデーション +enum SelectCandidateKeys { + /// 選択キーの文字数。候補パネルに一度に表示できる最大の候補数と同じ + static let count = 9 + static let `default` = "123456789" + /// 設定画面で選べるプリセット + static let presets = ["123456789", "ASDFGHJKL", "AOEUIDHTN"] + + enum ValidationError: Error, Equatable { + /// 文字数が ``SelectCandidateKeys/count`` ではない。値は入力された文字数 + case invalidLength(Int) + /// 重複している文字がある (大文字小文字は区別しない)。値は重複している文字を大文字にしたもの + case duplicated([Character]) + /// スペースを除く表示可能なASCII文字以外が含まれている。値は使えない文字 + case invalidCharacters([Character]) + } + + /** + * 選択キーとして正しいかを検証し、大文字にそろえた文字列を返す。 + * + * 複数の誤りがある場合は、使えない文字、重複、文字数の順で一つだけ報告する。 + * Shiftが必要な記号やキーバインドに割り当てられたキーは候補の選択に使えないが、 + * キーバインドは後から変更されうるのでここではエラーにしない。 + */ + static func validate(_ keys: String) throws(ValidationError) -> String { + let invalidCharacters = unique(keys.filter { !isAllowed($0) }) + if !invalidCharacters.isEmpty { + throw .invalidCharacters(invalidCharacters) + } + let uppercased = keys.uppercased() + var seen = Set() + let duplicated = unique(uppercased.filter { !seen.insert($0).inserted }) + if !duplicated.isEmpty { + throw .duplicated(duplicated) + } + if uppercased.count != count { + throw .invalidLength(uppercased.count) + } + return uppercased + } + + /// 保存されていた値や同期で受け取った値を検証し、不正ならデフォルト値を返す + static func sanitize(_ keys: String?) -> String { + guard let keys, let validated = try? validate(keys) else { + return Self.default + } + return validated + } + + /// スペースを除く表示可能なASCII文字 ("!" から "~") か + private static func isAllowed(_ character: Character) -> Bool { + guard let asciiValue = character.asciiValue else { return false } + // "\r\n" は asciiValue が "\n" になるが範囲外なので弾かれる + return (0x21...0x7E).contains(asciiValue) + } + + /// 出現順を保ったまま重複を除く + private static func unique(_ characters: String) -> [Character] { + var seen = Set() + return characters.filter { seen.insert($0).inserted } + } +} diff --git a/macSKK/Settings/SelectCandidateKeysView.swift b/macSKK/Settings/SelectCandidateKeysView.swift new file mode 100644 index 00000000..f7ea7f7c --- /dev/null +++ b/macSKK/Settings/SelectCandidateKeysView.swift @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// 変換候補の選択に使うキーを自由に入力するシート +struct SelectCandidateKeysView: View { + @Environment(\.dismiss) var dismiss + @ObservedObject var settingsViewModel: SettingsViewModel + @State var keys: String + + var body: some View { + let result = Result { () throws(SelectCandidateKeys.ValidationError) -> String in + try SelectCandidateKeys.validate(keys) + } + VStack { + Form { + Section { + TextField("Keys", text: $keys, prompt: Text(SelectCandidateKeys.default)) + .font(.body.monospaced()) + } footer: { + VStack(alignment: .leading, spacing: 8) { + Text("SelectCandidateKeysDescription") + .foregroundStyle(.secondary) + // エラーの有無でシートの高さが変わらないよう、エラーがないときも2行分の領域を確保して隠す + let errorMessage: String? = if case .failure(let error) = result { Self.message(for: error) } else { nil } + Label { + Text(errorMessage ?? " ") + .lineLimit(2, reservesSpace: true) + } icon: { + Image(systemName: "exclamationmark.triangle.fill") + } + .foregroundStyle(.red) + .opacity(errorMessage == nil ? 0 : 1) + .accessibilityHidden(errorMessage == nil) + } + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } + } + .formStyle(.grouped) + HStack { + Spacer() + Button("Cancel", role: .cancel) { + dismiss() + } + Button { + if case .success(let validated) = result { + settingsViewModel.selectCandidateKeys = validated + } + dismiss() + } label: { + Text("Done") + .padding([.leading, .trailing]) + } + .keyboardShortcut(.defaultAction) + .disabled((try? result.get()) == nil) + } + // 上はFormの下余白があるので詰める + .padding([.horizontal, .bottom]) + } + .frame(width: 420) + } + + private static func message(for error: SelectCandidateKeys.ValidationError) -> String { + switch error { + case .invalidLength(let count): + return String(localized: "SelectCandidateKeysErrorLength \(SelectCandidateKeys.count) \(count)") + case .duplicated(let characters): + return String(localized: "SelectCandidateKeysErrorDuplicated \(Self.quoted(characters))") + case .invalidCharacters(let characters): + return String(localized: "SelectCandidateKeysErrorInvalidCharacters \(Self.quoted(characters))") + } + } + + /// エラーメッセージ中で文字を示すために "A", "B" のように引用符で囲んで並べる + private static func quoted(_ characters: [Character]) -> String { + characters.map { character in + switch character { + case " ": "\"␣\"" + case "\t": "\"⇥\"" + default: "\"\(character)\"" + } + }.joined(separator: ", ") + } +} + +#Preview { + SelectCandidateKeysView(settingsViewModel: try! SettingsViewModel(), keys: "ASDFGHJKL") +} + +#Preview("Error") { + SelectCandidateKeysView(settingsViewModel: try! SettingsViewModel(), keys: "AASDF") +} diff --git a/macSKK/Settings/SettingsViewModel.swift b/macSKK/Settings/SettingsViewModel.swift index 58cac7ca..12bf86a7 100644 --- a/macSKK/Settings/SettingsViewModel.swift +++ b/macSKK/Settings/SettingsViewModel.swift @@ -286,7 +286,7 @@ final class SettingsViewModel: ObservableObject { self.systemDict = .daijirin } - selectCandidateKeys = UserDefaults.app.string(forKey: UserDefaultsKeys.selectCandidateKeys)! + selectCandidateKeys = SelectCandidateKeys.sanitize(UserDefaults.app.string(forKey: UserDefaultsKeys.selectCandidateKeys)) enterNewLine = UserDefaults.app.bool(forKey: UserDefaultsKeys.enterNewLine) showCompletion = UserDefaults.app.bool(forKey: UserDefaultsKeys.showCompletion) showCandidateForCompletion = UserDefaults.app.bool(forKey: UserDefaultsKeys.showCandidateForCompletion) @@ -947,9 +947,8 @@ final class SettingsViewModel: ObservableObject { annotationBackgroundColor = color } case UserDefaultsKeys.selectCandidateKeys: - if let selectCandidateKeys = UserDefaults.app.string(forKey: key) { - self.selectCandidateKeys = selectCandidateKeys - } + // 手で書き換えられた値などで候補パネルの表示が範囲外アクセスしないように不正な値はデフォルト値にする。 + selectCandidateKeys = SelectCandidateKeys.sanitize(UserDefaults.app.string(forKey: key)) case UserDefaultsKeys.enterNewLine: enterNewLine = UserDefaults.app.bool(forKey: key) case UserDefaultsKeys.showCompletion: @@ -1110,7 +1109,7 @@ final class SettingsViewModel: ObservableObject { responseEncoding: .japaneseEUC, saveToUserDict: true, enableCompletion: false) - selectCandidateKeys = "123456789" + selectCandidateKeys = SelectCandidateKeys.default findCompletionFromAllDicts = false keyBindingSets = [KeyBindingSet.defaultKeyBindingSet] selectedKeyBindingSet = KeyBindingSet.defaultKeyBindingSet diff --git a/macSKK/en.lproj/Localizable.strings b/macSKK/en.lproj/Localizable.strings index 63800916..5a63745b 100644 --- a/macSKK/en.lproj/Localizable.strings +++ b/macSKK/en.lproj/Localizable.strings @@ -77,6 +77,12 @@ "Show Annotation" = "Show the annotation of the candidate in current"; "System Dictionary for annotation" = "System Dictionary for annotation"; "Keys of selecting candidates" = "Keys of selecting candidates"; +"Custom…" = "Custom…"; +"Keys" = "Keys"; +"SelectCandidateKeysDescription" = "Enter 9 keys to select candidates. ASCII letters, digits and symbols except space are allowed, and uppercase and lowercase letters are treated the same. Symbols that require the Shift key and keys assigned in key bindings cannot be used to select candidates."; +"SelectCandidateKeysErrorLength %lld %lld" = "Enter %1$lld characters (currently %2$lld)"; +"SelectCandidateKeysErrorDuplicated %@" = "Duplicated characters: %@"; +"SelectCandidateKeysErrorInvalidCharacters %@" = "Invalid characters: %@"; "Copy" = "Copy"; "Number of inline candidates" = "Number of inline candidates"; "Number of candidates in panel" = "Number of candidates in panel"; diff --git a/macSKK/ja.lproj/Localizable.strings b/macSKK/ja.lproj/Localizable.strings index 478893f7..cc7ef782 100644 --- a/macSKK/ja.lproj/Localizable.strings +++ b/macSKK/ja.lproj/Localizable.strings @@ -77,6 +77,12 @@ "Show Annotation" = "現在の変換候補の注釈を表示"; "System Dictionary for annotation" = "注釈に使用するシステム辞書"; "Keys of selecting candidates" = "変換候補の決定に使用するキー"; +"Custom…" = "カスタム…"; +"Keys" = "キー"; +"SelectCandidateKeysDescription" = "変換候補の選択に使う9つのキーを入力してください。スペースを除く半角英数字と記号が使え、大文字と小文字は区別しません。Shiftを押しながら入力する記号や、キーバインドに割り当てたキーでは変換候補を選択できません。"; +"SelectCandidateKeysErrorLength %lld %lld" = "%1$lld文字で入力してください (現在%2$lld文字)"; +"SelectCandidateKeysErrorDuplicated %@" = "重複している文字があります: %@"; +"SelectCandidateKeysErrorInvalidCharacters %@" = "使用できない文字があります: %@"; "Copy" = "コピー"; "Number of inline candidates" = "インラインで表示する変換候補の数"; "Number of candidates in panel" = "変換候補パネルに表示する変換候補の数"; diff --git a/macSKKTests/SelectCandidateKeysTests.swift b/macSKKTests/SelectCandidateKeysTests.swift new file mode 100644 index 00000000..63f12cf5 --- /dev/null +++ b/macSKKTests/SelectCandidateKeysTests.swift @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +import XCTest + +@testable import macSKK + +final class SelectCandidateKeysTests: XCTestCase { + func testValidatePresets() throws { + for preset in SelectCandidateKeys.presets { + XCTAssertEqual(try SelectCandidateKeys.validate(preset), preset) + } + } + + func testValidateNormalizesToUppercase() throws { + XCTAssertEqual(try SelectCandidateKeys.validate("qwertyuio"), "QWERTYUIO") + XCTAssertEqual(try SelectCandidateKeys.validate(";,.pyfgcr"), ";,.PYFGCR") + } + + func testValidateInvalidLength() { + XCTAssertThrowsError(try SelectCandidateKeys.validate("")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidLength(0)) + } + XCTAssertThrowsError(try SelectCandidateKeys.validate("12345678")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidLength(8)) + } + XCTAssertThrowsError(try SelectCandidateKeys.validate("1234567890")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidLength(10)) + } + } + + func testValidateDuplicated() { + XCTAssertThrowsError(try SelectCandidateKeys.validate("112345678")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .duplicated(["1"])) + } + // 大文字小文字は区別しない + XCTAssertThrowsError(try SelectCandidateKeys.validate("aAbBcdefg")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .duplicated(["A", "B"])) + } + // 文字数が足りなくても重複を優先して報告する + XCTAssertThrowsError(try SelectCandidateKeys.validate("11")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .duplicated(["1"])) + } + } + + func testValidateInvalidCharacters() { + XCTAssertThrowsError(try SelectCandidateKeys.validate("1234 5678")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidCharacters([" "])) + } + XCTAssertThrowsError(try SelectCandidateKeys.validate("あいうえおかきくけ")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidCharacters(["あ", "い", "う", "え", "お", "か", "き", "く", "け"])) + } + XCTAssertThrowsError(try SelectCandidateKeys.validate("123456789")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidCharacters(["1"])) + } + XCTAssertThrowsError(try SelectCandidateKeys.validate("1234\t5678")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidCharacters(["\t"])) + } + // 使えない文字は重複していても1回だけ報告する + XCTAssertThrowsError(try SelectCandidateKeys.validate("12 ")) { error in + XCTAssertEqual(error as? SelectCandidateKeys.ValidationError, .invalidCharacters([" "])) + } + } + + func testSanitize() { + XCTAssertEqual(SelectCandidateKeys.sanitize("asdfghjkl"), "ASDFGHJKL") + XCTAssertEqual(SelectCandidateKeys.sanitize("1234"), SelectCandidateKeys.default) + XCTAssertEqual(SelectCandidateKeys.sanitize(nil), SelectCandidateKeys.default) + } +} diff --git a/macSKKTests/SettingsSyncTests.swift b/macSKKTests/SettingsSyncTests.swift index 76b58197..4bb5bca6 100644 --- a/macSKKTests/SettingsSyncTests.swift +++ b/macSKKTests/SettingsSyncTests.swift @@ -170,6 +170,36 @@ final class SettingsSyncTests: XCTestCase { XCTAssertEqual(store.setCount, setCountBeforeApply, "取り込んだ設定がiCloudに送り返されています") } + /// iCloudから不正な選択キーを取り込んだときはデフォルト値になること + func testInvalidSelectCandidateKeysFromStoreFallsBackToDefault() { + let preserved = preserveUserDefaults() + defer { restoreUserDefaults(preserved) } + + UserDefaults.app.set("ASDFGHJKL", forKey: UserDefaultsKeys.selectCandidateKeys) + let store = FakeKeyValueStore() + let settingsViewModel = makeSettingsViewModel(store: store) + settingsViewModel.enableSyncSettingsWithiCloud(initialSync: .pushLocal) + + store.set("AAB", forKey: UserDefaultsKeys.selectCandidateKeys) + postDidChangeExternallyNotification(changedKeys: [UserDefaultsKeys.selectCandidateKeys]) + pumpRunLoop { settingsViewModel.selectCandidateKeys == SelectCandidateKeys.default } + + XCTAssertEqual(settingsViewModel.selectCandidateKeys, SelectCandidateKeys.default) + XCTAssertEqual(Global.selectCandidateKeys, Array(SelectCandidateKeys.default)) + } + + /// 保存されていた選択キーが不正なときは起動時にデフォルト値になること + func testInvalidSelectCandidateKeysInUserDefaultsFallsBackToDefault() { + let preserved = preserveUserDefaults() + defer { restoreUserDefaults(preserved) } + + UserDefaults.app.set("12345", forKey: UserDefaultsKeys.selectCandidateKeys) + let settingsViewModel = makeSettingsViewModel(store: FakeKeyValueStore()) + + XCTAssertEqual(settingsViewModel.selectCandidateKeys, SelectCandidateKeys.default) + XCTAssertEqual(Global.selectCandidateKeys, Array(SelectCandidateKeys.default)) + } + // MARK: - 取り込んだことの通知 /// 起動時にiCloudの設定を取り込んだとき、実際に値が変わった設定のカテゴリだけが通知されること