Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift
T
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00

131 lines
4.3 KiB
Swift

import Foundation
import SprachmittlerCore
/// A pasteboard watcher event.
public enum PasteboardWatcherEvent: Sendable, Equatable {
/// A validated double copy.
case captured(CapturedText)
/// The copied text is above the script-aware limit.
case textTooLong(characters: Int, limit: Int)
/// The change had no usable text.
case noText
/// A change was our own write or the marker/suppression window.
case ignoredOwnWrite
}
/// Polls `changeCount`, reads the string only after a change, and emits double copies.
///
/// This type never reads the pasteboard in the background: `poll` first compares `changeCount`
/// and only then reads the string.
@MainActor
public final class PasteboardWatcher {
/// The own-write suppression window.
public static let suppressionWindow: TimeInterval = 0.75
private let pasteboard: any PasteboardAccessing
private let ticker: any PasteboardTicking
private let now: @MainActor () -> Date
private var detector: DoubleCopyDetector
private var lastChangeCount: Int
private var suppressUntil = Date.distantPast
private var task: Task<Void, Never>?
/// The capture limits used by the next poll.
public var limits: CaptureLimits
/// True while the poll task is running.
public private(set) var isRunning = false
/// Creates a watcher. The initial change count is recorded without reading any string.
public init(
pasteboard: any PasteboardAccessing,
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
ticker: any PasteboardTicking = TimerPasteboardTicker(),
limits: CaptureLimits = CaptureLimits(),
now: @escaping @MainActor () -> Date = { Date() }
) {
self.pasteboard = pasteboard
detector = DoubleCopyDetector(configuration: configuration)
self.ticker = ticker
self.limits = limits
self.now = now
lastChangeCount = pasteboard.changeCount
}
/// Starts polling. Calling it twice is a no-op.
public func start(onEvent: @escaping @MainActor (PasteboardWatcherEvent) -> Void) {
guard task == nil else { return }
lastChangeCount = pasteboard.changeCount
detector.reset()
isRunning = true
let ticker = ticker
task = Task { [weak self] in
for await _ in ticker.ticks() {
guard let self else { break }
if let event = poll(at: now()) {
onEvent(event)
}
}
}
}
/// Stops polling and releases the in-memory copies.
public func stop() {
task?.cancel()
task = nil
isRunning = false
detector.reset()
}
/// Polls once. Public so component tests can avoid real time.
@discardableResult
public func poll(at date: Date) -> PasteboardWatcherEvent? {
let count = pasteboard.changeCount
guard count != lastChangeCount else {
detector.expire(at: date)
return nil
}
lastChangeCount = count
if date < suppressUntil {
return .ignoredOwnWrite
}
if pasteboard.containsOwnWriteMarkers() {
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
detector.reset()
return .ignoredOwnWrite
}
guard let string = pasteboard.string() else {
detector.reset()
return .noText
}
switch detector.record(changeCount: count, text: string, at: date) {
case .none:
return nil
case .empty:
return .noText
case let .captured(text):
let limit = limits.captureLimit(for: text)
guard text.count <= limit else {
detector.reset()
return .textTooLong(characters: text.count, limit: limit)
}
detector.reset()
return .captured(CapturedText(text: text, capturedAt: date, source: .doubleCopy))
}
}
/// Marks a clipboard write by this app so the watcher suppresses it and the next changes.
public func noteOwnWrite(at date: Date) {
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
detector.reset()
}
/// Clears the remembered copy without stopping the watcher.
public func clear() {
detector.reset()
}
}