Sample CodemacOSReviewed 2026-11-01View on Apple Developer

Supporting Drag and Drop Through File Promises

At a glance

Item Summary
Purpose Accept images dropped as file promises or file URLs, let the user add text on top, and drag the result out as a promised JPEG file.
App architecture Storyboard AppKit app. WindowController hosts ImageCanvasController, whose root view is ImageCanvas. The canvas handles drag events and gestures, and hands drop and drag-out decisions to its controller through ImageCanvasDelegate.
Main patterns A custom @MainActor delegate protocol between view and controller, plus AppKit file-promise and gesture delegates
Project style Single target, one primary type per file. Gesture handling is split into ImageCanvas+Gestures.swift.
Execution model Swift 6. Controller and view code is main-actor isolated. File-promise reads and writes run on a private OperationQueue, through nonisolated delegate methods and a Task { @MainActor in } hop back.
State/event model Direct property mutation with didSet side effects. Drag, drop, and gesture events arrive through AppKit callbacks.
Key frameworks/packages Cocoa, UniformTypeIdentifiers

Project structure

MemeGenerator/
├── AppDelegate.swift              // @main, restorable state, quit on last window
├── WindowController.swift         // toolbar items ↔ ImageCanvasController
├── ImageCanvasController.swift    // ImageCanvasDelegate + NSFilePromiseProviderDelegate
├── ImageCanvas.swift              // ImageCanvasDelegate protocol, ImageCanvas view, SnapshotItem
├── ImageCanvas+Gestures.swift     // click/pan recognizers, drag-out session
├── TextField.swift                // editable label + DrawingItem value
├── Base.lproj/Main.storyboard     // window, controller, canvas, outlet wiring
├── en.lproj/Localizable.strings   // "DropFileTitle"
└── MemeGenerator.entitlements     // App Sandbox

Structure observations

  • The storyboard sets ImageCanvas as the controller’s root view and connects the canvas’s delegate outlet to the controller (MemeGenerator/Base.lproj/Main.storyboard:451, MemeGenerator/Base.lproj/Main.storyboard:482).
  • ImageCanvas.swift defines both the delegate protocol and the view that calls it. The gesture code lives in a separate extension file, so some stored properties are left internal (MemeGenerator/ImageCanvas.swift:142).
  • The app is sandboxed, with user-selected read-only file access (MemeGenerator/MemeGenerator.entitlements:5).

Overall architecture

Reference code

MemeGenerator/ImageCanvas.swift:11 — ImageCanvasDelegate

@MainActor @objc protocol ImageCanvasDelegate: AnyObject {
    /// Returns the drag operation to allow when a drag enters the canvas.
    func draggingEntered(forImageCanvas imageCanvas: ImageCanvas, sender: NSDraggingInfo) -> NSDragOperation
    /// Handles the items dropped onto the canvas, and returns `true` if it
    /// uses any of them.
    func performDragOperation(forImageCanvas imageCanvas: ImageCanvas, sender: NSDraggingInfo) -> Bool
    /// Returns the pasteboard writer for the image that someone drags out of
    /// the canvas.
    func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting
}

Interpretation

ImageCanvas receives the drag events, because the controller registers its root view for the dragged types (MemeGenerator/ImageCanvasController.swift:90). Every policy decision goes back to the controller: which operation to allow, what to do with dropped items, and which pasteboard writer to use for a drag-out. The view handles presentation and gestures only. The controller owns file I/O, the destination directory, and the work queue.

Ownership and state

Ownership evidence

MemeGenerator/ImageCanvasController.swift:31 — controller state

class ImageCanvasController: NSViewController, NSFilePromiseProviderDelegate, ImageCanvasDelegate {
    // ...
    /// The canvas that shows the image and its text fields.
    @IBOutlet weak var imageCanvas: ImageCanvas!
    // ...
    /// The queue for reading and writing file promises. The system requests it
    /// from a background queue, so it isn't isolated to the main actor.
    private nonisolated let workQueue: OperationQueue = {
        let providerQueue = OperationQueue()
        providerQueue.qualityOfService = .userInitiated
        return providerQueue
    }()

