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? /// 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() } }