diff --git a/App/AppEnvironment.swift b/App/AppEnvironment.swift index d6026df..ef7f209 100644 --- a/App/AppEnvironment.swift +++ b/App/AppEnvironment.swift @@ -217,6 +217,8 @@ final class AppEnvironment { translationFontSize: settings.translationFontSize, renderMarkdown: settings.renderMarkdown, closeWithEscape: settings.closeWithEscape, + autoSwitchTarget: settings.autoSwitchTarget, + fallbackTarget: settings.fallbackTargetModel, recentTargets: settings.recentTargets ) } diff --git a/App/Panel/LanguagePickerView.swift b/App/Panel/LanguagePickerView.swift index 857d6b7..f48bb63 100644 --- a/App/Panel/LanguagePickerView.swift +++ b/App/Panel/LanguagePickerView.swift @@ -5,6 +5,7 @@ import SwiftUI struct LanguagePickerView: View { @Binding var selection: ModelLanguage var recent: [ModelLanguage] = [] + var excluding: String? @Environment(\.dismiss) private var dismiss @State private var query = "" @@ -45,8 +46,12 @@ struct LanguagePickerView: View { let all = LanguageCatalogue.all.sorted { $0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending } - guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return all } - return all.filter { + let available = all.filter { language in + guard let excluding else { return true } + return language.code.caseInsensitiveCompare(excluding) != .orderedSame + } + guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return available } + return available.filter { $0.localizedDisplayName.localizedCaseInsensitiveContains(query) || $0.modelName.localizedCaseInsensitiveContains(query) || $0.code.localizedCaseInsensitiveContains(query) diff --git a/App/Panel/PanelView+Content.swift b/App/Panel/PanelView+Content.swift index 340c49d..3e3599c 100644 --- a/App/Panel/PanelView+Content.swift +++ b/App/Panel/PanelView+Content.swift @@ -36,7 +36,7 @@ extension PanelView { MarkdownTranslationView( markdown: model.translation, fontSize: model.configuration.translationFontSize, - isRTL: model.configuration.target.isRTL + isRTL: model.effectiveTarget.isRTL ) } else { Text(translationText) @@ -46,7 +46,7 @@ extension PanelView { .foregroundStyle(model.translation.isEmpty ? .secondary : .primary) .environment( \.layoutDirection, - model.configuration.target.isRTL ? .rightToLeft : .leftToRight + model.effectiveTarget.isRTL ? .rightToLeft : .leftToRight ) .accessibilityLabel(String(localized: "Translation")) } @@ -66,11 +66,34 @@ extension PanelView { } } + private func autoSwitchMessage(from original: ModelLanguage) -> String { + let source = original.localizedDisplayName + let target = model.effectiveTarget.localizedDisplayName + return String(localized: "Detected \(source). Translating to \(target).") + } + @ViewBuilder var warningArea: some View { + if let original = model.autoSwitchedFrom { + HStack(alignment: .top, spacing: 8) { + Image(systemName: "arrow.left.arrow.right.circle.fill") + .foregroundStyle(.blue) + .accessibilityHidden(true) + Text(autoSwitchMessage(from: original)) + .font(.callout) + Spacer() + Button(String(localized: "Translate to \(original.localizedDisplayName)")) { + Task { await model.overrideTarget(original) } + } + .controlSize(.small) + } + .padding(8) + .background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8)) + } + if model.sameLanguageWarning != nil { HStack(alignment: .top, spacing: 8) { Image(systemName: "info.circle.fill").foregroundStyle(.blue) - Text("This text already appears to be in \(model.configuration.target.localizedDisplayName).") + Text("This text already appears to be in \(model.effectiveTarget.localizedDisplayName).") .font(.callout) Spacer() Button(String(localized: "Translate anyway")) { diff --git a/App/Panel/PanelView.swift b/App/Panel/PanelView.swift index 29c9af3..7015db3 100644 --- a/App/Panel/PanelView.swift +++ b/App/Panel/PanelView.swift @@ -62,7 +62,7 @@ struct PanelView: View { VStack(alignment: .leading, spacing: 1) { Text(String(localized: "Translate")) .font(.headline) - Text("\(sourceLanguageLabel) → \(model.configuration.target.localizedDisplayName)") + Text("\(sourceLanguageLabel) → \(model.effectiveTarget.localizedDisplayName)") .font(.caption) .foregroundStyle(.secondary) } @@ -75,14 +75,14 @@ struct PanelView: View { Button { showLanguagePicker.toggle() } label: { - Label(model.configuration.target.localizedDisplayName, systemImage: "globe") + Label(model.effectiveTarget.localizedDisplayName, systemImage: "globe") .labelStyle(.titleAndIcon) } .accessibilityLabel(String(localized: "Target language")) .popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) { LanguagePickerView( selection: Binding( - get: { model.configuration.target }, + get: { model.effectiveTarget }, set: { language in Task { await model.setTarget(language) } } diff --git a/App/Resources/de.lproj/Localizable.strings b/App/Resources/de.lproj/Localizable.strings index 0bfa8f4..e791f19 100644 --- a/App/Resources/de.lproj/Localizable.strings +++ b/App/Resources/de.lproj/Localizable.strings @@ -104,3 +104,10 @@ "Render bold, italic, headings, lists, code and links when the source is Markdown." = "Fett, kursiv, Überschriften, Listen, Code und Links anzeigen, wenn die Quelle Markdown ist."; "Close with Esc without clicking" = "Mit Esc schließen, ohne zu klicken"; "The panel takes keyboard focus while it is visible. The source app stays frontmost." = "Das Panel übernimmt die Tastatureingabe, solange es sichtbar ist. Die Quell-App bleibt im Vordergrund."; +"Translate the other direction when the text is already in the target language" = "In die andere Richtung übersetzen, wenn der Text bereits in der Zielsprache ist"; +"Translate the other direction" = "In die andere Richtung übersetzen"; +"Fallback target language" = "Ausweich-Zielsprache"; +"Used only when the text is confidently detected as the target language." = "Wird nur verwendet, wenn der Text sicher als Zielsprache erkannt wird."; +"Detected %@. Translating to %@." = "%@ erkannt. Übersetzung nach %@."; +"Translate to %@" = "Nach %@ übersetzen"; +"This text already appears to be in %@ (detected %@)." = "Dieser Text scheint bereits auf %@ zu sein (erkannt: %@)."; diff --git a/App/Resources/en.lproj/Localizable.strings b/App/Resources/en.lproj/Localizable.strings index 604005d..3336ef5 100644 --- a/App/Resources/en.lproj/Localizable.strings +++ b/App/Resources/en.lproj/Localizable.strings @@ -104,3 +104,10 @@ "Render bold, italic, headings, lists, code and links when the source is Markdown." = "Render bold, italic, headings, lists, code and links when the source is Markdown."; "Close with Esc without clicking" = "Close with Esc without clicking"; "The panel takes keyboard focus while it is visible. The source app stays frontmost." = "The panel takes keyboard focus while it is visible. The source app stays frontmost."; +"Translate the other direction when the text is already in the target language" = "Translate the other direction when the text is already in the target language"; +"Translate the other direction" = "Translate the other direction"; +"Fallback target language" = "Fallback target language"; +"Used only when the text is confidently detected as the target language." = "Used only when the text is confidently detected as the target language."; +"Detected %@. Translating to %@." = "Detected %@. Translating to %@."; +"Translate to %@" = "Translate to %@"; +"This text already appears to be in %@ (detected %@)." = "This text already appears to be in %@ (detected %@)."; diff --git a/App/Settings/FallbackTargetSettings.swift b/App/Settings/FallbackTargetSettings.swift new file mode 100644 index 0000000..196c0ae --- /dev/null +++ b/App/Settings/FallbackTargetSettings.swift @@ -0,0 +1,54 @@ +import SprachmittlerCore +import SprachmittlerEngines +import SwiftUI + +/// The optional reverse-direction controls in Settings ▸ General. +struct FallbackTargetSettings: View { + @Binding var autoSwitchTarget: Bool + @Binding var fallbackTargetLanguage: String + let targetLanguage: String + let recentTargets: [ModelLanguage] + + @State private var showLanguagePicker = false + + private var fallbackTarget: ModelLanguage { + HyMT3Languages.resolve(fallbackTargetLanguage) ?? HyMT3Languages.english + } + + var body: some View { + Toggle( + String( + localized: "Translate the other direction when the text is already in the target language" + ), + isOn: $autoSwitchTarget + ) + .accessibilityLabel(String(localized: "Translate the other direction")) + if autoSwitchTarget { + LabeledContent(String(localized: "Fallback target language")) { + Button { + showLanguagePicker.toggle() + } label: { + HStack { + Text(fallbackTarget.localizedDisplayName) + Image(systemName: "chevron.up.chevron.down") + .font(.caption) + } + } + .popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) { + LanguagePickerView( + selection: Binding( + get: { fallbackTarget }, + set: { fallbackTargetLanguage = $0.code } + ), + recent: recentTargets, + excluding: targetLanguage + ) + } + .accessibilityLabel(String(localized: "Fallback target language")) + } + Text(String(localized: "Used only when the text is confidently detected as the target language.")) + .font(.caption) + .foregroundStyle(.secondary) + } + } +} diff --git a/App/Settings/SettingsView.swift b/App/Settings/SettingsView.swift index 481013b..ba7f937 100644 --- a/App/Settings/SettingsView.swift +++ b/App/Settings/SettingsView.swift @@ -123,6 +123,11 @@ struct SettingsView: View { ) .font(.caption) .foregroundStyle(.secondary) + FallbackTargetSettings( + autoSwitchTarget: $draft.autoSwitchTarget, + fallbackTargetLanguage: $draft.fallbackTargetLanguage, + targetLanguage: draft.targetLanguage, recentTargets: draft.recentTargets + ) } Section(String(localized: "Double copy")) { diff --git a/MANIFEST.sha256 b/MANIFEST.sha256 index 5844bfc..1453f06 100644 --- a/MANIFEST.sha256 +++ b/MANIFEST.sha256 @@ -18,7 +18,7 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk 2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml 3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md 593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift -57bb84de7d482ba5a4a51126b647a99f595b1af8e3739a5db63dd4d6006f28bd ./App/AppEnvironment.swift +6b939be53c45030f2b72c8a7a9f818528feeaad5b8e82822227df5cba601a163 ./App/AppEnvironment.swift dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift 69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist 36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift @@ -27,11 +27,11 @@ dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnost 3b001166f13cac42136917cfde0277c6cd8cfa922280832a4065081b822b3f9d ./App/MenuBar/StatusMenuView.swift c4a25b6c1207197109d12ea740dc15ad8aa75b6304d901110aa3e10570cd65a0 ./App/Onboarding/OnboardingView.swift ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboarding/README.md -eaf54c09c3df9847f456cb81f198df3b82fa53f02f1fad4918af5549e92ddc7c ./App/Panel/LanguagePickerView.swift +382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift 76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift 0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift -aa364e7cb6373cdeaea0c24f59c959ebcdca228be21a27c6fae431463a6d2c04 ./App/Panel/PanelView+Content.swift -278b9bd96ffe8c322703dec7c660632351c8e9a1996b0ee5713299f3de4ae082 ./App/Panel/PanelView.swift +1887d05e9b6e24658787f57cb0fcc347352a831b8c8322a4af54d18720d264b7 ./App/Panel/PanelView+Content.swift +41c47cba0a4ff81a8e97210c91642fcc1e15330d5917e44cfd01792c0b13c623 ./App/Panel/PanelView.swift bd37b327672595d55c263f109005b816406cce5928ac58c66286cee0f5d16531 ./App/Panel/README.md 9e09591204b9ca4518a031fc856b0cd01245fe8c4e14aa7238e75a83ab05d4c3 ./App/Panel/TranslationPanel.swift 9e8223452ecc9eb20a4e0395d225b93871c4fd2cccbdfe58880620c30d3bb047 ./App/Panel/WindowDragArea.swift @@ -47,10 +47,11 @@ f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resource 182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512.png 2c8e82d99378ff2fe0ca98754a3ef29861f0130c54008634106532d0754760d6 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png f23266b9672263c92ced1d26fe4dafa75a14d530eb9bc5fc1f599034d597ab48 ./App/Resources/Assets.xcassets/Contents.json -1da14ac15fda89935795e6a9faa5274cf6a2047de56f635be7d6da01699c2cdf ./App/Resources/de.lproj/Localizable.strings -3fcec362d3bd5776af97259d92f9e6349a927d8730fb06f3f8776c97b7a10606 ./App/Resources/en.lproj/Localizable.strings +63f4c90b4347e48a7e7bd81bafee1e2f8c251e220b463f3fdb19c82b33ab43b3 ./App/Resources/de.lproj/Localizable.strings +679983eb225cd2de1b996168bdee527018b1f2a3130e51ab7a5224e115d15af4 ./App/Resources/en.lproj/Localizable.strings +d24fada1051cf3412ceac9d0da308cf510c450b4891fa14d0c8c3defd08a9d3d ./App/Settings/FallbackTargetSettings.swift dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md -13ded50c5202ce32bbe6d8432f0701f7d71bf9bc99e4b5e02e688b51416053b9 ./App/Settings/SettingsView.swift +d0e25575fc43e42b8fa5da74499396499a3112334f80edeebaaa0a715c505b30 ./App/Settings/SettingsView.swift d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile @@ -69,7 +70,8 @@ ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/Spr dada1b00037d12da0df03a24d1140e428beb9488fde7e0a9d99d0cca58d1a4ca ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SprachmittlerCapture.swift 728ab857854f1f2bb46f032a13f6d47edd491ee0d6ca0aa8bf2b98f91ccb3c23 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SystemPasteboard.swift 7c580669d76ca3154889a2f3045a1e2689c8984398163496e0ce4cdcad9ae880 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift -ec9fea234c3ba2b1d3ef3b308537071bb1e72bd913da9271f4b291c26f62d5d8 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift +37f715a9755db8c21bde2f9e957a5023c8892b2c90282bb2fdd5495302c121a9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift +fe257f0e38b0b6b65eae175d8f6360358ab7956b8c611b460e66259926770eb7 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift 7921d56341b4b6fe4392989b30de91bb2aeb91a8d52d840dc9602a3d5a6134dd ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift 5159e03a08507c4d6f61479cd4ce389e9541a8df4540ef6540cedaba6e8133a1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift 02421321864ecf0540a96b55a692e91eacb9364d579735d20b9ca94ebcf99a80 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureText.swift @@ -84,7 +86,7 @@ cc89553a898735a1288bdd1c67a04fbcd282f99ee812a83c8b18eff9627ab65d ./Packages/Spr 39cec81db2748fd5e01c5d6ade00bae5babf4a68d7d472a69e98b20884585c5f ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Loggers.swift 83b6c93fc950df1fa8e4942521187a0ee3ecb319b5ffec6deef6047ef8d2b171 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OllamaErrorMapping.swift b7dfab9b2c613071b97bc329378eae47b97305cae758221fba787c8be4eb52f5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift -e46605bc2ff74d4a122ac23bce763b847b9930abbe2b9d2a5f1ea1ed0cb5d6e7 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift +20e2a546fad6ccfee5458889d5c0a6601af0d8602eedc44a29a1da69f3eb3416 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift c52e182fdc6806a06f7b516806140ef26aad8c44e72f9e5beb9135acbe28b878 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift 563d79ceae06a20e8a5b78e155bfe8489bac8f5267a8c3d064fd5c50ecc66cf5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift 761c20b4a1c063ac39648c3d24d8864a0329ff348eaf45db4fb27c573f15e44a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift @@ -114,6 +116,7 @@ c473fa0f2c89d4a4f75307e81a6a5d28f1f21f3bffcc8911bb30487d27f64486 ./Packages/Spr dfe9d284e76ae67a42418c69dae4f84810b9ac7e6d3af675ded1625dd083282b ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/RepetitionDetector.swift 5ddee40aab9a5e099ffdb3c7844ae9d19ea44c885a89a774335c66b6927de62d ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SamplingOptions.swift 1a0d4d9149432f7771a84060377eda2589d14b9041d9f296b871dc4ae3e92718 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationAdapter.swift +b09e5a629c23405f1097a79c6a2ba13dbd93cdca307ee885e47c79fff8f239c5 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift 8969928cf7b9a71d9aeb2ee36fd6a70cec1c7ba9fdd5f42c23d4bf28e49a43b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationWarning.swift 418b1f3737fcf926815055c4f4f3409b292e6afcf0d6b81f37d1160b9f65ac35 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift 43d7f19f92767fb2109dadf939ec4e829a58bd738f81c8abe7b8f3c92e58f9bd ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift @@ -161,7 +164,7 @@ c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/Spr 3443a4e2a7d3d493b9d604875f0abec2f3a515fd162f6af41e25f48c78185b57 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift b639d452d78dcda9e9f3b5ac3298e8499a7837a955839ae5203b508944df2c63 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClass.swift b768d43f50bd4fcede0f3c654787771a605b6ea2648cac722d0e78dd913b4fa5 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClassifier.swift -983997717ee3a06b7355a9611a27f7c93a631a8434fd9bcfc79f8497c4a3696d ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift +9eebbc1339104d8a0b0f9f579d0c9f0bf69b05b5ad1a4550cf645ca3197686dd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift 41aeff6d807caa027f9496a4bd6048bdde55d6eeb4a11b2acdf445dff39735bc ./Packages/SprachmittlerKit/Sources/SprachmittlerText/MarkdownPresentation.swift c7591458a2fcf4813a166cf4f15aaca69688a85e319cf71ebd5c2dcffba756b8 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedToken.swift 2ec31538fe5a2ed98fcce6b815c1844cfd30a53073f4987eda8043bcd222d58d ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedTokenScanner.swift @@ -194,14 +197,14 @@ efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/Spr 87e92d608b14675873a6554a3bcce951fb62b45b95ce32972df978cada697a43 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PlaceholderTests.swift d2d3507f437c7126bf15ebcba7be6d03794a73a637089c511c99096bc564cc5a ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ServicesProviderTests.swift f7375e2cd08709d7b590ae4f6d70be3edb88f122f9fb3aeaac37c826ff637d12 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/SystemPasteboardTests.swift -4d5776174be0ae5a17d3414b410671c83b492029af47a9204311be066d0f9119 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift +d8347d9f17250e5e6a130596855dce10e4a8ea37305ac3fd2019ec3fc5b31b07 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift 4ca70a674a35b723f7608bfe9b250b8572586ce4923e9965245626588935bb6e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift 2d5742a1fbbb65044455cea92b9f95b9d39f5236e92e4f152b141bcf964c639e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMappingTests.swift c584df764e9fa0a029ed9f17c1a3b27cb4e3b91005f27171d5553aaf51edb48a ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift 95ca20f1c4cf0fd68f29a488770a1d6d7911c534913a0f88515ea1fe4f4cdb9e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LogRedactionTests.swift 6610797e6dd77401d1bce624d65e84db9bdda95820b1f56add1d24cea1f5df91 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LoggingContractTests.swift 8c0462d50ff3796aba6024349083d8b1ede654b495790d7610f95aecc8870001 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift -caa6eb7016ecd217811761530af2dcc1f6abbc03548b4267e6a94ed691c2a0fd ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift +954dd7e4c6b06603a3619c3f112bb67049cdff32038c5cdea2ecd9b79fd07f61 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PlaceholderTests.swift 9a1a9671fdde945d3dd8356ea4dab8b6c30120d868970507883a77657701c500 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift 304cc5262dd6713041bb12cfa5502e5971c1c7e486c33be79818985bc0545232 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift @@ -215,6 +218,7 @@ e56dc9de2741d731b02ff3bb39ee74532ac4350d232eb66fac86ffb770cb7a86 ./Packages/Spr 7d1c6fd3193bcd169be2421a56e42fca82e7e44a5a288dd6482957ab6c50af21 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptFixtureTests.swift 8bb2e2310a40e5923fa77014ac5209cf09cc8a52056a22cae9544f3468e1d2cc ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptGoldenTests.swift d93aa1ae54f4a6f49aba4f2badb065a86d29c335afb6efd0890684759718a3c3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptPolicyTests.swift +7df7f5675c61b74f752870cb56824054fdbb73878ccc35f99c105fd55c442af4 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift b921811eb2bad2cde5a5c199b9c5e4fac710740193789d324d73580d2b8c7abf ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/PlaceholderTests.swift 78fd25235b625f82115f3d14c6a9863949055fbead95c9ef83668866bf255d10 ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerLiveTests/PlaceholderTests.swift @@ -246,16 +250,16 @@ a90dc29af451dac1557a88081a53defcffa8d21fdc0029d7fc19bc3a34d81598 ./Packages/Spr f9ede3201de7a3d092b2f114dd7f131dafd3b2d6614c0ba91d6181e326ab005b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/en-sample.txt b0a7d3451d8830654fe79476b8d32d95709d956817a4436f58c0f73bbd8d3194 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/markdown-sample.md 6ceff5d7b34dc4f4099c1ac8415f89b680f64608c3b9e140c4dee1737cf2477b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/placeholders.txt -60f1c5ea4134593dc721650f32c48b9cf20c02fd6e8b692d8bb1da9e02490518 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift +436ed18c9c1cd8bf15df11e2c2f9ca974f9a6f17ca8b894e5ffef999458653fa ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift 80d28cb607b67a35cda89d86e2819e29e71b38e8234557683cb7c96f611037d1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/MarkdownPresentationTests.swift 8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift 67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift -eeff058dee89a14f9c9207bc5a28d5f06a733c9f596af7bd4553a90c199780cf ./README.md +ae0f9746adc229ad1140b6961fd392c8cb7a9b3ccddc83236d2d8ef88232f393 ./README.md f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg -3b7b1fe301c5f715c6f4f74cc553a907c1ae89e669d5625d414dc3dae51d0216 ./docs/ARCHITECTURE.md +2b6df8cf5b6637e217288c87c51f981b8d84c60de336aff72986115f302d704a ./docs/ARCHITECTURE.md 018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md -017ff14372220594a25a9d139145fa6cf05a3b50ddd2d1f54f8e98b6fe6463c9 ./docs/DECISIONS.md +5cc9fcccdf45a55e6be22c4e19faa8f1bb07bc7a8e8b64a43532a8fe627c131d ./docs/DECISIONS.md 5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md @@ -265,12 +269,12 @@ a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_E e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md 4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md -e6208158c5230a63ddcf5fca4f6a7f9559f34c7026a5310398891955c6277b89 ./docs/PROGRESS.md +be500879c3170a776dbe15697a8138d18b8961312c95be6373c665a575804ab9 ./docs/PROGRESS.md c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md 2e6c7ba67d857db7cddf1e31b5a6516f70b8094e9115094b58156f9e6626452c ./docs/SELECTION_AND_CLIPBOARD.md 8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md -d86aa67b08549ecce44e14d1e4fde0050ea5e89f77643733efd312fa42ef4e25 ./docs/TRANSLATION_OUTPUT.md -d59e6bf414777e4a068b08c2e81fcc3dee220034f0916e3867f338c4b7e6f4a3 ./docs/USER_GUIDE.md +c3c232d61ad70ebf375d1a7ad3cfcfd51810c86ff89d7a01fcd10c9bf3440fb6 ./docs/TRANSLATION_OUTPUT.md +ff36cf983bfb0ee16730ae9229d32a607b95ccb054d1069ffc090c2edc5b0311 ./docs/USER_GUIDE.md 373b20746a6ed145ee598786458a97cead5cacd97a339db14b3e2341645c6c8d ./evaluation/README.md a60f1917c64ac8c3df0d01dd55818652ae100a6d750c34be24675b33226cad45 ./evaluation/corpus.example.json a5c4b95257aa02eca20ae98acf68dee329acb870f16fb3ac549038627327da71 ./evaluation/corpus.schema.json diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift new file mode 100644 index 0000000..0350899 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift @@ -0,0 +1,121 @@ +import Foundation +import SprachmittlerEngines + +private struct DecodedDirection { + let autoSwitch: Bool + let fallback: String +} + +extension AppSettings { + public init(from decoder: any Decoder) throws { + let defaults = AppSettings() + let container = try decoder.container(keyedBy: CodingKeys.self) + + endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint + allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint) + ?? defaults.allowRemoteEndpoint + model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model + fastModel = container.contains(.fastModel) + ? try container.decodeIfPresent(String.self, forKey: .fastModel) + : defaults.fastModel + let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage) + ?? defaults.targetLanguage + targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage + let direction = try Self.decodeDirection(from: container, defaults: defaults, target: targetLanguage) + autoSwitchTarget = direction.autoSwitch + fallbackTargetLanguage = direction.fallback + recentTargetLanguages = try Self.decodeRecentTargets(from: container) + let limits = try Self.decodeLimits(from: container, defaults: defaults) + doubleCopyWindowMs = limits.window + maxCharactersLatin = limits.latin + maxCharactersCJK = limits.cjk + numCtx = limits.numCtx + numPredict = limits.numPredict + translationFontSize = limits.fontSize + let sampling = try Self.decodeSampling(from: container, defaults: defaults) + temperature = sampling.temperature + topP = sampling.topP + topK = sampling.topK + repeatPenalty = sampling.repeatPenalty + let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded) + ?? defaults.keepModelLoaded + keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded + warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch) ?? defaults.warmUpOnLaunch + let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy) + ?? defaults.promptVariantPolicy + promptVariantPolicy = policy + // Auto-copy is a hard invariant: decoding cannot turn it on. + autoCopy = false + showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview) + ?? defaults.showSourcePreview + renderMarkdown = try container.decodeIfPresent(Bool.self, forKey: .renderMarkdown) ?? defaults.renderMarkdown + closeWithEscape = try container.decodeIfPresent(Bool.self, forKey: .closeWithEscape) ?? defaults.closeWithEscape + launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? defaults.launchAtLogin + keepRecentTranslationInMemory = try container.decodeIfPresent( + Bool.self, + forKey: .keepRecentTranslationInMemory + ) ?? defaults.keepRecentTranslationInMemory + hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding) + ?? defaults.hasCompletedOnboarding + settingsVersion = Self.currentVersion + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(endpoint, forKey: .endpoint) + try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint) + try container.encode(model, forKey: .model) + try container.encode(fastModel, forKey: .fastModel) + try container.encode(targetLanguage, forKey: .targetLanguage) + try container.encode(autoSwitchTarget, forKey: .autoSwitchTarget) + try container.encode(fallbackTargetLanguage, forKey: .fallbackTargetLanguage) + try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages) + try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs) + try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin) + try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK) + try container.encode(numCtx, forKey: .numCtx) + try container.encode(numPredict, forKey: .numPredict) + try container.encode(temperature, forKey: .temperature) + try container.encode(topP, forKey: .topP) + try container.encode(topK, forKey: .topK) + try container.encode(repeatPenalty, forKey: .repeatPenalty) + try container.encode(keepModelLoaded, forKey: .keepModelLoaded) + try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch) + try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy) + try container.encode(autoCopy, forKey: .autoCopy) + try container.encode(showSourcePreview, forKey: .showSourcePreview) + try container.encode(translationFontSize, forKey: .translationFontSize) + try container.encode(renderMarkdown, forKey: .renderMarkdown) + try container.encode(closeWithEscape, forKey: .closeWithEscape) + try container.encode(launchAtLogin, forKey: .launchAtLogin) + try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory) + try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding) + try container.encode(settingsVersion, forKey: .settingsVersion) + } + + private static func decodeDirection( + from container: KeyedDecodingContainer, + defaults: AppSettings, + target: String + ) throws -> DecodedDirection { + let autoSwitch = try container.decodeIfPresent(Bool.self, forKey: .autoSwitchTarget) + ?? defaults.autoSwitchTarget + let code = try container.decodeIfPresent(String.self, forKey: .fallbackTargetLanguage) + ?? defaults.fallbackTargetLanguage + return DecodedDirection( + autoSwitch: autoSwitch, + fallback: AppSettings.normalizedFallback(code, target: target) + ) + } + + private static func decodeRecentTargets( + from container: KeyedDecodingContainer + ) throws -> [String] { + let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? [] + var seen = Set() + return recents.compactMap { HyMT3Languages.resolve($0)?.code } + .filter { seen.insert($0).inserted } + .prefix(3) + .map(\.self) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift index a688290..817aea4 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift @@ -29,6 +29,10 @@ public struct AppSettings: Codable, Sendable, Equatable { public var fastModel: String? /// The selected target BCP-47 code. public var targetLanguage: String + /// Translate into the fallback when the source is already the target. + public var autoSwitchTarget: Bool + /// The fallback target BCP-47 code used by `autoSwitchTarget`. + public var fallbackTargetLanguage: String /// Up to three recent target codes, most recent first. public var recentTargetLanguages: [String] /// The double-copy window in milliseconds (300–1000). @@ -82,6 +86,10 @@ public struct AppSettings: Codable, Sendable, Equatable { model = HyMT3ModelPreset.defaultModel fastModel = HyMT3ModelPreset.fastModel targetLanguage = systemCode ?? HyMT3Languages.english.code + autoSwitchTarget = true + fallbackTargetLanguage = targetLanguage == HyMT3Languages.english.code + ? HyMT3Languages.german.code + : HyMT3Languages.english.code recentTargetLanguages = [] doubleCopyWindowMs = 500 maxCharactersLatin = 4000 @@ -111,6 +119,11 @@ public struct AppSettings: Codable, Sendable, Equatable { HyMT3Languages.resolve(targetLanguage) ?? HyMT3Languages.english } + /// The fallback target, always a catalogue entry. + public var fallbackTargetModel: ModelLanguage { + HyMT3Languages.resolve(fallbackTargetLanguage) ?? HyMT3Languages.english + } + /// The recent targets that still exist in the catalogue. public var recentTargets: [ModelLanguage] { recentTargetLanguages.compactMap(HyMT3Languages.resolve) @@ -123,6 +136,9 @@ public struct AppSettings: Codable, Sendable, Equatable { /// Records a target as recent, keeping at most three unique codes. public mutating func noteTarget(_ language: ModelLanguage) { + if language.code != targetLanguage, language.code == fallbackTargetLanguage { + fallbackTargetLanguage = targetLanguage + } targetLanguage = language.code recentTargetLanguages.removeAll { $0 == language.code } recentTargetLanguages.insert(language.code, at: 0) @@ -132,6 +148,7 @@ public struct AppSettings: Codable, Sendable, Equatable { /// Clamps values edited outside the decoder (Settings UI) to the safe ranges. public mutating func sanitize() { targetLanguage = HyMT3Languages.resolve(targetLanguage)?.code ?? HyMT3Languages.english.code + fallbackTargetLanguage = Self.normalizedFallback(fallbackTargetLanguage, target: targetLanguage) doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000) maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000) maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000) @@ -165,7 +182,7 @@ public struct AppSettings: Codable, Sendable, Equatable { Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK) } - private struct DecodedLimits { + struct DecodedLimits { let window: Int let latin: Int let cjk: Int @@ -174,14 +191,14 @@ public struct AppSettings: Codable, Sendable, Equatable { let fontSize: Int } - private struct DecodedSampling { + struct DecodedSampling { let temperature: Double let topP: Double let topK: Int let repeatPenalty: Double } - private static func decodeLimits( + static func decodeLimits( from container: KeyedDecodingContainer, defaults: AppSettings ) throws -> DecodedLimits { @@ -217,7 +234,7 @@ public struct AppSettings: Codable, Sendable, Equatable { ) } - private static func decodeSampling( + static func decodeSampling( from container: KeyedDecodingContainer, defaults: AppSettings ) throws -> DecodedSampling { @@ -237,8 +254,9 @@ public struct AppSettings: Codable, Sendable, Equatable { ) } - private enum CodingKeys: String, CodingKey { - case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, recentTargetLanguages + enum CodingKeys: String, CodingKey { + case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, autoSwitchTarget + case fallbackTargetLanguage, recentTargetLanguages case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown @@ -246,95 +264,15 @@ public struct AppSettings: Codable, Sendable, Equatable { case settingsVersion } - /// Decodes with v0 migration: missing or unknown fields fall back to defaults, and an old - /// `settingsVersion` is upgraded to the current one. Unknown keys are ignored by Codable. - public init(from decoder: any Decoder) throws { - let defaults = AppSettings() - let container = try decoder.container(keyedBy: CodingKeys.self) - - endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint - allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint) - ?? defaults.allowRemoteEndpoint - model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model - fastModel = container.contains(.fastModel) - ? try container.decodeIfPresent(String.self, forKey: .fastModel) - : defaults.fastModel - let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage) - ?? defaults.targetLanguage - targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage - let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? [] - var seen = Set() - recentTargetLanguages = recents.compactMap { HyMT3Languages.resolve($0)?.code } - .filter { seen.insert($0).inserted } - .prefix(3) - .map(\.self) - let limits = try Self.decodeLimits(from: container, defaults: defaults) - doubleCopyWindowMs = limits.window - maxCharactersLatin = limits.latin - maxCharactersCJK = limits.cjk - numCtx = limits.numCtx - numPredict = limits.numPredict - translationFontSize = limits.fontSize - let sampling = try Self.decodeSampling(from: container, defaults: defaults) - temperature = sampling.temperature - topP = sampling.topP - topK = sampling.topK - repeatPenalty = sampling.repeatPenalty - let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded) - ?? defaults.keepModelLoaded - keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded - warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch) ?? defaults.warmUpOnLaunch - let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy) - ?? defaults.promptVariantPolicy - promptVariantPolicy = policy - // Auto-copy is a hard invariant: decoding cannot turn it on. - autoCopy = false - showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview) - ?? defaults.showSourcePreview - renderMarkdown = try container.decodeIfPresent(Bool.self, forKey: .renderMarkdown) ?? defaults.renderMarkdown - closeWithEscape = try container.decodeIfPresent(Bool.self, forKey: .closeWithEscape) ?? defaults.closeWithEscape - launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? defaults.launchAtLogin - keepRecentTranslationInMemory = try container.decodeIfPresent( - Bool.self, - forKey: .keepRecentTranslationInMemory - ) ?? defaults.keepRecentTranslationInMemory - hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding) - ?? defaults.hasCompletedOnboarding - settingsVersion = Self.currentVersion + static func normalizedFallback(_ code: String, target: String) -> String { + let resolved = HyMT3Languages.resolve(code)?.code ?? HyMT3Languages.english.code + guard resolved == target else { return resolved } + return target == HyMT3Languages.english.code + ? HyMT3Languages.german.code + : HyMT3Languages.english.code } - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(endpoint, forKey: .endpoint) - try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint) - try container.encode(model, forKey: .model) - try container.encode(fastModel, forKey: .fastModel) - try container.encode(targetLanguage, forKey: .targetLanguage) - try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages) - try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs) - try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin) - try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK) - try container.encode(numCtx, forKey: .numCtx) - try container.encode(numPredict, forKey: .numPredict) - try container.encode(temperature, forKey: .temperature) - try container.encode(topP, forKey: .topP) - try container.encode(topK, forKey: .topK) - try container.encode(repeatPenalty, forKey: .repeatPenalty) - try container.encode(keepModelLoaded, forKey: .keepModelLoaded) - try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch) - try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy) - try container.encode(autoCopy, forKey: .autoCopy) - try container.encode(showSourcePreview, forKey: .showSourcePreview) - try container.encode(translationFontSize, forKey: .translationFontSize) - try container.encode(renderMarkdown, forKey: .renderMarkdown) - try container.encode(closeWithEscape, forKey: .closeWithEscape) - try container.encode(launchAtLogin, forKey: .launchAtLogin) - try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory) - try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding) - try container.encode(settingsVersion, forKey: .settingsVersion) - } - - private static func clamp(_ value: Int, to range: ClosedRange) -> Int { + static func clamp(_ value: Int, to range: ClosedRange) -> Int { min(max(value, range.lowerBound), range.upperBound) } } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift index 5087602..7697109 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift @@ -1,6 +1,7 @@ import Foundation import Observation import SprachmittlerEngines +import SprachmittlerText /// The panel phase from `docs/ARCHITECTURE.md` §10. public enum PanelPhase: Sendable, Equatable { @@ -20,6 +21,10 @@ public enum PanelPhase: Sendable, Equatable { public struct PanelConfiguration: Sendable, Equatable { /// The selected target language. public var target: ModelLanguage + /// Whether the source-equals-target direction switches to `fallbackTarget`. + public var autoSwitchTarget: Bool + /// The fallback target used when the source is already the target. + public var fallbackTarget: ModelLanguage? /// The selected model tag. public var model: String /// The Ollama keep-alive value. @@ -47,6 +52,8 @@ public struct PanelConfiguration: Sendable, Equatable { translationFontSize: Int = 17, renderMarkdown: Bool = true, closeWithEscape: Bool = true, + autoSwitchTarget: Bool = true, + fallbackTarget: ModelLanguage? = HyMT3Languages.english, recentTargets: [ModelLanguage] = [] ) { self.target = target @@ -57,6 +64,8 @@ public struct PanelConfiguration: Sendable, Equatable { self.translationFontSize = translationFontSize self.renderMarkdown = renderMarkdown self.closeWithEscape = closeWithEscape + self.autoSwitchTarget = autoSwitchTarget + self.fallbackTarget = fallbackTarget self.recentTargets = recentTargets } } @@ -83,8 +92,12 @@ public final class PanelViewModel { public private(set) var didCopy = false /// True while a Replace action is running. public private(set) var isReplacing = false - /// The current target, model and prompt settings. + /// The current target, model and prompt settings. `target` is the user's saved preference. public private(set) var configuration: PanelConfiguration + /// The target used by the current request, after an optional reverse-direction switch. + public private(set) var effectiveTarget: ModelLanguage + /// The saved target that was replaced by `effectiveTarget`, or nil. + public private(set) var autoSwitchedFrom: ModelLanguage? /// True after the user dismisses the same-language advisory. public private(set) var sameLanguageDismissed = false @@ -100,9 +113,11 @@ public final class PanelViewModel { public let onTargetChanged: @MainActor (ModelLanguage) -> Void private let session: TranslationSession + private let detector: any LanguageDetecting private var eventTask: Task? private var currentEpoch: UInt64 = 0 private var lastCaptured: CapturedText? + private var directionOverride = false /// Creates a panel model. public init( @@ -112,10 +127,13 @@ public final class PanelViewModel { replace: (@MainActor () async -> InsertionOutcome)? = nil, onCloseRequest: @escaping @MainActor () -> Void = {}, eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil, - onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in } + onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in }, + detector: any LanguageDetecting = NaturalLanguageDetector() ) { self.session = session self.configuration = configuration + effectiveTarget = configuration.target + self.detector = detector self.copy = copy self.replace = replace self.onCloseRequest = onCloseRequest @@ -180,8 +198,8 @@ public final class PanelViewModel { error?.recoveryAction } - /// Synchronously resets the visible state before the panel is shown. - public func prepare(_ captured: CapturedText) { + /// Synchronously resets the visible state before the panel is shown and resolves the direction. + public func prepare(_ captured: CapturedText, resetDirectionOverride: Bool = true) { currentEpoch = 0 lastCaptured = captured source = captured @@ -189,29 +207,47 @@ public final class PanelViewModel { warnings = [] error = nil timing = nil - sourceLanguage = nil didCopy = false isReplacing = false - sameLanguageDismissed = false + if resetDirectionOverride { + directionOverride = false + } + let normalized = TextNormalization.normalizeInput(captured.text) + let detection = detector.detect(normalized) + sourceLanguage = detection?.code + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: configuration.target, + fallbackTarget: configuration.fallbackTarget, + detection: detection, + autoSwitch: configuration.autoSwitchTarget, + override: directionOverride + ) + effectiveTarget = direction.target + autoSwitchedFrom = direction.didSwitch ? direction.originalTarget : nil + sameLanguageDismissed = directionOverride phase = .translating } /// Starts a translation for a captured text. public func begin(_ captured: CapturedText) async { - prepare(captured) + await begin(captured, resetDirectionOverride: true) + } + + private func begin(_ captured: CapturedText, resetDirectionOverride: Bool) async { + prepare(captured, resetDirectionOverride: resetDirectionOverride) _ = await session.start(request(for: captured)) } - /// Retries the last captured text. + /// Retries the last captured text without discarding a manual direction choice. public func retry() async { guard let lastCaptured else { return } - await begin(lastCaptured) + await begin(lastCaptured, resetDirectionOverride: false) } - /// Retranslates after an external target change. + /// Retranslates after an external target change and re-evaluates the direction. public func retranslate() async { guard let lastCaptured else { return } - await begin(lastCaptured) + await begin(lastCaptured, resetDirectionOverride: true) } /// Shows a capture-time error such as a too-long selection. @@ -225,15 +261,33 @@ public final class PanelViewModel { warnings = [] timing = nil sourceLanguage = nil + effectiveTarget = configuration.target + autoSwitchedFrom = nil + directionOverride = false } - /// Changes the target and retranslates the current selection. + /// Changes the saved target from the panel and retranslates the current selection. public func setTarget(_ language: ModelLanguage) async { - guard language.code != configuration.target.code else { return } + guard language.code != effectiveTarget.code else { return } configuration.target = language + effectiveTarget = language + autoSwitchedFrom = nil + directionOverride = true onTargetChanged(language) if let lastCaptured { - await begin(lastCaptured) + await begin(lastCaptured, resetDirectionOverride: false) + } + } + + /// Uses another language for this capture only. It does not change the saved target. + public func overrideTarget(_ language: ModelLanguage) async { + guard language.code != effectiveTarget.code else { return } + effectiveTarget = language + autoSwitchedFrom = nil + directionOverride = true + sameLanguageDismissed = true + if let lastCaptured { + await begin(lastCaptured, resetDirectionOverride: false) } } @@ -268,7 +322,13 @@ public final class PanelViewModel { /// Updates the settings snapshot without restarting the current request. public func updateConfiguration(_ configuration: PanelConfiguration) { + let targetChanged = configuration.target.code != self.configuration.target.code self.configuration = configuration + if targetChanged || source == nil { + effectiveTarget = configuration.target + autoSwitchedFrom = nil + directionOverride = false + } } /// Resets the panel and cancels the active request. The event stream stays open. @@ -284,6 +344,9 @@ public final class PanelViewModel { didCopy = false isReplacing = false sameLanguageDismissed = false + effectiveTarget = configuration.target + autoSwitchedFrom = nil + directionOverride = false lastCaptured = nil } @@ -296,7 +359,7 @@ public final class PanelViewModel { private func request(for captured: CapturedText) -> TranslationSessionRequest { TranslationSessionRequest( captured: captured, - target: configuration.target, + target: effectiveTarget, model: configuration.model, keepAlive: configuration.keepAlive, sampling: configuration.sampling @@ -308,7 +371,7 @@ public final class PanelViewModel { case let .started(epoch, request): currentEpoch = epoch source = request.captured - configuration.target = request.target + effectiveTarget = request.target translation = "" warnings = [] error = nil diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift new file mode 100644 index 0000000..9294f47 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift @@ -0,0 +1,47 @@ +import SprachmittlerText + +/// The effective target for one translation, after an optional reverse-direction switch. +public struct TranslationDirection: Sendable, Equatable { + /// The language the request will translate into. + public let target: ModelLanguage + /// True when the configured target was replaced by the fallback target. + public let didSwitch: Bool + /// The configured target when `didSwitch` is true. + public let originalTarget: ModelLanguage? + + /// Creates a direction. + public init(target: ModelLanguage, didSwitch: Bool, originalTarget: ModelLanguage?) { + self.target = target + self.didSwitch = didSwitch + self.originalTarget = originalTarget + } +} + +/// Chooses the direction for a capture. Detection stays advisory: a switch needs the same +/// high-confidence agreement as the same-language advisory. +public enum TranslationDirectionPolicy { + /// Resolves the target. + /// + /// - Parameters: + /// - configuredTarget: The user's saved target language. + /// - fallbackTarget: The language to use when the source is already the configured target. + /// - detection: The advisory source-language detection. + /// - autoSwitch: Whether the fallback is enabled. + /// - override: True after an explicit target choice for the current capture. + public static func resolve( + configuredTarget: ModelLanguage, + fallbackTarget: ModelLanguage?, + detection: LanguageDetection?, + autoSwitch: Bool, + override: Bool + ) -> TranslationDirection { + guard autoSwitch, !override, let fallbackTarget, + fallbackTarget.code.caseInsensitiveCompare(configuredTarget.code) != .orderedSame, + let detection, + LanguageMatching.isSameLanguage(detection, target: configuredTarget) + else { + return TranslationDirection(target: configuredTarget, didSwitch: false, originalTarget: nil) + } + return TranslationDirection(target: fallbackTarget, didSwitch: true, originalTarget: configuredTarget) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift index 7b6df92..b56d799 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift @@ -37,10 +37,16 @@ public struct NaturalLanguageDetector: LanguageDetecting { let recognizer = NLLanguageRecognizer() recognizer.processString(trimmed) guard let dominant = recognizer.dominantLanguage else { return nil } - let hypotheses = recognizer.languageHypotheses(withMaximum: 3) - let ordered = hypotheses.sorted { lhs, rhs in - lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value - }.map(\.key.rawValue) + let hypotheses = recognizer.languageHypotheses(withMaximum: 5) + // NLLanguageRecognizer returns many near-zero hypotheses. Keep only candidates that + // carry meaningful evidence, so a confident single-language text is not treated as mixed. + let minimumAlternativeConfidence = 0.05 + let ordered = hypotheses + .filter { $0.value >= minimumAlternativeConfidence } + .sorted { lhs, rhs in + lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value + } + .map(\.key.rawValue) let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered return LanguageDetection( code: dominant.rawValue, diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift index 7de60cc..d7f7b20 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift @@ -18,6 +18,9 @@ struct AppSettingsTests { #expect(settings.maxCharactersCJK == 2000) #expect(settings.numCtx == 8192) #expect(settings.translationFontSize == 17) + #expect(settings.autoSwitchTarget) + #expect(HyMT3Languages.resolve(settings.fallbackTargetLanguage) != nil) + #expect(settings.fallbackTargetLanguage != settings.targetLanguage) #expect(settings.renderMarkdown) #expect(settings.closeWithEscape) #expect(!settings.autoCopy) @@ -32,6 +35,8 @@ struct AppSettingsTests { settings.noteTarget(HyMT3Languages.german) settings.temperature = 0.2 settings.translationFontSize = 22 + settings.autoSwitchTarget = false + settings.fallbackTargetLanguage = "fr" settings.renderMarkdown = false settings.closeWithEscape = false settings.launchAtLogin = true @@ -57,6 +62,9 @@ struct AppSettingsTests { #expect(decoded.settingsVersion == AppSettings.currentVersion) #expect(decoded.targetLanguage == "de") #expect(decoded.model == HyMT3ModelPreset.defaultModel) + #expect(decoded.autoSwitchTarget) + #expect(HyMT3Languages.resolve(decoded.fallbackTargetLanguage) != nil) + #expect(decoded.fallbackTargetLanguage != decoded.targetLanguage) #expect(decoded.renderMarkdown) #expect(decoded.closeWithEscape) #expect(!decoded.autoCopy) @@ -91,6 +99,7 @@ struct AppSettingsTests { "repeatPenalty": 9, "keepModelLoaded": "forever", "translationFontSize": 99, + "fallbackTargetLanguage": "xx", "targetLanguage": "xx" } """ @@ -106,6 +115,8 @@ struct AppSettingsTests { #expect(decoded.repeatPenalty == 2) #expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive) #expect(decoded.translationFontSize == 28) + #expect(HyMT3Languages.resolve(decoded.fallbackTargetLanguage) != nil) + #expect(decoded.fallbackTargetLanguage != decoded.targetLanguage) #expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil) } @@ -117,8 +128,9 @@ struct AppSettingsTests { settings.topK = 0 settings.keepModelLoaded = "forever" settings.translationFontSize = 99 + settings.fallbackTargetLanguage = "de" settings.autoCopy = true - settings.targetLanguage = "xx" + settings.targetLanguage = "de" settings.sanitize() #expect(settings.doubleCopyWindowMs == 300) @@ -127,10 +139,33 @@ struct AppSettingsTests { #expect(settings.topK == 1) #expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive) #expect(settings.translationFontSize == 28) + #expect(settings.fallbackTargetLanguage == "en") #expect(!settings.autoCopy) #expect(HyMT3Languages.resolve(settings.targetLanguage) != nil) } + @Test func changingToTheFallbackSwapsThePair() { + var settings = AppSettings() + settings.targetLanguage = HyMT3Languages.german.code + settings.fallbackTargetLanguage = HyMT3Languages.english.code + settings.noteTarget(HyMT3Languages.english) + #expect(settings.targetLanguage == HyMT3Languages.english.code) + #expect(settings.fallbackTargetLanguage == HyMT3Languages.german.code) + } + + @Test func sanitizeKeepsTheFallbackDifferentFromTheTarget() { + var settings = AppSettings() + settings.targetLanguage = HyMT3Languages.german.code + settings.fallbackTargetLanguage = HyMT3Languages.german.code + settings.sanitize() + #expect(settings.fallbackTargetLanguage == HyMT3Languages.english.code) + + settings.targetLanguage = HyMT3Languages.english.code + settings.fallbackTargetLanguage = HyMT3Languages.english.code + settings.sanitize() + #expect(settings.fallbackTargetLanguage == HyMT3Languages.german.code) + } + @Test func endpointPolicyIsEnforced() throws { var settings = AppSettings() settings.endpoint = try #require(URL(string: "http://192.168.1.10:11434")) diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift index c1100c6..444d952 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift @@ -1,5 +1,6 @@ import Foundation import SprachmittlerEngines +import SprachmittlerText import Testing @testable import SprachmittlerCore @@ -12,6 +13,12 @@ struct PanelViewModelTests { source: .doubleCopy ) + private let germanCaptured = CapturedText( + text: "Hallo.", + capturedAt: Date(timeIntervalSince1970: 0), + source: .doubleCopy + ) + @Test func streamsIntoThePanelAndCopyKeepsItOpen() async { let (panel, copies, _) = makePanel( streaming: ImmediateStreaming(deltas: ["Hal", "lo"], result: makeResult("Hallo")) @@ -81,6 +88,89 @@ struct PanelViewModelTests { #expect(panel.sameLanguageWarning == nil) } + @Test func autoSwitchesWhenTheSourceIsTheTarget() async { + let detector = FixedDetector( + detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"]) + ) + let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true) + + await panel.begin(germanCaptured) + await waitFor { panel.phase == .ready } + + #expect(panel.effectiveTarget == HyMT3Languages.english) + #expect(panel.autoSwitchedFrom == HyMT3Languages.german) + #expect(panel.configuration.target == HyMT3Languages.german) + #expect(panel.translation == "en") + } + + @Test func autoSwitchOverrideIsSessionOnly() async { + let detector = FixedDetector( + detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"]) + ) + let (panel, _, targets) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true) + await panel.begin(germanCaptured) + await waitFor { panel.phase == .ready } + + await panel.overrideTarget(HyMT3Languages.german) + await waitFor { panel.phase == .ready && panel.translation == "de" } + + #expect(panel.effectiveTarget == HyMT3Languages.german) + #expect(panel.autoSwitchedFrom == nil) + #expect(panel.configuration.target == HyMT3Languages.german) + #expect(targets.codes.isEmpty) + } + + @Test func explicitTargetPersistsAndDisablesAutoSwitch() async { + let detector = FixedDetector( + detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"]) + ) + let (panel, _, targets) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true) + await panel.begin(germanCaptured) + await waitFor { panel.phase == .ready } + + await panel.setTarget(HyMT3Languages.german) + await waitFor { panel.phase == .ready && panel.translation == "de" } + + #expect(targets.codes == ["de"]) + #expect(panel.effectiveTarget == HyMT3Languages.german) + #expect(panel.autoSwitchedFrom == nil) + } + + @Test func retryKeepsTheManualTarget() async { + let detector = FixedDetector( + detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"]) + ) + let streaming = EchoStreaming() + let (panel, _, _) = makePanel(streaming: streaming, detector: detector, autoSwitch: true) + await panel.begin(germanCaptured) + await waitFor { panel.phase == .ready } + await panel.setTarget(HyMT3Languages.german) + await waitFor { panel.phase == .ready && panel.translation == "de" } + + await panel.retry() + await waitFor { panel.phase == .ready && panel.translation == "de" } + + #expect(panel.effectiveTarget == HyMT3Languages.german) + #expect(await streaming.callCount == 3) + } + + @Test func newCaptureReevaluatesTheDirection() async { + let detector = FixedDetector( + detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"]) + ) + let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true) + await panel.begin(germanCaptured) + await waitFor { panel.phase == .ready } + await panel.overrideTarget(HyMT3Languages.german) + await waitFor { panel.phase == .ready && panel.translation == "de" } + + await panel.begin(germanCaptured) + await waitFor { panel.phase == .ready && panel.translation == "en" } + + #expect(panel.effectiveTarget == HyMT3Languages.english) + #expect(panel.autoSwitchedFrom == HyMT3Languages.german) + } + @Test func changingTargetRetranslatesAndNotifies() async { let streaming = EchoStreaming() let (panel, _, targets) = makePanel(streaming: streaming) @@ -145,7 +235,11 @@ struct PanelViewModelTests { private func makePanel( streaming: any TranslationStreaming, replacement: (@MainActor () async -> InsertionOutcome)? = nil, - onClose: @escaping @MainActor () -> Void = {} + onClose: @escaping @MainActor () -> Void = {}, + detector: any LanguageDetecting = FixedDetector(detection: nil), + autoSwitch: Bool = false, + target: ModelLanguage = HyMT3Languages.german, + fallback: ModelLanguage? = HyMT3Languages.english ) -> (PanelViewModel, CopiedTextBox, TargetBox) { let session = TranslationSession(pipelineFactory: { streaming }) let copies = CopiedTextBox() @@ -153,14 +247,17 @@ struct PanelViewModelTests { let panel = PanelViewModel( session: session, configuration: PanelConfiguration( - target: HyMT3Languages.german, + target: target, model: "test-hy-mt3", - keepAlive: "30m" + keepAlive: "30m", + autoSwitchTarget: autoSwitch, + fallbackTarget: fallback ), copy: { copies.text = $0 }, replace: replacement, onCloseRequest: onClose, - onTargetChanged: { targets.codes.append($0.code) } + onTargetChanged: { targets.codes.append($0.code) }, + detector: detector ) panel.startObserving() return (panel, copies, targets) @@ -271,3 +368,11 @@ private final class ReplaceBox: @unchecked Sendable { private final class CloseBox: @unchecked Sendable { var closed = false } + +private struct FixedDetector: LanguageDetecting { + let detection: LanguageDetection? + + func detect(_ text: String) -> LanguageDetection? { + detection + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift new file mode 100644 index 0000000..28590fa --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift @@ -0,0 +1,117 @@ +import SprachmittlerEngines +import SprachmittlerText +import Testing + +@Suite("Translation direction") +struct TranslationDirectionTests { + private let german = HyMT3Languages.german + private let english = HyMT3Languages.english + + private func detection( + _ code: String, + confidence: Double = 0.9, + alternatives: [String]? = nil + ) -> LanguageDetection { + LanguageDetection(code: code, confidence: confidence, alternatives: alternatives ?? [code]) + } + + @Test func keepsTheConfiguredTargetWhenTheSourceIsDifferent() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: detection("en"), + autoSwitch: true, + override: false + ) + #expect(direction == TranslationDirection(target: german, didSwitch: false, originalTarget: nil)) + } + + @Test func switchesWhenTheSourceIsConfidentlyTheTarget() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: detection("de"), + autoSwitch: true, + override: false + ) + #expect(direction == TranslationDirection(target: english, didSwitch: true, originalTarget: german)) + } + + @Test func doesNotSwitchWhenDisabled() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: detection("de"), + autoSwitch: false, + override: false + ) + #expect(direction.target == german) + #expect(!direction.didSwitch) + } + + @Test func doesNotSwitchAfterAManualOverride() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: detection("de"), + autoSwitch: true, + override: true + ) + #expect(direction.target == german) + #expect(!direction.didSwitch) + } + + @Test func doesNotSwitchWithLowConfidence() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: detection("de", confidence: 0.49), + autoSwitch: true, + override: false + ) + #expect(direction.target == german) + } + + @Test func doesNotSwitchWhenTheAlternativesDisagree() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: detection("de", alternatives: ["de", "en"]), + autoSwitch: true, + override: false + ) + #expect(direction.target == german) + } + + @Test func doesNotSwitchWhenTheFallbackIsTheTarget() { + let direction = TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: german, + detection: detection("de"), + autoSwitch: true, + override: false + ) + #expect(direction.target == german) + } + + @Test func doesNotSwitchWithoutAFallbackOrDetection() { + #expect( + TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: nil, + detection: detection("de"), + autoSwitch: true, + override: false + ).target == german + ) + #expect( + TranslationDirectionPolicy.resolve( + configuredTarget: german, + fallbackTarget: english, + detection: nil, + autoSwitch: true, + override: false + ).target == german + ) + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift index a70db66..a3177b9 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift @@ -13,6 +13,8 @@ struct LanguageDetectorTests { ) #expect(detection.code == "de") #expect(detection.confidence > 0.5) + #expect(detection.alternatives.contains("de")) + #expect(detection.alternatives.count == 1) } @Test func detectsEnglish() throws { diff --git a/README.md b/README.md index 06a9d14..eb496eb 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ A user-facing installation, permission and troubleshooting guide is in [docs/USE - Double-copy trigger in any app: select, **⌘C**, **⌘C**. - Streaming translations from a local Hy-MT3 model; no cloud API. - 102 supported languages with a language picker and recent targets. +- Automatic reverse direction: with target German and fallback English, German text is translated to English and English text to German. - Markdown rendering for headings, bold, italic, lists, quotes, code and links. - Configurable translation text size, source-preview toggle and an optional Fast model preset. @@ -102,6 +103,10 @@ The panel takes keyboard focus while it is visible by default, so Esc and the sh | Replace the selection | **⌘↩** | | Settings | **⌘,** | +### Translating the other direction + +When the source is confidently detected as the saved target language, the panel translates into the configured fallback language instead. The header and banner show the effective direction, and the banner offers a one-capture override. **Settings ▸ General ▸ Translation** controls this; it is on by default with English as the fallback (German when the target is English). + ### Markdown When the source looks like Markdown and **Settings ▸ General ▸ Translation ▸ Render Markdown formatting** is on (the default), the translation is rendered with headings, bold, italic, lists, quotes, fenced code and links. JSON, HTML and code sources are never Markdown-rendered. **Copy** and **Replace** always use the raw Markdown translation, not the rendered text. Only `http` and `https` links open, and only on an explicit click. @@ -112,7 +117,7 @@ Replace verifies the source app and, when available, the selected text before to ### Settings -- **General** — target language, source preview, Markdown rendering, translation text size, Esc behaviour, double-copy window and startup. +- **General** — target language, fallback target language, source preview, Markdown rendering, translation text size, Esc behaviour, double-copy window and startup. - **Model** — model and Fast preset, Ollama endpoint, sampling and context settings. - **Translation** — chunking and prompt policy. - **Privacy** — local/remote endpoint policy and permissions. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6735997..d949044 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -554,6 +554,8 @@ stateDiagram-v2 | Onboarding | `NSWindow` (not a SwiftUI `Window` scene) | Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility for Replace; each with a fix button | | Diagnostics | Window from the menu | Server version, model digests, last 50 timings and error kinds; copy as text; no text or translations | +When the source is confidently detected as the saved target language, the panel can translate into the configured fallback target instead. The saved target and the effective target are separate: the header and language picker show the effective target, a banner explains the switch and offers a one-capture override, and the language picker still changes the saved target. Detection remains advisory and uses the same high-confidence rule as the same-language advisory. + Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel is made key when shown (unless the setting is off) so Esc and the shortcuts work without a click; the app is still not activated, the source app remains frontmost and owns the menu bar, and clicking the source app takes keyboard focus back. A click sent to another app dismisses the panel; while the panel is visible a transient mouse-down monitor observes only that the click went to another app, discards the event and is removed on close. While the panel is key it receives keystrokes, so a user who types immediately after triggering should disable the Esc-on-show setting. The whole header bar (full width, flush with the top edge) moves the panel; the drag view moves the window itself from the screen-space mouse delta because `performDrag` does nothing while the app is inactive; moving it keeps its position while it stays open, and a newly shown panel is placed near the cursor (DeepL-like transient position). The translation text size is a Settings value. Accessibility: every control has an `accessibilityLabel`; the panel exposes source and translation as read-only text elements; full keyboard navigation; respects Reduce Motion and Increase Contrast. @@ -587,6 +589,8 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour | `autoCopy` | Bool | **false** (never copy automatically) | | `showSourcePreview` | Bool | true | | `translationFontSize` | Int | 17 pt (12–28) | +| `autoSwitchTarget` | Bool | true (optional reverse direction when the source is already the target) | +| `fallbackTargetLanguage` | String | `en` (or `de` when the target is English; always differs from the target) | | `renderMarkdown` | Bool | true (presentation only; raw text is copied and replaced) | | `closeWithEscape` | Bool | true (make the panel key on show; no app activation) | | `launchAtLogin` | Bool | false | diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 2441e89..19eb168 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -149,4 +149,11 @@ Status: Accepted Context: Hy-MT3 preserves Markdown structure, but a plain `Text` showed `**bold**`, headings and lists literally. Users translating Markdown want the formatting rendered, while Copy and Replace must keep the Markdown that the model produced and the validator checked. Decision: Parse presentation Markdown in `SprachmittlerText` with Foundation's inline Markdown parser plus a small, conservative block parser (headings, lists, quotes, fenced code, rules, paragraphs). `MarkdownPresentation.shouldRender` rejects JSON, HTML and code sources and otherwise requires block or inline Markdown markers. The panel renders only when the setting `renderMarkdown` is on (default). Copy and Replace use the raw translation unchanged. Only `http` and `https` links open, on an explicit click; image syntax is reduced to alt text and no remote resource is fetched. Tables, raw HTML and nested lists/quotes remain plain text in this pass. -Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added. \ No newline at end of file +Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added. + +## ADR-022 — Optional reverse direction for source-equals-target text +Status: Accepted + +Context: A single saved target language is simple, but selecting text that is already in that language produced a same-language translation and an advisory. Users working in a two-language pair want the opposite direction automatically: with target German and fallback English, German text should become English and English text should become German. +Decision: Add `autoSwitchTarget` (default true) and `fallbackTargetLanguage` (default English, or the other language when the target is English). Detect the source before the request and, only when the existing high-confidence same-language rule holds, use the fallback as the effective target. Keep the saved target separate from the effective target; the header and language picker show the effective one, and a panel banner offers a one-capture override that does not persist. A language-picker change persists the saved target. The fallback is kept different from the target; changing the target to the fallback swaps the pair to the previous target. +Consequences: Confident two-language text translates in the useful direction without extra clicks. Uncertain, short or mixed text keeps the saved target, and the same-language advisory still appears when no switch occurs. Detection is advisory, so a wrong dominant language can choose the wrong direction; the banner and the language picker make it visible and recoverable. The effective target is what the prompt, chunking and validation use; Copy and Replace are unaffected. No key tap, permission or new dependency is added. \ No newline at end of file diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 3df70d8..54ac423 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -156,3 +156,4 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain) 2026-11-26 · Panel · Esc now closes the panel without a click: `TranslationPanel` becomes key on show without activating the app (`frontmostApplication` and the menu bar stay with the source app), and `keyDown` handles keyCode 53. Added the `closeWithEscape` setting (default on) and amended ADR-009. 2026-11-26 · Panel · Markdown translations render with headings, bold/italic, inline code, lists, quotes, fenced code, rules and http/https links. `MarkdownPresentation` rejects JSON/HTML/code and only renders with the `renderMarkdown` setting (default on); Copy/Replace stay raw. Added ADR-021 and tests. 2026-11-26 · Panel · A click outside the panel now closes it. The panel observes `didResignKey` and installs a transient global mouse-down monitor while visible; global monitors ignore events sent to this app, so panel/popover clicks are unaffected, and the monitor is removed on close. Verified: inside click keeps it open, outside click closes it with and without `closeWithEscape`, and an outside click while the language popover is open closes both. +2026-11-26 · Panel · Added an optional reverse direction: with the saved target German and fallback English, confidently German text is translated to English automatically, and vice versa. The saved target and effective target are separate; a banner offers a one-capture override, and the language picker still changes the saved target. `autoSwitchTarget` defaults on and `fallbackTargetLanguage` defaults to English/the opposite language. Filtered near-zero detector hypotheses so the high-confidence same-language rule works. Added resolver, settings, view-model and detector tests. diff --git a/docs/TRANSLATION_OUTPUT.md b/docs/TRANSLATION_OUTPUT.md index 9ad0977..583c5e2 100644 --- a/docs/TRANSLATION_OUTPUT.md +++ b/docs/TRANSLATION_OUTPUT.md @@ -83,7 +83,9 @@ If detected: warning `preambleDetected(firstLine:)`; the panel shows a banner; R ## 8. Same-language input -If `NLLanguageRecognizer` reports the target language with confidence ≥ 0.5 and all detected candidates agree, show "This text already appears to be in {language}" and offer "Translate anyway". Do not block: short text, names and mixed text are often misdetected. +If `NLLanguageRecognizer` reports the target language with confidence ≥ 0.5 and all meaningful candidates agree, the source is considered to be in the target language. Near-zero hypotheses (below 0.05) are ignored, so a confident single-language text is not treated as mixed. + +With `autoSwitchTarget` on (default), a confident same-language source is translated into `fallbackTargetLanguage` instead of the saved target. The prompt, chunking and validation use that effective target. The panel shows "German → English" (or the configured pair), a banner explains the switch, and "Translate to German" overrides the direction for that capture only. The same-language advisory is shown only when no switch happens. Detection is advisory: uncertain or mixed text keeps the saved target, and the user can change it with the language picker. ## 9. Numbers and units diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index b1858b0..c4b4f4c 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -43,6 +43,21 @@ the Hy-MT3 model and the target language. You can reopen setup from the menu bar Replace is explicit; nothing is inserted automatically. Replace needs the macOS Accessibility permission. Double copy, translation, Copy and the Services menu work without it. +### Translating the other direction + +By default the panel also handles the opposite direction. With target **German** and fallback +**English**, English text becomes German and German text becomes English. This is controlled in +**Settings ▸ General ▸ Translation**: + +- **Translate the other direction when the text is already in the target language** (on by default). +- **Fallback target language** (English by default). + +The header shows the actual direction, and a banner explains an automatic switch. **Translate to +German** (or the original target) overrides the direction for that result only; the saved target +does not change. Choosing a language from the panel's picker does change the saved target. The +switch happens only when the text is confidently detected as the target language; short or mixed +text keeps the normal direction. + ## 4. Services and the menu bar - **Services ▸ Translate with Sprachmittler** translates the current selection without polling