    /// The directory that receives promised files.
    private lazy var destinationURL: URL = {
        let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent("Drops")
        // Create the directory if it doesn't exist.
        try? FileManager.default.createDirectory(at: destinationURL, withIntermediateDirectories: true)
        return destinationURL
    }()
    // ...
}
Owner Object or state Relationship Mutation authority
ImageCanvasController workQueue, destinationURL Creates and stores, both private ImageCanvasController
ImageCanvasController imageCanvas, placeholderLabel, imageLabel Weak storyboard outlets Storyboard. The controller sets their content (MemeGenerator/ImageCanvasController.swift:47).
ImageCanvas delegate Weak outlet to the controller (MemeGenerator/ImageCanvas.swift:134) Storyboard
ImageCanvas overlay, textFields, selectedTextField, draggedTextField Creates and stores (MemeGenerator/ImageCanvas.swift:179, MemeGenerator/ImageCanvas.swift:200) ImageCanvas and its gesture extension
ImageCanvas isLoading, isHighlighted Stored flags whose didSet updates the view Set by the controller (isLoading) and by drag callbacks (isHighlighted)
NSFilePromiseProvider SnapshotItem Set as userInfo when the drag starts (MemeGenerator/ImageCanvasController.swift:165) Immutable once built. All its properties are let.
WindowController addTextToolbarItem Outlet. ImageCanvasController.handleFile enables or disables it (MemeGenerator/ImageCanvasController.swift:60). ImageCanvasController

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Main-actor isolation @MainActor protocol Every ImageCanvasDelegate requirement is main-actor isolated MemeGenerator/ImageCanvas.swift:11
Main-actor assumption MainActor.assumeIsolated awakeFromNib asserts main-actor isolation before it configures subviews and recognizers MemeGenerator/ImageCanvas.swift:171
Worker queue OperationQueue (qualityOfService = .userInitiated) Passed to receivePromisedFiles and returned from operationQueue(for:) for writing promised files MemeGenerator/ImageCanvasController.swift:31, MemeGenerator/ImageCanvasController.swift:139, MemeGenerator/ImageCanvasController.swift:179
Non-isolated callbacks nonisolated delegate methods File-name, queue, and write callbacks for the file promise are not main-actor isolated. The write callback reads only the SnapshotItem from userInfo. MemeGenerator/ImageCanvasController.swift:171, MemeGenerator/ImageCanvasController.swift:182
Hop back to the UI Task { @MainActor in } inside a @Sendable completion The receive-completion handler creates a main-actor task to call handleError or handleFile. Nothing stores or cancels the task. MemeGenerator/ImageCanvasController.swift:142
Shared-state safety Immutable value handoff SnapshotItem holds only let properties and is built on the main actor before it crosses to workQueue MemeGenerator/ImageCanvas.swift:26, MemeGenerator/ImageCanvas.swift:124

Reference code

MemeGenerator/ImageCanvasController.swift:142 — receive callback hops to the main actor

            case let filePromiseReceiver as NSFilePromiseReceiver:
                self.prepareForUpdate()
                filePromiseReceiver.receivePromisedFiles(atDestination: self.destinationURL, options: [:],
                                                         operationQueue: self.workQueue) { @Sendable (fileURL, error) in
                    // The system calls this handler on `workQueue`, so hop back
                    // to the main actor.
                    Task { @MainActor in
                        if let error = error {
                            self.handleError(error)
                        } else {
                            self.handleFile(at: fileURL)
                        }
                    }
                }

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
State propagation didSet observers Setting isHighlighted redraws the view. Setting isLoading toggles the image view and the progress indicator. MemeGenerator/ImageCanvas.swift:67, MemeGenerator/ImageCanvas.swift:75
State propagation Custom delegate The canvas forwards drag-enter, drop, and drag-out writer requests to the controller MemeGenerator/ImageCanvas.swift:324, MemeGenerator/ImageCanvas.swift:332, MemeGenerator/ImageCanvas+Gestures.swift:106
State propagation Direct mutation The controller pushes the loaded image and size label into the views MemeGenerator/ImageCanvasController.swift:46
Framework import Cocoa Imported by every source file MemeGenerator/ImageCanvas.swift:8
Framework import UniformTypeIdentifiers Used for UTType.image filtering and the promised UTType.jpeg file type MemeGenerator/ImageCanvasController.swift:9, MemeGenerator/ImageCanvasController.swift:164

