import Foundation /// The double-copy state machine result (`docs/SELECTION_AND_CLIPBOARD.md` §2). public enum DoubleCopyOutcome: Sendable, Equatable { /// No trigger. case none /// A valid double copy; the value is normalised line endings and trimmed, internal whitespace kept. case captured(String) /// The change had no usable text; the state was reset. case empty } /// The pure double-copy state machine. It has no pasteboard or timer dependency. public struct DoubleCopyDetector: Sendable { /// Detector configuration. public struct Configuration: Sendable, Equatable { /// The two-copy window; 500 ms by default (range 300–1000). public let window: TimeInterval /// Creates a configuration. public init(window: TimeInterval = 0.5) { self.window = window } } private struct Candidate { let changeCount: Int let text: String let date: Date } private let configuration: Configuration private var candidate: Candidate? /// Creates a detector. public init(configuration: Configuration = Configuration()) { self.configuration = configuration } /// Records one changed pasteboard value and returns the outcome. public mutating func record(changeCount: Int, text: String?, at date: Date) -> DoubleCopyOutcome { guard let text else { candidate = nil return .empty } let normalized = text .replacingOccurrences(of: "\r\n", with: "\n") .replacingOccurrences(of: "\r", with: "\n") .trimmingCharacters(in: .whitespacesAndNewlines) guard normalized.contains(where: { !$0.isWhitespace }) else { candidate = nil return .empty } if let candidate { if candidate.changeCount == changeCount { return .none } let elapsed = date.timeIntervalSince(candidate.date) if candidate.text == normalized, elapsed >= 0, elapsed <= configuration.window { self.candidate = nil return .captured(normalized) } } candidate = Candidate(changeCount: changeCount, text: normalized, date: date) return .none } /// Forgets the remembered copy. Call when the session starts or the window expires. public mutating func reset() { candidate = nil } /// Clears the remembered copy once the two-copy window has passed, so no text is retained /// longer than necessary. public mutating func expire(at date: Date) { guard let candidate, date.timeIntervalSince(candidate.date) > configuration.window else { return } self.candidate = nil } }