When Settings saves a changed languageRoutes table, retranslate an open panel so the new rule is visible immediately. Verified with make verify.
425 lines
15 KiB
Swift
425 lines
15 KiB
Swift
import AppKit
|
|
import Foundation
|
|
import SprachmittlerCapture
|
|
import SprachmittlerCore
|
|
|
|
/// The app composition root: settings, Ollama clients, session, panel, capture and diagnostics.
|
|
@MainActor
|
|
final class AppEnvironment {
|
|
let settingsStore: SettingsStore
|
|
let pasteboard: SystemPasteboard
|
|
var watcher: PasteboardWatcher
|
|
let accessibility: AccessibilityPermission
|
|
let launchAtLogin: LaunchAtLoginController
|
|
let diagnostics: DiagnosticsStore
|
|
let targetProvider: FrontmostTargetProvider
|
|
let session: TranslationSession
|
|
let settingsModel: SettingsViewModel
|
|
let onboarding: OnboardingViewModel
|
|
let diagnosticsModel: DiagnosticsViewModel
|
|
|
|
private(set) var lastCaptured: CapturedText?
|
|
private(set) var lastTranslation: String?
|
|
private(set) var lastWarnings: [TranslationWarning] = []
|
|
private(set) var insertionTarget: InsertionTarget?
|
|
private var insertionTargetGeneration = 0
|
|
private(set) var lastCaptureFailure: CaptureValidation?
|
|
var onCapture: ((CapturedText) -> Void)?
|
|
var onStateChange: (() -> Void)?
|
|
|
|
private var watcherEventSink: (@MainActor (PasteboardWatcherEvent) -> Void)?
|
|
private var watcherWindowMs: Int
|
|
|
|
/// The Services provider, created lazily so it can capture `self` weakly.
|
|
lazy var servicesProvider = ServicesProvider { [weak self] captured in
|
|
Task { @MainActor in
|
|
self?.deliver(captured)
|
|
}
|
|
}
|
|
|
|
/// The insertion coordinator, created on first use.
|
|
lazy var insertionCoordinator = InsertionCoordinator(
|
|
pasteboard: pasteboard,
|
|
accessibility: AXTextEditor(),
|
|
ownWrite: { [weak self] in self?.watcher.noteOwnWrite(at: Date()) },
|
|
frontmostPID: { NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 }
|
|
)
|
|
|
|
/// The panel model, created on first use.
|
|
lazy var panelViewModel: PanelViewModel = {
|
|
let model = PanelViewModel(
|
|
session: session,
|
|
configuration: configuration(for: settingsStore.current()),
|
|
copy: { [weak self] text in
|
|
self?.copyToPasteboard(text, remember: self?.panelViewModel.translation == text)
|
|
},
|
|
replace: { [weak self] in
|
|
guard let self else { return .failed(.cancelled) }
|
|
return await performReplace()
|
|
},
|
|
onCloseRequest: { [weak self] in self?.panelController.close() },
|
|
eventObserver: { [weak self] event in self?.observe(event) },
|
|
onTargetChanged: { [weak self] language in self?.applyTarget(language) }
|
|
)
|
|
model.startObserving()
|
|
return model
|
|
}()
|
|
|
|
/// The panel window controller, created on first use.
|
|
lazy var panelController = PanelController(viewModel: panelViewModel)
|
|
|
|
/// Creates the environment.
|
|
init() {
|
|
let store = SettingsStore()
|
|
let pasteboard = SystemPasteboard()
|
|
let access = AccessibilityPermission()
|
|
let launch = LaunchAtLoginController()
|
|
let diagnostics = DiagnosticsStore()
|
|
let windowMs = store.current().doubleCopyWindowMs
|
|
|
|
settingsStore = store
|
|
self.pasteboard = pasteboard
|
|
accessibility = access
|
|
targetProvider = FrontmostTargetProvider()
|
|
launchAtLogin = launch
|
|
self.diagnostics = diagnostics
|
|
watcherWindowMs = windowMs
|
|
watcher = PasteboardWatcher(
|
|
pasteboard: pasteboard,
|
|
configuration: DoubleCopyDetector.Configuration(
|
|
window: Double(windowMs) / 1000
|
|
)
|
|
)
|
|
|
|
let factoryStore = store
|
|
session = TranslationSession(pipelineFactory: {
|
|
try AppOllama.makePipeline(settings: factoryStore.current())
|
|
})
|
|
|
|
let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog = { settings in
|
|
try AppOllama.makeCatalog(settings: settings)
|
|
}
|
|
settingsModel = SettingsViewModel(
|
|
store: store,
|
|
catalogProvider: catalogProvider,
|
|
launchAtLogin: launch
|
|
)
|
|
onboarding = OnboardingViewModel(
|
|
settingsStore: store,
|
|
catalogProvider: catalogProvider,
|
|
accessibility: access
|
|
)
|
|
diagnosticsModel = DiagnosticsViewModel(
|
|
store: diagnostics,
|
|
catalogProvider: catalogProvider,
|
|
settingsProvider: { factoryStore.current() }
|
|
)
|
|
}
|
|
|
|
/// Starts the watcher and optional warm-up.
|
|
func start(onCapture: @escaping (CapturedText) -> Void) {
|
|
self.onCapture = onCapture
|
|
let sink: @MainActor (PasteboardWatcherEvent) -> Void = { [weak self] event in
|
|
self?.handle(event)
|
|
}
|
|
watcherEventSink = sink
|
|
watcher.start(onEvent: sink)
|
|
warmUpIfNeeded()
|
|
}
|
|
|
|
/// Stops the watcher, panel and event stream.
|
|
func stop() {
|
|
watcher.stop()
|
|
panelViewModel.shutdown()
|
|
Task { await panelViewModel.close() }
|
|
lastCaptured = nil
|
|
lastTranslation = nil
|
|
lastWarnings = []
|
|
}
|
|
|
|
/// Reads the clipboard once for the menu-bar item.
|
|
func captureClipboardText() {
|
|
guard !pasteboard.containsOwnWriteMarkers(),
|
|
let text = pasteboard.string(),
|
|
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
|
else {
|
|
return
|
|
}
|
|
deliver(CapturedText(text: text, capturedAt: Date(), source: .menu))
|
|
}
|
|
|
|
/// Copies arbitrary text with the app's own-write markers.
|
|
func copyText(_ text: String) {
|
|
copyToPasteboard(text, remember: false)
|
|
}
|
|
|
|
/// Copies the last translation for the status menu.
|
|
func copyLastTranslation() {
|
|
guard let lastTranslation else { return }
|
|
copyToPasteboard(lastTranslation, remember: false)
|
|
}
|
|
|
|
/// True when the last translation can safely be inserted.
|
|
var canReplaceLast: Bool {
|
|
lastTranslation != nil
|
|
&& lastCaptured != nil
|
|
&& insertionTarget != nil
|
|
&& !InsertionPolicy.isBlocked(by: lastWarnings)
|
|
}
|
|
|
|
/// Replaces the last selection from the status menu.
|
|
func replaceLastTranslation() {
|
|
guard let captured = lastCaptured,
|
|
let translation = lastTranslation,
|
|
let target = insertionTarget
|
|
else {
|
|
return
|
|
}
|
|
Task {
|
|
do {
|
|
_ = try await insertionCoordinator.replace(
|
|
selection: captured,
|
|
with: translation,
|
|
target: target
|
|
)
|
|
} catch let error as SprachmittlerError {
|
|
showPanelError(error, source: captured)
|
|
} catch {
|
|
showPanelError(.server(status: 0, message: "Insertion failed"), source: captured)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The current target code, for the status menu.
|
|
var currentTarget: ModelLanguage {
|
|
settingsStore.current().targetLanguageModel
|
|
}
|
|
|
|
/// Changes the target from the status menu and retranslates the open panel.
|
|
func selectTarget(_ language: ModelLanguage) {
|
|
try? settingsStore.update { $0.noteTarget(language) }
|
|
applySettings()
|
|
}
|
|
|
|
/// Called after Settings or Onboarding saves. Updates the panel and watcher.
|
|
func settingsDidChange() {
|
|
applySettings()
|
|
settingsModel.reload()
|
|
}
|
|
|
|
private func configuration(for settings: AppSettings) -> PanelConfiguration {
|
|
PanelConfiguration(
|
|
target: settings.targetLanguageModel,
|
|
model: settings.model,
|
|
keepAlive: settings.keepModelLoaded,
|
|
sampling: settings.samplingOptions,
|
|
showSourcePreview: settings.showSourcePreview,
|
|
translationFontSize: settings.translationFontSize,
|
|
renderMarkdown: settings.renderMarkdown,
|
|
closeWithEscape: settings.closeWithEscape,
|
|
languageRoutes: settings.languageRoutes,
|
|
recentTargets: settings.recentTargets
|
|
)
|
|
}
|
|
|
|
private func applySettings() {
|
|
let settings = settingsStore.current()
|
|
let previousTarget = panelViewModel.configuration.target.code
|
|
let previousRoutes = panelViewModel.configuration.languageRoutes
|
|
panelViewModel.updateConfiguration(configuration(for: settings))
|
|
if settings.doubleCopyWindowMs != watcherWindowMs {
|
|
watcherWindowMs = settings.doubleCopyWindowMs
|
|
restartWatcher()
|
|
}
|
|
let targetChanged = previousTarget != settings.targetLanguage && panelViewModel.source != nil
|
|
let routesChanged = previousRoutes != settings.languageRoutes && panelViewModel.source != nil
|
|
if targetChanged || routesChanged {
|
|
Task { await panelViewModel.retranslate() }
|
|
}
|
|
onStateChange?()
|
|
}
|
|
|
|
private func applyTarget(_ language: ModelLanguage) {
|
|
try? settingsStore.update { $0.noteTarget(language) }
|
|
applySettings()
|
|
}
|
|
|
|
private func restartWatcher() {
|
|
watcher.stop()
|
|
watcher = PasteboardWatcher(
|
|
pasteboard: pasteboard,
|
|
configuration: DoubleCopyDetector.Configuration(
|
|
window: Double(watcherWindowMs) / 1000
|
|
)
|
|
)
|
|
if let sink = watcherEventSink {
|
|
watcher.start(onEvent: sink)
|
|
}
|
|
}
|
|
|
|
private func handle(_ event: PasteboardWatcherEvent) {
|
|
switch event {
|
|
case let .captured(captured):
|
|
deliver(captured)
|
|
case let .textTooLong(characters, limit):
|
|
let error = SprachmittlerError.textTooLong(characters: characters, limit: limit)
|
|
lastTranslation = nil
|
|
lastWarnings = []
|
|
onStateChange?()
|
|
lastCaptureFailure = .textTooLong(characters: characters, limit: limit)
|
|
showPanelError(error)
|
|
case .noText, .ignoredOwnWrite:
|
|
break
|
|
}
|
|
}
|
|
|
|
private func deliver(_ captured: CapturedText) {
|
|
// A new capture invalidates the previous result for the status-menu actions.
|
|
lastTranslation = nil
|
|
lastWarnings = []
|
|
onStateChange?()
|
|
|
|
switch CapturePolicy.validate(captured.text) {
|
|
case .valid:
|
|
lastCaptureFailure = nil
|
|
case .empty:
|
|
lastCaptureFailure = .empty
|
|
return
|
|
case let .textTooLong(characters, limit):
|
|
lastCaptureFailure = .textTooLong(characters: characters, limit: limit)
|
|
showPanelError(
|
|
.textTooLong(characters: characters, limit: limit),
|
|
source: captured
|
|
)
|
|
return
|
|
}
|
|
|
|
lastCaptured = captured
|
|
captureInsertionTarget()
|
|
onCapture?(captured)
|
|
panelViewModel.updateConfiguration(configuration(for: settingsStore.current()))
|
|
panelViewModel.prepare(captured)
|
|
panelController.show()
|
|
Task { await panelViewModel.begin(captured) }
|
|
}
|
|
}
|
|
|
|
extension AppEnvironment {
|
|
private func performReplace() async -> InsertionOutcome {
|
|
guard let captured = lastCaptured,
|
|
let target = insertionTarget,
|
|
!panelViewModel.translation.isEmpty
|
|
else {
|
|
return .failed(.insertionTargetChanged)
|
|
}
|
|
if let warning = panelViewModel.blockingWarnings.first {
|
|
return .failed(warning.insertionError)
|
|
}
|
|
do {
|
|
if let selected = target.selectedText {
|
|
let frontmost = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0
|
|
try InsertionPolicy.verify(
|
|
frontmostPID: frontmost,
|
|
target: target,
|
|
selectedText: selected,
|
|
source: captured.text
|
|
)
|
|
}
|
|
return try await insertionCoordinator.replace(
|
|
selection: captured,
|
|
with: panelViewModel.translation,
|
|
target: target
|
|
)
|
|
} catch let error as SprachmittlerError {
|
|
return .failed(error)
|
|
} catch is CancellationError {
|
|
return .failed(.cancelled)
|
|
} catch {
|
|
return .failed(.server(status: 0, message: "Insertion failed"))
|
|
}
|
|
}
|
|
|
|
private func captureInsertionTarget() {
|
|
guard let base = targetProvider.captureTarget() else {
|
|
insertionTarget = nil
|
|
return
|
|
}
|
|
insertionTarget = base
|
|
Task {
|
|
let editor = AXTextEditor()
|
|
guard await editor.isTrusted(),
|
|
let selected = await editor.selectedText(pid: base.pid),
|
|
insertionTarget?.pid == base.pid
|
|
else {
|
|
return
|
|
}
|
|
insertionTarget = InsertionTarget(
|
|
pid: base.pid,
|
|
bundleID: base.bundleID,
|
|
selectedText: selected,
|
|
capturedAt: base.capturedAt
|
|
)
|
|
}
|
|
}
|
|
|
|
private func showPanelError(_ error: SprachmittlerError, source: CapturedText? = nil) {
|
|
panelViewModel.updateConfiguration(configuration(for: settingsStore.current()))
|
|
panelViewModel.showError(error, source: source)
|
|
panelController.show()
|
|
}
|
|
|
|
private func copyToPasteboard(_ text: String, remember: Bool) {
|
|
pasteboard.write(text)
|
|
watcher.noteOwnWrite(at: Date())
|
|
let shouldRemember = remember
|
|
&& panelViewModel.phase == .ready
|
|
&& settingsStore.current().keepRecentTranslationInMemory
|
|
if shouldRemember {
|
|
lastTranslation = text
|
|
}
|
|
onStateChange?()
|
|
}
|
|
|
|
private func observe(_ event: TranslationSessionEvent) {
|
|
switch event {
|
|
case let .finished(_, result):
|
|
lastWarnings = result.warnings
|
|
if settingsStore.current().keepRecentTranslationInMemory {
|
|
lastTranslation = result.translation
|
|
} else {
|
|
lastTranslation = nil
|
|
}
|
|
let detail = result.warnings.map(\.code).joined(separator: ",")
|
|
let duration = result.timing.totalMs
|
|
Task {
|
|
await diagnostics.record(
|
|
kind: "translation",
|
|
durationMs: duration,
|
|
detail: detail.isEmpty ? nil : detail
|
|
)
|
|
}
|
|
onStateChange?()
|
|
case let .failed(_, error):
|
|
Task {
|
|
await diagnostics.record(kind: "error", detail: error.diagnosticCode)
|
|
}
|
|
onStateChange?()
|
|
case .started, .delta, .cancelled:
|
|
break
|
|
}
|
|
}
|
|
|
|
private func warmUpIfNeeded() {
|
|
let settings = settingsStore.current()
|
|
guard settings.warmUpOnLaunch else { return }
|
|
Task {
|
|
do {
|
|
try await AppOllama.warmUp(settings: settings)
|
|
await diagnostics.record(kind: "warmup")
|
|
} catch {
|
|
await diagnostics.record(kind: "warmupFailed", detail: "unavailable")
|
|
}
|
|
}
|
|
}
|
|
}
|