Platform boundary

Apple lists macOS for this sample. The downloaded project sets MACOSX_DEPLOYMENT_TARGET = 27.0 and SWIFT_VERSION = 6.0 (MemeGenerator.xcodeproj/project.pbxproj:262, MemeGenerator.xcodeproj/project.pbxproj:351).

Class and protocol design

Reference code

MemeGenerator/ImageCanvas+Gestures.swift:106 — drag-out uses the delegate’s pasteboard writer

    private func beginImageDraggingSession(for gesture: NSGestureRecognizer) {
        guard let delegate = delegate else { return }
        // Get the file promise provider from the delegate, and show the image
        // in the overlay's frame while the person drags it.
        let draggingItem = NSDraggingItem(pasteboardWriter: delegate.pasteboardWriter(forImageCanvas: self))
        draggingItem.setDraggingFrame(overlay.frame, contents: draggingImage)
        beginDraggingSession(items: [draggingItem], gesture: gesture, source: self)
    }
Type Responsibility Depends on
ImageCanvasController Drop policy, file-promise receiving and providing, error presentation ImageCanvas, OperationQueue, NSFilePromiseReceiver/Provider
ImageCanvas Draws the image and overlay, routes drag-destination events, handles click and pan gestures, creates snapshots ImageCanvasDelegate, TextField
ImageCanvas.SnapshotItem Immutable render input. Produces outputImage and jpegRepresentation. TextField.DrawingItem
TextField Editable label that keeps its center as the text grows. Exposes a DrawingItem. NSTextField
WindowController Connects the toolbar items to the controller ImageCanvasController

Access control

Symbol Access Verified effect Likely rationale
ImageCanvasController.workQueue private nonisolated let Only the controller can see it, and its nonisolated file-promise callbacks can read it Matches the source comment: the system asks for the queue from a background queue
ImageCanvasController.destinationURL, handleImage, handleFile, handleError, prepareForUpdate private UI update helpers are callable only from the controller Inference: callers outside the controller go through the delegate methods
ImageCanvas.imagePixelSize private Only ImageCanvas.swift can see it. It changes only through the image setter. Inference: keeps pixel size consistent with image
ImageCanvas.overlay, textFields, selectedTextField, draggedTextField implicit internal Visible across the module The source says these are non-private so the gesture extension in another file can use them
Gesture helpers (subviewHit, select, beginImageDraggingSession, constrainRectToBounds) private Visible only inside ImageCanvas+Gestures.swift Inference: implementation details of gesture handling
WindowController.imageCanvasController private computed Toolbar actions reach the controller through this property Inference: hides the downcast of contentViewController

Reference code

MemeGenerator/ImageCanvas.swift:146 — properties widened for the gesture extension

class ImageCanvas: NSView, NSTextFieldDelegate, NSDraggingSource, NSGestureRecognizerDelegate {
    // ...
    // The size of the image, in pixels.
    private var imagePixelSize = CGSize.zero
    // The properties below aren't private, so the gesture code in
    // `ImageCanvas+Gestures.swift` can use them.

    // A view that matches the displayed image and contains the text fields.
    var overlay: NSView!
    // ...
}

Logic ownership and placement

Logic Owning type or file Placement rationale
Accepted drag types and copy-only policy ImageCanvasController Registration in viewDidLoad and filtering in performDragOperation keep drop policy with the controller (MemeGenerator/ImageCanvasController.swift:110)
First-item-only drop handling ImageCanvasController.performDragOperation Stops the enumeration after the first item, because the canvas shows one image (MemeGenerator/ImageCanvasController.swift:132)
Writing the promised JPEG ImageCanvasController (nonisolated) Runs on workQueue and uses only the immutable snapshot
Flattening image + text ImageCanvas.SnapshotItem.outputImage The scale factor converts canvas points to image pixels (MemeGenerator/ImageCanvas.swift:129)
Gesture arbitration ImageCanvas+Gestures.swift The single click waits for the double click to fail, and gestures are blocked while the field editor has the hit (MemeGenerator/ImageCanvas+Gestures.swift:147)
Source-side drag mask ImageCanvas.draggingSession(_:sourceOperationMaskFor:) Copy is allowed only outside the app (MemeGenerator/ImageCanvas.swift:314)

