diff --git a/Sources/MWBMac/Pasteboard.swift b/Sources/MWBMac/Pasteboard.swift new file mode 100644 index 0000000..82a5330 --- /dev/null +++ b/Sources/MWBMac/Pasteboard.swift @@ -0,0 +1,186 @@ +// 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]) + } + } +} diff --git a/Sources/MWBMac/ReceivedFile.swift b/Sources/MWBMac/ReceivedFile.swift new file mode 100644 index 0000000..d045db6 --- /dev/null +++ b/Sources/MWBMac/ReceivedFile.swift @@ -0,0 +1,109 @@ +// Where a file that arrives over the bulk channel lands, and how it gets there +// without ever leaving a half-written file in its place. +// +// Ported from App/Core/ReceivedDestinationFile.cs (the staging file and its +// commit/delete pair), App/Core/Common.cs GetMyStorageDir (1291-1330) and +// App/Core/Clipboard.cs (669-711, 787-798, 840-848). +// +// The staging file lives in the destination directory so the commit is a rename +// on one volume, which is what makes it atomic. + +import AppKit +import Foundation + +/// Why a received file could not be put where it belongs. +public enum ReceivedFileError: Error, Sendable, Equatable { + /// The Desktop folder could not be found or the download folder could not + /// be created under it. + case destinationUnavailable(String) + /// The rename into place failed. + case commitFailed(String) +} + +/// The download folder and the staged-file dance around it. +/// +/// Every method is a plain function of its arguments: no shared state, so this +/// is safe to call from the bulk channel's queue and from the Engine alike. +public enum ReceivedFile { + /// The folder Windows drops received files into, under the user's Desktop + /// (`Clipboard.cs:679`, `Common.cs:1321-1327`). + public static let folderName = "MouseWithoutBorders" + + /// `~/Desktop/MouseWithoutBorders/`, created if it is not there yet. + public static func destinationDirectory() throws -> URL { + let manager = FileManager.default + guard + let desktop = manager.urls(for: .desktopDirectory, in: .userDomainMask).first + else { + throw ReceivedFileError.destinationUnavailable("no Desktop folder") + } + let folder = desktop.appendingPathComponent(folderName, isDirectory: true) + if !manager.fileExists(atPath: folder.path) { + do { + try manager.createDirectory(at: folder, withIntermediateDirectories: true) + } catch { + throw ReceivedFileError.destinationUnavailable("\(error)") + } + } + return folder + } + + /// A hidden, unique, empty file in `directory` to stream into + /// (`ReceivedDestinationFile.cs:24-27`: `.{guid}.partial`). + public static func stagingURL(in directory: URL) -> URL { + let name = ".\(UUID().uuidString.replacingOccurrences(of: "-", with: "")).partial" + return directory.appendingPathComponent(name, isDirectory: false) + } + + /// Moves a completed staging file onto its final name, replacing whatever + /// was there (`File.Move(..., overwrite: true)`, `Clipboard.cs:542`). + /// + /// The existing file is only disturbed at this point, so a transfer that + /// fails half way leaves the previous copy alone. + @discardableResult + public static func commit(staged: URL, toFileNamed name: String, in directory: URL) throws + -> URL + { + let destination = directory.appendingPathComponent(name, isDirectory: false) + let manager = FileManager.default + do { + if manager.fileExists(atPath: destination.path) { + _ = try manager.replaceItemAt(destination, withItemAt: staged) + } else { + try manager.moveItem(at: staged, to: destination) + } + } catch { + throw ReceivedFileError.commitFailed("\(error)") + } + return destination + } + + /// Deletes an abandoned staging file (`ReceivedDestinationFile.cs:41-46`). + /// A failure here is not worth reporting: the file is hidden and unique. + public static func discard(_ staged: URL) { + try? FileManager.default.removeItem(at: staged) + } + + /// Shows the folder with the new file selected (`Clipboard.cs:840-848` + /// starts Explorer on the saving folder). + @MainActor + public static func reveal(_ file: URL) { + NSWorkspace.shared.activateFileViewerSelecting([file]) + } + + /// The size of a file to be sent, or `nil` when the path is not a readable + /// regular file (`SocketStuff.cs:1690-1702`). + public static func size(of file: URL) -> Int64? { + let values = try? file.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]) + guard values?.isRegularFile == true, let size = values?.fileSize else { return nil } + return Int64(size) + } + + /// Whether a path names a directory, which Windows refuses to transfer + /// (`SocketStuff.cs:1693`). + public static func isDirectory(_ url: URL) -> Bool { + var directory: ObjCBool = false + let exists = FileManager.default.fileExists(atPath: url.path, isDirectory: &directory) + return exists && directory.boolValue + } +}