feat(m2-m3): adapter, text pipeline, double-copy capture and Services (T2.1-T2.7, T3.1-T3.4)
M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes. M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open. Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018. Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
This commit is contained in:
1 parent
26b493e7e5
commit
64078e2f04
80 files changed
+4090
-325
No files matched your search
@@ -0,0 +1,26 @@
|
||||
import Foundation
|
||||
|
||||
/// One pasteboard item's type-to-data map. The key is the raw pasteboard type.
|
||||
public struct ClipboardItemData: Sendable, Equatable {
|
||||
/// The item's data, keyed by pasteboard type.
|
||||
public let data: [String: Data]
|
||||
|
||||
/// Creates an item snapshot.
|
||||
public init(data: [String: Data]) {
|
||||
self.data = data
|
||||
}
|
||||
}
|
||||
|
||||
/// A full pasteboard snapshot used only for the Replace paste fallback.
|
||||
public struct ClipboardSnapshot: Sendable, Equatable {
|
||||
/// Every item, in pasteboard order.
|
||||
public let items: [ClipboardItemData]
|
||||
/// The `changeCount` when the snapshot was taken.
|
||||
public let changeCount: Int
|
||||
|
||||
/// Creates a snapshot.
|
||||
public init(items: [ClipboardItemData], changeCount: Int) {
|
||||
self.items = items
|
||||
self.changeCount = changeCount
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Foundation
|
||||
|
||||
/// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses
|
||||
/// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is.
|
||||
@MainActor
|
||||
public protocol PasteboardAccessing: AnyObject {
|
||||
/// The current pasteboard change count.
|
||||
var changeCount: Int { get }
|
||||
|
||||
/// The plain-text string, read only after `changeCount` changed.
|
||||
func string() -> String?
|
||||
|
||||
/// True when the pasteboard contains our own marker or a transient/concealed marker.
|
||||
func containsOwnWriteMarkers() -> Bool
|
||||
|
||||
/// Snapshots every item and type, forcing lazy data.
|
||||
func snapshot() -> ClipboardSnapshot?
|
||||
|
||||
/// Restores a snapshot only when `changeCount` still matches the recorded value.
|
||||
func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches: Int) -> Bool
|
||||
|
||||
/// Writes `text` with the own/transient/concealed markers and returns the new change count.
|
||||
@discardableResult
|
||||
func write(_ text: String) -> Int
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
|
||||
/// A source of pasteboard poll ticks. Production uses a 120 ms timer; tests drive it manually.
|
||||
public protocol PasteboardTicking: Sendable {
|
||||
/// A stream of ticks. Cancelling the consuming task must terminate the stream.
|
||||
func ticks() -> AsyncStream<Void>
|
||||
}
|
||||
|
||||
/// The production 120 ms ticker (`docs/SELECTION_AND_CLIPBOARD.md` §2).
|
||||
public struct TimerPasteboardTicker: PasteboardTicking {
|
||||
/// The poll interval.
|
||||
public let interval: Duration
|
||||
|
||||
/// Creates a ticker.
|
||||
public init(interval: Duration = .milliseconds(120)) {
|
||||
self.interval = interval
|
||||
}
|
||||
|
||||
public func ticks() -> AsyncStream<Void> {
|
||||
AsyncStream { continuation in
|
||||
let task = Task {
|
||||
while !Task.isCancelled {
|
||||
do {
|
||||
try await Task.sleep(for: interval)
|
||||
} catch {
|
||||
break
|
||||
}
|
||||
continuation.yield(())
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
continuation.onTermination = { _ in task.cancel() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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>?
|
||||
|
||||
/// 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(),
|
||||
now: @escaping @MainActor () -> Date = { Date() }
|
||||
) {
|
||||
self.pasteboard = pasteboard
|
||||
detector = DoubleCopyDetector(configuration: configuration)
|
||||
self.ticker = ticker
|
||||
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 = CaptureLimits.characters(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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
|
||||
/// The Services entry point (`docs/SELECTION_AND_CLIPBOARD.md` §6).
|
||||
///
|
||||
/// The system supplies the pasteboard, so this path needs no Accessibility permission and no
|
||||
/// polling. `AppDelegate` installs this object as `NSApp.servicesProvider`.
|
||||
///
|
||||
/// `@unchecked Sendable` is safe: the only stored value is an immutable `@Sendable` closure, and
|
||||
/// AppKit invokes the selector on the main thread.
|
||||
public final class ServicesProvider: NSObject, @unchecked Sendable {
|
||||
/// The captured-text handler. The app hops to the main actor itself.
|
||||
public typealias Handler = @Sendable (CapturedText) -> Void
|
||||
|
||||
private let handler: Handler
|
||||
|
||||
/// Creates a provider.
|
||||
public init(handler: @escaping Handler) {
|
||||
self.handler = handler
|
||||
super.init()
|
||||
}
|
||||
|
||||
/// The `NSMessage = translateSelection` selector from Info.plist.
|
||||
@objc
|
||||
@MainActor
|
||||
public func translateSelection(
|
||||
_ pasteboard: NSPasteboard,
|
||||
userData: String,
|
||||
error: AutoreleasingUnsafeMutablePointer<NSString>
|
||||
) {
|
||||
guard !SystemPasteboard.containsOwnWriteMarkers(in: pasteboard),
|
||||
let text = pasteboard.string(forType: .string),
|
||||
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
else {
|
||||
error.pointee = "No text was selected." as NSString
|
||||
return
|
||||
}
|
||||
handler(CapturedText(text: text, capturedAt: Date(), source: .services))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
/// The production pasteboard adapter. This is the only type that touches `NSPasteboard.general`.
|
||||
@MainActor
|
||||
public final class SystemPasteboard: PasteboardAccessing {
|
||||
private nonisolated static let ownType = NSPasteboard.PasteboardType("com.schihei.sprachmittler.own")
|
||||
private nonisolated static let transientType = NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
|
||||
private nonisolated static let concealedType = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
|
||||
|
||||
private let pasteboard: NSPasteboard
|
||||
|
||||
/// Creates an adapter for the general pasteboard.
|
||||
public init(pasteboard: NSPasteboard = .general) {
|
||||
self.pasteboard = pasteboard
|
||||
}
|
||||
|
||||
public var changeCount: Int {
|
||||
pasteboard.changeCount
|
||||
}
|
||||
|
||||
public func string() -> String? {
|
||||
pasteboard.string(forType: .string)
|
||||
}
|
||||
|
||||
public func containsOwnWriteMarkers() -> Bool {
|
||||
Self.containsOwnWriteMarkers(in: pasteboard)
|
||||
}
|
||||
|
||||
/// True when a pasteboard carries our own or a transient/concealed marker.
|
||||
public nonisolated static func containsOwnWriteMarkers(in pasteboard: NSPasteboard) -> Bool {
|
||||
let types = pasteboard.types ?? []
|
||||
return types.contains(ownType)
|
||||
|| types.contains(transientType)
|
||||
|| types.contains(concealedType)
|
||||
}
|
||||
|
||||
public func snapshot() -> ClipboardSnapshot? {
|
||||
let items = pasteboard.pasteboardItems ?? []
|
||||
let snapshots = items.map { item -> ClipboardItemData in
|
||||
var data: [String: Data] = [:]
|
||||
for type in item.types {
|
||||
// `data(forType:)` forces lazy providers now; an unresolved provider is skipped.
|
||||
if let value = item.data(forType: type) {
|
||||
data[type.rawValue] = value
|
||||
}
|
||||
}
|
||||
return ClipboardItemData(data: data)
|
||||
}
|
||||
return ClipboardSnapshot(items: snapshots, changeCount: pasteboard.changeCount)
|
||||
}
|
||||
|
||||
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
|
||||
guard pasteboard.changeCount == expected else { return false }
|
||||
pasteboard.clearContents()
|
||||
guard !snapshot.items.isEmpty else { return true }
|
||||
|
||||
let items = snapshot.items.map { snapshotItem -> NSPasteboardItem in
|
||||
let item = NSPasteboardItem()
|
||||
for (type, data) in snapshotItem.data {
|
||||
item.setData(data, forType: NSPasteboard.PasteboardType(type))
|
||||
}
|
||||
return item
|
||||
}
|
||||
return pasteboard.writeObjects(items)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func write(_ text: String) -> Int {
|
||||
pasteboard.clearContents()
|
||||
pasteboard.setString(text, forType: .string)
|
||||
let marker = Data()
|
||||
pasteboard.setData(marker, forType: Self.ownType)
|
||||
pasteboard.setData(marker, forType: Self.transientType)
|
||||
pasteboard.setData(marker, forType: Self.concealedType)
|
||||
return pasteboard.changeCount
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user