Design patterns

Pattern Source evidence Purpose or tradeoff
Protocol-oriented abstraction MemeGenerator/ImageCanvas.swift:11 and ImageCanvasDelegate The view depends on a protocol instead of ImageCanvasController, so drop policy can change without changing the view
Delegate or data-source callbacks MemeGenerator/ImageCanvasController.swift:11, MemeGenerator/ImageCanvas.swift:23 Custom canvas delegate plus AppKit NSFilePromiseProviderDelegate, NSDraggingSource, and NSGestureRecognizerDelegate callbacks

Main application flow

Reference code

MemeGenerator/ImageCanvas.swift:332 — canvas forwards the drop

    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        // Let the delegate handle the dropped items.
        return delegate?.performDragOperation(forImageCanvas: self, sender: sender) ?? false
    }

MemeGenerator/ImageCanvasController.swift:138 — controller starts receiving the promise

                filePromiseReceiver.receivePromisedFiles(atDestination: self.destinationURL, options: [:],
                                                         operationQueue: self.workQueue) { @Sendable (fileURL, error) in
                    // ...
                    Task { @MainActor in
                        if let error = error {
                            self.handleError(error)
                        } else {
                            self.handleFile(at: fileURL)
                        }
                    }
                }

MemeGenerator/ImageCanvasController.swift:47 — main-actor UI update

    private func handleImage(_ image: NSImage?) {
        imageCanvas.image = image
        // Hide the placeholder label when there's an image.
        placeholderLabel.isHidden = (image != nil)
        // Update the label that shows the image's size.
        imageLabel.stringValue = imageCanvas.imageDescription
    }

Naming conventions

  • Types: AppKit role suffixes (WindowController, ImageCanvasController). Nested value types are named for their use: SnapshotItem, DrawingItem, RuntimeError.
  • Protocols: ImageCanvasDelegate follows AppKit’s <Type>Delegate convention. Its methods take the sender first, as in forImageCanvas:.
  • Methods: handle… for UI updates the controller makes, prepareForUpdate for loading state, and handleSingleClick, handleDoubleClick, handlePan for gesture actions.
  • Files and extensions: ImageCanvas+Gestures.swift uses the Type+Feature extension convention.

Architecture takeaways

  • A narrow, @MainActor delegate protocol keeps drag and drop policy in the controller while the view handles events and gestures.
  • File-promise I/O uses one private OperationQueue. The callbacks that run on it are marked nonisolated, which makes the actor boundary visible in the type.
  • Data crossing to the worker queue is an immutable snapshot (SnapshotItem) built on the main actor, so the write callback never touches view state.
  • Splitting gesture code into an extension file forces private state to widen to internal. The source documents that tradeoff in a comment.

Source map

Source file Relevant symbols
MemeGenerator/AppDelegate.swift AppDelegate
MemeGenerator/WindowController.swift WindowController, addTextToolbarItem, imageCanvasController
MemeGenerator/ImageCanvasController.swift ImageCanvasController, workQueue, performDragOperation, pasteboardWriter, filePromiseProvider(_:writePromiseTo:completionHandler:)
MemeGenerator/ImageCanvas.swift ImageCanvasDelegate, ImageCanvas, SnapshotItem, awakeFromNib
MemeGenerator/ImageCanvas+Gestures.swift handlePan, beginImageDraggingSession, gestureRecognizer(_:shouldRequireFailureOf:)
MemeGenerator/TextField.swift TextField, DrawingItem
MemeGenerator/Base.lproj/Main.storyboard Controller, canvas, and delegate outlet wiring
MemeGenerator/MemeGenerator.entitlements App Sandbox
MemeGenerator.xcodeproj/project.pbxproj MACOSX_DEPLOYMENT_TARGET, SWIFT_VERSION