# Drag and drop

Receive files dropped on a window and drag files or text out of it with the Compose drag-and-drop API.

Drag and drop uses the standard Compose modifiers, `Modifier.dragAndDropTarget` and
`Modifier.dragAndDropSource`, and comes with `nucleus-application`. Both need
`@OptIn(ExperimentalComposeUiApi::class)`.

![Two files dragged from Finder onto the drop zone, which lights up; then report.pdf dragged out of the app into the Finder folder](/assets/docs/input/drag-and-drop-finder.gif)

## Receive dropped files

```kotlin
val target = remember {
    object : DragAndDropTarget {
        override fun onDrop(event: DragAndDropEvent): Boolean {
            @Suppress("UNCHECKED_CAST")
            val files = event.awtTransferable
                .getTransferData(DataFlavor.javaFileListFlavor) as List<File>
            onFiles(files)
            return files.isNotEmpty()
        }
    }
}

Box(Modifier.fillMaxSize().dragAndDropTarget(shouldStartDragAndDrop = { true }, target = target))
```

Return `true` from `onDrop` to accept the data.

- On macOS, inbound drops carry files only. Windows and Linux also deliver dropped text and URLs.
  HTML drops are not delivered.
- The file list is available while the drag hovers, so `shouldStartDragAndDrop`, `onEntered` and
  `onMoved` can accept or refuse a drag by its paths or extensions. `onDrop` reads the dropped
  payload itself.
- On Windows the paths arrive a moment after the drag enters. Until then the list is empty and the
  window offers a copy; acceptance is decided once the paths arrive, or at the drop if the user
  releases sooner.
- [`TrayApp`](/docs/os/tray/tray-app) popups accept drops through the same modifier.

## Receive dropped text and links

On Windows and Linux, a window accepts plain text and links, such as a link or an image dragged
from a browser. Read them through `event.taoPayload` (`dev.nucleusframework.window.tao`):

```kotlin
override fun onDrop(event: DragAndDropEvent): Boolean {
    val payload = event.taoPayload ?: return false
    val link = payload.uris.firstOrNull()
    val text = payload.text
    val files = payload.files
    // …
    return true
}
```

| Property | Holds |
| --- | --- |
| `files` | Absolute paths of the dragged files |
| `text` | The plain text the source offers, or `null` |
| `uris` | Non-file URIs, such as a link. Files are never repeated here |

`taoPayload` is `null` for an event that does not come from a Nucleus window. The same data is in
`event.awtTransferable`:

| Flavor | Returns |
| --- | --- |
| `DataFlavor.javaFileListFlavor` | The files |
| `DataFlavor.stringFlavor` | The text, else the URIs, else the file paths, one per line |
| `text/uri-list` | The URIs, one per line |
| `application/x-java-url` | The first URI as a `java.net.URL` |

Hover events carry what the platform could read before the drop. The drop event always carries the
full payload.

## Drag data out of the window

Wrap an AWT `Transferable` that offers `javaFileListFlavor`, `stringFlavor`, or both:

```kotlin
Modifier.dragAndDropSource { _ ->
    DragAndDropTransferData(
        transferable = DragAndDropTransferable(StringSelection("Hello from Nucleus")),
        supportedActions = listOf(DragAndDropTransferAction.Copy),
        onTransferCompleted = { action -> /* null when cancelled */ },
    )
}
```

A transferable with neither files nor text does not start a drag. Your window keeps drawing while
the cursor is outside it.

## Carry a cross-window drag on Wayland 

On native Wayland a window cannot read or set its screen position (`TaoWindow.canPlaceOnScreen`
is `false`), so the source of a drag between two of your windows cannot tell which window the
pointer is over. The transfer drag API carries such a drag on the platform's drag-and-drop
session instead: the window under the pointer resolves the drop, and the source acts on the
outcome. [Satellites](/docs/tool-windows/satellites) and [tabs](/docs/tool-windows/tabs) use it
for their own drags. Use it for a docking or tab layout of your own. It is
`@ExperimentalNucleusApi` and lives in `dev.nucleusframework.window.tao.workspace`.

Implement `TransferDrag` for the session, and keep the drag in flight where every window sees it:

```kotlin
// One drag in flight per process, visible to every window
var currentDrag: PanelDrag? by mutableStateOf(null)

@OptIn(ExperimentalNucleusApi::class)
class PanelDrag(val panelId: String) : TransferDrag {
    override val title = "Layers"
    override val ghostSizePx = Size(240f, 32f)
    override val ghostSource = TransferGhostSource.None
    var zone: DropZone? = null

    override fun end() {
        zone?.let { movePanel(panelId, it) }
        currentDrag = null
    }

    override fun cancel() {
        currentDrag = null
    }
}
```

Put `Modifier.transferDragHandle` on the grip of the source. `begin` returns the session, or
`null` to refuse the drag:

```kotlin
val window = LocalTaoWindow.current ?: return
Box(
    Modifier.transferDragHandle(
        key = "layers",
        window = window,
        begin = { PanelDrag("layers").also { currentDrag = it } },
    ),
)
```

In every window that accepts the drop, accept only while a session is in flight and resolve
`DragAndDropEvent.positionInWindowPx()` against your drop zones:

```kotlin
val target = remember {
    object : DragAndDropTarget {
        override fun onDrop(event: DragAndDropEvent): Boolean {
            val drag = currentDrag ?: return false
            drag.zone = zoneAt(event.positionInWindowPx()) ?: return false
            return true
        }
    }
}
Box(Modifier.dragAndDropTarget(shouldStartDragAndDrop = { currentDrag != null }, target = target))
```

`end()` runs on the source once the platform session is over, whether or not anything was
dropped.

- `ghostSource` sets what the drag icon pictures: `TransferGhostSource.WholeWindow`,
  `Region(rectPx)` for one part of the source window, or `None` for a card that shows `title`.
- The `gesture` parameter takes a `TransferDragGesture`. Its `onDrag` keeps the pointer for as long
  as it returns `false`, so a tab strip can reorder locally before the session starts. The
  default, `TransferDragGesture.Immediate`, hands over once the pointer passes the touch slop.
- Linux only. Elsewhere the session does not start and `cancel()` is called. Branch on
  `canPlaceOnScreen` and move real windows on the other platforms.

- Nucleus installs no AWT `DropTarget`, and reading `awtTransferable` does not start the AWT
  toolkit.
- To debug a drag that does not start, read `TaoDnDDiagnostics.lastMessage`
  (`dev.nucleusframework.window.tao`): it holds the last reason a drag was skipped.

## What's next

- [Pointer icons](/docs/input/pointer-icons): show a grab or not-allowed cursor during a drag.
- [Tabs](/docs/tool-windows/tabs): tear-off and merge built on the same drag session.
- [Tool windows](/docs/tool-windows#two-ways-to-carry-a-drag): how satellites and tabs pick a
  drag kind.
- [Trackpad gestures](/docs/input/trackpad-gestures): pans and pinch-to-zoom.
