#if os(macOS) import AppKit import Testing @testable import EquipoKit @testable import EquipoMac @MainActor @Suite(.serialized) struct MacAttachmentTests { @Test func pastedAndDroppedImagesUseTheDraftAndGateSend() async throws { let server = AttachmentServer() let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let pasteboard = NSPasteboard.withUniqueName() defer { pasteboard.releaseGlobally() } pasteboard.setData(try AttachmentTests.image(), forType: .png) // Both NSTextView.paste and performDragOperation call this entry point. #expect(composer.acceptAttachments(pasteboard)) for _ in 0..<500 { if !draft.readyAttachments.isEmpty { break } try await Task.sleep(for: .milliseconds(10)) } #expect(draft.readyAttachments.count == 1) var sent: String? composer.onSend = { sent = $0 } composer.submit() #expect(sent == "") pasteboard.clearContents(); pasteboard.setString("ordinary text", forType: .string) #expect(!composer.acceptAttachments(pasteboard)) } } #endif #if os(macOS) @MainActor final class AttachmentDraggingInfo: NSObject, NSDraggingInfo { let draggingPasteboard: NSPasteboard let draggingDestinationWindow: NSWindow? init(_ board: NSPasteboard, window: NSWindow? = nil) { draggingPasteboard = board; draggingDestinationWindow = window } var draggingSourceOperationMask: NSDragOperation { .copy } var draggingLocation: NSPoint { .zero } var draggedImageLocation: NSPoint { .zero } nonisolated var draggedImage: NSImage? { nil } var draggingSource: Any? { nil } var draggingSequenceNumber: Int { 1 } var draggingFormation: NSDraggingFormation = .none var animatesToDestination = false var numberOfValidItemsForDrop = 1 var springLoadingHighlight: NSSpringLoadingHighlight { .none } func slideDraggedImage(to screenPoint: NSPoint) {} nonisolated override func namesOfPromisedFilesDropped(atDestination dropDestination: URL) -> [String]? { nil } func resetSpringLoading() {} func enumerateDraggingItems(options: NSDraggingItemEnumerationOptions = [], for view: NSView?, classes classArray: [AnyClass], searchOptions: [NSPasteboard.ReadingOptionKey: Any] = [:], using block: (NSDraggingItem, Int, UnsafeMutablePointer) -> Void) {} } extension MacAttachmentTests { @Test(arguments: [NSPasteboard.PasteboardType.png, .tiff, .fileURL]) func fullDragLifecycleAcceptsImages(_ type: NSPasteboard.PasteboardType) async throws { let server = AttachmentServer(), board = NSPasteboard.withUniqueName() defer { board.releaseGlobally() } let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png") defer { try? FileManager.default.removeItem(at: url) } if type == .fileURL { try AttachmentTests.image().write(to: url); board.writeObjects([url as NSURL]) } else { board.setData(try AttachmentTests.image(type == .tiff ? .tiff : .png), forType: type) } let drag = AttachmentDraggingInfo(board) #expect(composer.editor.draggingEntered(drag) == .copy) #expect(composer.editor.draggingUpdated(drag) == .copy) #expect(composer.editor.prepareForDragOperation(drag)) #expect(composer.editor.performDragOperation(drag)) for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } #expect(draft.readyAttachments.count == 1) } @Test func foldersAreRefusedBeforeAddingItems() async throws { let server = AttachmentServer(), board = NSPasteboard.withUniqueName() defer { board.releaseGlobally() } let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let drag = AttachmentDraggingInfo(board) board.writeObjects([FileManager.default.temporaryDirectory as NSURL]) _ = composer.editor.performDragOperation(drag) try await Task.sleep(for: .milliseconds(40)) #expect(draft.items.isEmpty) #expect(draft.notice == EquipoStrings.text("api.attachment_type")) #expect(await server.requests.isEmpty) } } #endif #if os(macOS) @MainActor private final class FixturePromise: NSFilePromiseReceiver { let bytes: Data var destination: URL? var permissions: Int? init(_ bytes: Data) { self.bytes = bytes; super.init() } required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError() } override func receivePromisedFiles(atDestination destinationDir: URL, options: [AnyHashable: Any] = [:], operationQueue: OperationQueue, reader: @escaping (URL, (any Error)?) -> Void) { destination = destinationDir permissions = (try? FileManager.default.attributesOfItem(atPath: destinationDir.path)[.posixPermissions]) as? Int let url = destinationDir.appendingPathComponent("promise.png") do { try bytes.write(to: url); reader(url, nil) } catch { reader(url, error) } } } extension MacAttachmentTests { @Test func promisedFilesUsePrivateStorageAndRemoveItAfterReading() async throws { let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let promise = FixturePromise(try AttachmentTests.image()) composer.receive([promise], into: draft) let destination = try #require(promise.destination) #expect(promise.permissions == 0o700) for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } #expect(draft.readyAttachments.count == 1) #expect(!FileManager.default.fileExists(atPath: destination.path)) let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } for type in NSFilePromiseReceiver.readableDraggedTypes { board.clearContents(); board.setData(Data(), forType: NSPasteboard.PasteboardType(type)) let drag = AttachmentDraggingInfo(board) #expect(composer.editor.draggingEntered(drag) == .copy) #expect(composer.editor.draggingUpdated(drag) == .copy) #expect(composer.editor.prepareForDragOperation(drag)) } } } #endif #if os(macOS) @MainActor private final class HeldFilePromise: NSFilePromiseReceiver { var destination: URL? var reader: ((URL, (any Error)?) -> Void)? override init() { super.init() } required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError() } override func receivePromisedFiles(atDestination destinationDir: URL, options: [AnyHashable: Any] = [:], operationQueue: OperationQueue, reader: @escaping (URL, (any Error)?) -> Void) { destination = destinationDir self.reader = reader } } extension MacAttachmentTests { @Test func textDragFallsThroughTheWholeNativeLifecycle() throws { _ = NSApplication.shared let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false) let editor = ComposerEditor(frame: NSRect(x: 0, y: 0, width: 300, height: 200)) let baseline = NSTextView(frame: NSRect(x: 300, y: 0, width: 300, height: 200)) for view in [editor, baseline] { view.isRichText = false; window.contentView?.addSubview(view) } let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } board.setString("dragged text", forType: .string) let drag = AttachmentDraggingInfo(board, window: window) let entered = baseline.draggingEntered(drag) #expect(!entered.isEmpty) #expect(editor.draggingEntered(drag) == entered) #expect(editor.draggingUpdated(drag) == baseline.draggingUpdated(drag)) #expect(baseline.prepareForDragOperation(drag)) #expect(editor.prepareForDragOperation(drag)) #expect(baseline.performDragOperation(drag)) #expect(editor.performDragOperation(drag)) #expect(editor.string == "dragged text") #expect(editor.string == baseline.string) } @Test func promiseDeletesEachFileWhileOtherReadersStillOwnDirectory() async throws { let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let promise = HeldFilePromise() composer.receive([promise], into: draft) let directory = try #require(promise.destination) defer { promise.reader = nil } let url = directory.appendingPathComponent("delivered.png") try AttachmentTests.image().write(to: url) promise.reader?(url, nil) #expect(FileManager.default.fileExists(atPath: directory.path)) #expect(!FileManager.default.fileExists(atPath: url.path)) for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } #expect(draft.readyAttachments.count == 1) } @Test func promiseCannotReadOutsideItsPrivateDirectory() async throws { let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let promise = HeldFilePromise() composer.receive([promise], into: draft) let outside = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png") try AttachmentTests.image().write(to: outside) defer { promise.reader = nil; try? FileManager.default.removeItem(at: outside) } promise.reader?(outside, nil) for _ in 0..<100 { if draft.notice != nil || !draft.items.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } #expect(draft.notice == AttachmentFailure.type.words) #expect(draft.items.isEmpty) #expect(await server.requests.isEmpty) #expect(FileManager.default.fileExists(atPath: outside.path)) } } #endif #if os(macOS) extension MacAttachmentTests { @Test func webURLDropAndPasteInsertTextWithoutAttachments() async throws { _ = NSApplication.shared let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let composer = MacComposer(); composer.attach(draft) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false) composer.frame = NSRect(x: 0, y: 0, width: 400, height: 100) window.contentView?.addSubview(composer) composer.layoutSubtreeIfNeeded() let url = URL(string: "https://example.com/photo.png")! let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } board.writeObjects([url as NSURL]) let drag = AttachmentDraggingInfo(board, window: window) #expect(!composer.editor.draggingEntered(drag).isEmpty) #expect(!composer.editor.draggingUpdated(drag).isEmpty) #expect(composer.editor.prepareForDragOperation(drag)) #expect(composer.editor.performDragOperation(drag)) #expect(composer.text == url.absoluteString) #expect(!composer.acceptAttachments(board)) // NSTextView.paste reads the general pasteboard. Preserve it in memory // for this short synchronous test; no clipboard contents are logged. do { let clipboard = NSPasteboard.general let saved = (clipboard.pasteboardItems ?? []).map { item in item.types.compactMap { type in item.data(forType: type).map { (type, $0) } } } defer { clipboard.clearContents() let restored = saved.map { values in let item = NSPasteboardItem() for (type, data) in values { item.setData(data, forType: type) } return item } clipboard.writeObjects(restored) } clipboard.clearContents(); clipboard.writeObjects([url as NSURL]) composer.setText("Link: ") composer.editor.setSelectedRange(NSRange(location: 6, length: 0)) composer.editor.paste(nil) #expect(composer.text == "Link: " + url.absoluteString) } #expect(draft.items.isEmpty) #expect(await server.requests.isEmpty) } } #endif