Files
mac_without_borders/Sources/MWBMac/Pasteboard.swift
T
lucioandClaude Opus 5 9ab4956551 clipboard: pasteboard watcher/writer and received-file staging
Pasteboard.swift is the macOS FormHelper (FormHelper.cs:234-330) plus the
writing half of Clipboard.cs:1101-1294, polled on one private serial queue.
ReceivedFile.swift ports ReceivedDestinationFile.cs and Common.GetMyStorageDir.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 04:38:19 -07:00

187 lines
7.9 KiB
Swift

// The macOS clipboard: a poll that notices what the user copied, and the writer
// that puts a peer's clipboard here.
//
// This is what the Windows helper process does with a clipboard viewer chain
// (`Helper/FormHelper.cs:234-330`) plus the writing half of
// `Core/Clipboard.cs` (1101-1294). macOS posts no clipboard notification, so
// `NSPasteboard.changeCount` is polled instead (README §Windows concept → macOS).
//
// Every access to `NSPasteboard.general` in the app goes through this file, on
// one serial queue. AppKit documents the general pasteboard as usable from any
// thread — it is a window-server object, not a view — and keeping reads and
// writes on one private queue means a poll can never interleave with a write
// and mistake our own paste for the user's copy. Nothing here blocks the main
// thread, which matters because a poll runs twice a second forever.
import AppKit
import Foundation
import MWBCore
/// Watches `NSPasteboard.general` and writes to it.
///
/// `@unchecked Sendable`: every stored property is read and written only on
/// `queue`, a private serial queue (contracts C3, the same discipline the
/// channels use).
public final class PasteboardWatcher: @unchecked Sendable {
/// How often the change counter is examined. Windows is event-driven; a
/// half-second poll is the macOS equivalent and is invisible in a profile.
public static let pollInterval: TimeInterval = 0.5
private let queue = DispatchQueue(label: "mwb.pasteboard", qos: .utility)
private let onChange: @Sendable (ClipboardContent) -> Void
private var timer: (any DispatchSourceTimer)?
private var lastChangeCount: Int
private var lastEventTime: TimeInterval = 0
private var running = false
/// A watcher that calls `onChange` on its own queue whenever the user puts
/// something new on the clipboard.
///
/// The current contents are taken as already seen, so starting the app does
/// not broadcast whatever happened to be on the clipboard.
public init(onChange: @escaping @Sendable (ClipboardContent) -> Void) {
self.onChange = onChange
lastChangeCount = NSPasteboard.general.changeCount
}
// MARK: - Lifecycle
/// Starts polling. Calling it twice does nothing the second time.
public func start() {
queue.async { [self] in
guard !running else { return }
running = true
lastChangeCount = NSPasteboard.general.changeCount
let source = DispatchSource.makeTimerSource(queue: queue)
source.schedule(
deadline: .now() + PasteboardWatcher.pollInterval,
repeating: PasteboardWatcher.pollInterval, leeway: .milliseconds(100))
source.setEventHandler { [weak self] in self?.poll() }
timer = source
source.resume()
}
}
/// Stops polling.
public func stop() {
queue.async { [self] in
running = false
timer?.cancel()
timer = nil
}
}
// MARK: - Reading
private func poll() {
guard running else { return }
let pasteboard = NSPasteboard.general
let count = pasteboard.changeCount
guard count != lastChangeCount else { return }
lastChangeCount = count
// `Clipboard.cs:100-107`: two clipboard events within a second are one
// event as far as this protocol is concerned, and the clock is reset
// even by the change that is being ignored.
let now = TimeInterval(DispatchTime.now().uptimeNanoseconds) / 1_000_000_000
let quiet = now - lastEventTime >= ClipboardCodec.quietPeriod
lastEventTime = now
guard quiet else { return }
guard let content = PasteboardWatcher.read(pasteboard) else { return }
onChange(content)
}
/// What the pasteboard currently holds, in the order Windows looks
/// (`FormHelper.cs:269-325`) with one change: files are tested **first**.
///
/// A file copied in Finder also carries its path as a string, so testing
/// text first would send the path as text and never transfer the file.
static func read(_ pasteboard: NSPasteboard) -> ClipboardContent? {
if let url = fileURL(on: pasteboard) { return .file(url) }
let text = readText(pasteboard)
if !text.isEmpty { return .text(text) }
if let png = readPNG(pasteboard) { return .image(png: png) }
return nil
}
private static func fileURL(on pasteboard: NSPasteboard) -> URL? {
let options: [NSPasteboard.ReadingOptionKey: Any] = [.urlReadingFileURLsOnly: true]
let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: options)
return (urls?.first as? URL)?.standardizedFileURL
}
private static func readText(_ pasteboard: NSPasteboard) -> ClipboardText {
var text = ClipboardText()
if let plain = pasteboard.string(forType: .string), !plain.isEmpty { text.plain = plain }
if let data = pasteboard.data(forType: .rtf), let rtf = decodeRTF(data) { text.rtf = rtf }
if let html = pasteboard.string(forType: .html), !html.isEmpty {
// Windows reads `DataFormats.Html`, which is CF_HTML — header block
// and all — so the wire form is built here rather than in the codec.
text.html = html.hasPrefix("Version:") ? html : ClipboardCodec.cfHTML(wrapping: html)
}
return text
}
/// RTF is an ASCII document with `\'xx` escapes for everything else, so a
/// UTF-8 read all but always succeeds; Latin-1 is the fallback that cannot
/// fail on arbitrary bytes.
private static func decodeRTF(_ data: Data) -> String? {
let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1)
return (text?.isEmpty ?? true) ? nil : text
}
private static func readPNG(_ pasteboard: NSPasteboard) -> Data? {
if let png = pasteboard.data(forType: .png), !png.isEmpty { return png }
guard let tiff = pasteboard.data(forType: .tiff),
let rep = NSBitmapImageRep(data: tiff),
let png = rep.representation(using: .png, properties: [:])
else { return nil }
return png
}
// MARK: - Writing
/// Puts a peer's clipboard on this Mac's.
///
/// The change counter the write produces is remembered before the next poll
/// can see it, so nothing we receive is immediately broadcast back
/// (`Clipboard.cs:351-363` resets `LastClipboardEventTime` for the same
/// reason).
public func write(_ content: ClipboardContent) {
queue.async { [self] in
let pasteboard = NSPasteboard.general
PasteboardWatcher.write(content, to: pasteboard)
lastChangeCount = pasteboard.changeCount
lastEventTime = TimeInterval(DispatchTime.now().uptimeNanoseconds) / 1_000_000_000
}
}
static func write(_ content: ClipboardContent, to pasteboard: NSPasteboard) {
switch content {
case .text(let text):
var types: [NSPasteboard.PasteboardType] = []
if text.plain != nil { types.append(.string) }
if text.rtf != nil { types.append(.rtf) }
if text.html != nil { types.append(.html) }
guard !types.isEmpty else { return }
pasteboard.declareTypes(types, owner: nil)
if let plain = text.plain { pasteboard.setString(plain, forType: .string) }
if let rtf = text.rtf {
pasteboard.setData(Data(rtf.utf8), forType: .rtf)
}
if let html = text.html {
pasteboard.setString(ClipboardCodec.htmlFragment(from: html), forType: .html)
}
case .image(let png):
pasteboard.declareTypes([.png], owner: nil)
pasteboard.setData(png, forType: .png)
case .file(let url):
pasteboard.clearContents()
pasteboard.writeObjects([url as NSURL])
}
}
}