| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import Testing |
| 4 | @testable import EquipoKit |
| 5 | @testable import EquipoMac |
| 6 | |
| 7 | @MainActor @Suite(.serialized) struct MacAttachmentTests { |
| 8 | @Test func pastedAndDroppedImagesUseTheDraftAndGateSend() async throws { |
| 9 | let server = AttachmentServer() |
| 10 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 11 | let composer = MacComposer(); composer.attach(draft) |
| 12 | let pasteboard = NSPasteboard.withUniqueName() |
| 13 | defer { pasteboard.releaseGlobally() } |
| 14 | pasteboard.setData(try AttachmentTests.image(), forType: .png) |
| 15 | // Both NSTextView.paste and performDragOperation call this entry point. |
| 16 | #expect(composer.acceptAttachments(pasteboard)) |
| 17 | for _ in 0..<500 { |
| 18 | if !draft.readyAttachments.isEmpty { break } |
| 19 | try await Task.sleep(for: .milliseconds(10)) |
| 20 | } |
| 21 | #expect(draft.readyAttachments.count == 1) |
| 22 | var sent: String? |
| 23 | composer.onSend = { sent = $0 } |
| 24 | composer.submit() |
| 25 | #expect(sent == "") |
| 26 | pasteboard.clearContents(); pasteboard.setString("ordinary text", forType: .string) |
| 27 | #expect(!composer.acceptAttachments(pasteboard)) |
| 28 | } |
| 29 | } |
| 30 | #endif |
| 31 | |
| 32 | #if os(macOS) |
| 33 | @MainActor final class AttachmentDraggingInfo: NSObject, NSDraggingInfo { |
| 34 | let draggingPasteboard: NSPasteboard |
| 35 | let draggingDestinationWindow: NSWindow? |
| 36 | init(_ board: NSPasteboard, window: NSWindow? = nil) { draggingPasteboard = board; draggingDestinationWindow = window } |
| 37 | var draggingSourceOperationMask: NSDragOperation { .copy } |
| 38 | var draggingLocation: NSPoint { .zero } |
| 39 | var draggedImageLocation: NSPoint { .zero } |
| 40 | nonisolated var draggedImage: NSImage? { nil } |
| 41 | var draggingSource: Any? { nil } |
| 42 | var draggingSequenceNumber: Int { 1 } |
| 43 | var draggingFormation: NSDraggingFormation = .none |
| 44 | var animatesToDestination = false |
| 45 | var numberOfValidItemsForDrop = 1 |
| 46 | var springLoadingHighlight: NSSpringLoadingHighlight { .none } |
| 47 | func slideDraggedImage(to screenPoint: NSPoint) {} |
| 48 | nonisolated override func namesOfPromisedFilesDropped(atDestination dropDestination: URL) -> [String]? { nil } |
| 49 | func resetSpringLoading() {} |
| 50 | func enumerateDraggingItems(options: NSDraggingItemEnumerationOptions = [], for view: NSView?, classes classArray: [AnyClass], searchOptions: [NSPasteboard.ReadingOptionKey: Any] = [:], using block: (NSDraggingItem, Int, UnsafeMutablePointer<ObjCBool>) -> Void) {} |
| 51 | } |
| 52 | |
| 53 | extension MacAttachmentTests { |
| 54 | @Test(arguments: [NSPasteboard.PasteboardType.png, .tiff, .fileURL]) |
| 55 | func fullDragLifecycleAcceptsImages(_ type: NSPasteboard.PasteboardType) async throws { |
| 56 | let server = AttachmentServer(), board = NSPasteboard.withUniqueName() |
| 57 | defer { board.releaseGlobally() } |
| 58 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 59 | let composer = MacComposer(); composer.attach(draft) |
| 60 | let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png") |
| 61 | defer { try? FileManager.default.removeItem(at: url) } |
| 62 | if type == .fileURL { try AttachmentTests.image().write(to: url); board.writeObjects([url as NSURL]) } |
| 63 | else { board.setData(try AttachmentTests.image(type == .tiff ? .tiff : .png), forType: type) } |
| 64 | let drag = AttachmentDraggingInfo(board) |
| 65 | #expect(composer.editor.draggingEntered(drag) == .copy) |
| 66 | #expect(composer.editor.draggingUpdated(drag) == .copy) |
| 67 | #expect(composer.editor.prepareForDragOperation(drag)) |
| 68 | #expect(composer.editor.performDragOperation(drag)) |
| 69 | for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 70 | #expect(draft.readyAttachments.count == 1) |
| 71 | } |
| 72 | |
| 73 | @Test func foldersAreRefusedBeforeAddingItems() async throws { |
| 74 | let server = AttachmentServer(), board = NSPasteboard.withUniqueName() |
| 75 | defer { board.releaseGlobally() } |
| 76 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 77 | let composer = MacComposer(); composer.attach(draft) |
| 78 | let drag = AttachmentDraggingInfo(board) |
| 79 | board.writeObjects([FileManager.default.temporaryDirectory as NSURL]) |
| 80 | _ = composer.editor.performDragOperation(drag) |
| 81 | try await Task.sleep(for: .milliseconds(40)) |
| 82 | #expect(draft.items.isEmpty) |
| 83 | #expect(draft.notice == EquipoStrings.text("api.attachment_type")) |
| 84 | #expect(await server.requests.isEmpty) |
| 85 | } |
| 86 | } |
| 87 | #endif |
| 88 | |
| 89 | #if os(macOS) |
| 90 | @MainActor private final class FixturePromise: NSFilePromiseReceiver { |
| 91 | let bytes: Data |
| 92 | var destination: URL? |
| 93 | var permissions: Int? |
| 94 | init(_ bytes: Data) { self.bytes = bytes; super.init() } |
| 95 | required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError() } |
| 96 | override func receivePromisedFiles(atDestination destinationDir: URL, options: [AnyHashable: Any] = [:], operationQueue: OperationQueue, reader: @escaping (URL, (any Error)?) -> Void) { |
| 97 | destination = destinationDir |
| 98 | permissions = (try? FileManager.default.attributesOfItem(atPath: destinationDir.path)[.posixPermissions]) as? Int |
| 99 | let url = destinationDir.appendingPathComponent("promise.png") |
| 100 | do { try bytes.write(to: url); reader(url, nil) } catch { reader(url, error) } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | extension MacAttachmentTests { |
| 105 | @Test func promisedFilesUsePrivateStorageAndRemoveItAfterReading() async throws { |
| 106 | let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 107 | let composer = MacComposer(); composer.attach(draft) |
| 108 | let promise = FixturePromise(try AttachmentTests.image()) |
| 109 | composer.receive([promise], into: draft) |
| 110 | let destination = try #require(promise.destination) |
| 111 | #expect(promise.permissions == 0o700) |
| 112 | for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 113 | #expect(draft.readyAttachments.count == 1) |
| 114 | #expect(!FileManager.default.fileExists(atPath: destination.path)) |
| 115 | let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| 116 | for type in NSFilePromiseReceiver.readableDraggedTypes { |
| 117 | board.clearContents(); board.setData(Data(), forType: NSPasteboard.PasteboardType(type)) |
| 118 | let drag = AttachmentDraggingInfo(board) |
| 119 | #expect(composer.editor.draggingEntered(drag) == .copy) |
| 120 | #expect(composer.editor.draggingUpdated(drag) == .copy) |
| 121 | #expect(composer.editor.prepareForDragOperation(drag)) |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | #endif |
| 126 | |
| 127 | #if os(macOS) |
| 128 | @MainActor private final class HeldFilePromise: NSFilePromiseReceiver { |
| 129 | var destination: URL? |
| 130 | var reader: ((URL, (any Error)?) -> Void)? |
| 131 | override init() { super.init() } |
| 132 | required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError() } |
| 133 | override func receivePromisedFiles(atDestination destinationDir: URL, options: [AnyHashable: Any] = [:], operationQueue: OperationQueue, reader: @escaping (URL, (any Error)?) -> Void) { |
| 134 | destination = destinationDir |
| 135 | self.reader = reader |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | extension MacAttachmentTests { |
| 140 | @Test func textDragFallsThroughTheWholeNativeLifecycle() throws { |
| 141 | _ = NSApplication.shared |
| 142 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| 143 | let editor = ComposerEditor(frame: NSRect(x: 0, y: 0, width: 300, height: 200)) |
| 144 | let baseline = NSTextView(frame: NSRect(x: 300, y: 0, width: 300, height: 200)) |
| 145 | for view in [editor, baseline] { view.isRichText = false; window.contentView?.addSubview(view) } |
| 146 | let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| 147 | board.setString("dragged text", forType: .string) |
| 148 | let drag = AttachmentDraggingInfo(board, window: window) |
| 149 | let entered = baseline.draggingEntered(drag) |
| 150 | #expect(!entered.isEmpty) |
| 151 | #expect(editor.draggingEntered(drag) == entered) |
| 152 | #expect(editor.draggingUpdated(drag) == baseline.draggingUpdated(drag)) |
| 153 | #expect(baseline.prepareForDragOperation(drag)) |
| 154 | #expect(editor.prepareForDragOperation(drag)) |
| 155 | #expect(baseline.performDragOperation(drag)) |
| 156 | #expect(editor.performDragOperation(drag)) |
| 157 | #expect(editor.string == "dragged text") |
| 158 | #expect(editor.string == baseline.string) |
| 159 | } |
| 160 | |
| 161 | @Test func promiseDeletesEachFileWhileOtherReadersStillOwnDirectory() async throws { |
| 162 | let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 163 | let composer = MacComposer(); composer.attach(draft) |
| 164 | let promise = HeldFilePromise() |
| 165 | composer.receive([promise], into: draft) |
| 166 | let directory = try #require(promise.destination) |
| 167 | defer { promise.reader = nil } |
| 168 | let url = directory.appendingPathComponent("delivered.png") |
| 169 | try AttachmentTests.image().write(to: url) |
| 170 | promise.reader?(url, nil) |
| 171 | #expect(FileManager.default.fileExists(atPath: directory.path)) |
| 172 | #expect(!FileManager.default.fileExists(atPath: url.path)) |
| 173 | for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 174 | #expect(draft.readyAttachments.count == 1) |
| 175 | } |
| 176 | |
| 177 | @Test func promiseCannotReadOutsideItsPrivateDirectory() async throws { |
| 178 | let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 179 | let composer = MacComposer(); composer.attach(draft) |
| 180 | let promise = HeldFilePromise() |
| 181 | composer.receive([promise], into: draft) |
| 182 | let outside = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png") |
| 183 | try AttachmentTests.image().write(to: outside) |
| 184 | defer { promise.reader = nil; try? FileManager.default.removeItem(at: outside) } |
| 185 | promise.reader?(outside, nil) |
| 186 | for _ in 0..<100 { if draft.notice != nil || !draft.items.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 187 | #expect(draft.notice == AttachmentFailure.type.words) |
| 188 | #expect(draft.items.isEmpty) |
| 189 | #expect(await server.requests.isEmpty) |
| 190 | #expect(FileManager.default.fileExists(atPath: outside.path)) |
| 191 | } |
| 192 | } |
| 193 | #endif |
| 194 | |
| 195 | #if os(macOS) |
| 196 | extension MacAttachmentTests { |
| 197 | @Test func webURLDropAndPasteInsertTextWithoutAttachments() async throws { |
| 198 | _ = NSApplication.shared |
| 199 | let server = AttachmentServer(), draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 200 | let composer = MacComposer(); composer.attach(draft) |
| 201 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false) |
| 202 | composer.frame = NSRect(x: 0, y: 0, width: 400, height: 100) |
| 203 | window.contentView?.addSubview(composer) |
| 204 | composer.layoutSubtreeIfNeeded() |
| 205 | let url = URL(string: "https://example.com/photo.png")! |
| 206 | let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| 207 | board.writeObjects([url as NSURL]) |
| 208 | let drag = AttachmentDraggingInfo(board, window: window) |
| 209 | #expect(!composer.editor.draggingEntered(drag).isEmpty) |
| 210 | #expect(!composer.editor.draggingUpdated(drag).isEmpty) |
| 211 | #expect(composer.editor.prepareForDragOperation(drag)) |
| 212 | #expect(composer.editor.performDragOperation(drag)) |
| 213 | #expect(composer.text == url.absoluteString) |
| 214 | #expect(!composer.acceptAttachments(board)) |
| 215 | |
| 216 | // NSTextView.paste reads the general pasteboard. Preserve it in memory |
| 217 | // for this short synchronous test; no clipboard contents are logged. |
| 218 | do { |
| 219 | let clipboard = NSPasteboard.general |
| 220 | let saved = (clipboard.pasteboardItems ?? []).map { item in |
| 221 | item.types.compactMap { type in item.data(forType: type).map { (type, $0) } } |
| 222 | } |
| 223 | defer { |
| 224 | clipboard.clearContents() |
| 225 | let restored = saved.map { values in |
| 226 | let item = NSPasteboardItem() |
| 227 | for (type, data) in values { item.setData(data, forType: type) } |
| 228 | return item |
| 229 | } |
| 230 | clipboard.writeObjects(restored) |
| 231 | } |
| 232 | clipboard.clearContents(); clipboard.writeObjects([url as NSURL]) |
| 233 | composer.setText("Link: ") |
| 234 | composer.editor.setSelectedRange(NSRange(location: 6, length: 0)) |
| 235 | composer.editor.paste(nil) |
| 236 | #expect(composer.text == "Link: " + url.absoluteString) |
| 237 | } |
| 238 | #expect(draft.items.isEmpty) |
| 239 | #expect(await server.requests.isEmpty) |
| 240 | } |
| 241 | } |
| 242 | #endif |
| 243 | |