feat(panel): optional reverse direction for target-language text
Add opt-in automatic reverse translation for a two-language pair. autoSwitchTarget defaults on with fallbackTargetLanguage English (or German when the target is English); the saved target and the effective request target are separate. Confident source-equals-target text uses the fallback, the header and a panel banner show the effective direction, and the banner can override the direction for one capture without changing the saved target. The language picker still changes the saved target, and changing the target to the fallback swaps the pair. JSON/HTML/code handling is unchanged.\n\nFilter near-zero NLLanguageRecognizer hypotheses so the existing high-confidence same-language rule works for real text. Add resolver, settings, view-model, detector and persistence tests; document ADR-022, the panel, settings and user guide. Verified: make verify green; German text with target German/fallback English renders German → English with the banner, English text stays English → German, a real click on the override shows German → German, and a new German capture switches back to English.
This commit is contained in:
1 parent
7c9cece201
commit
41f1cea769
24 files changed
+723
-148
No files matched your search
@@ -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<CodingKeys>,
|
||||
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<CodingKeys>
|
||||
) throws -> [String] {
|
||||
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
|
||||
var seen = Set<String>()
|
||||
return recents.compactMap { HyMT3Languages.resolve($0)?.code }
|
||||
.filter { seen.insert($0).inserted }
|
||||
.prefix(3)
|
||||
.map(\.self)
|
||||
}
|
||||
}
|
||||
@@ -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<CodingKeys>,
|
||||
defaults: AppSettings
|
||||
) throws -> DecodedLimits {
|
||||
@@ -217,7 +234,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
)
|
||||
}
|
||||
|
||||
private static func decodeSampling(
|
||||
static func decodeSampling(
|
||||
from container: KeyedDecodingContainer<CodingKeys>,
|
||||
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<String>()
|
||||
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>) -> Int {
|
||||
static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
|
||||
min(max(value, range.lowerBound), range.upperBound)
|
||||
}
|
||||
}
|
||||
@@ -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<Void, Never>?
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user