teksilo-platform 0.27.0

Platform integration for Teksilo — winit and AccessKit adapters, clipboard, OS theme, native file dialogs, drag-and-drop and menus.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! External drag-and-drop over the hub's one `wl_data_device`.
//!
//! The device is the seat's, not a window's, so a drag aimed at any of our
//! windows arrives on it. Each window publishes its surface in
//! [`DndState::routes`]; an `enter` names a surface and is delivered to the
//! window that owns it. `motion` / `drop` / `leave` carry no surface and follow
//! the route the last `enter` established.
//!
//! Outbound drags (app → OS) are started on the same device with the press
//! serial of the device class carrying the drag ([`TouchSerialSource`]).
//!
//! [`TouchSerialSource`]: crate::external_dnd::TouchSerialSource

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use teksilo_canvas::Point;
use teksilo_core::window::TeksiloWindowId;
use teksilo_core::{AppEventPoster, DropOutcome, ExternalDropData, OsDragId, OutboundDragData};
use wayland_client::protocol::wl_data_device::Event as DataDeviceEvent;
use wayland_client::protocol::wl_data_device_manager::DndAction;
use wayland_client::protocol::wl_data_offer::WlDataOffer;
use wayland_client::protocol::wl_data_source::{Event as DataSourceEvent, WlDataSource};
use wayland_client::protocol::wl_surface::WlSurface;
use wayland_client::{Proxy, WEnum};

use super::{HubState, SourceKind, io, offer_mimes};
use crate::external_dnd::{
    ExternalDndEventPayload, ExternalDragEvent, outbound_bytes, outbound_mimes,
};

/// Preferred drop MIME types, in order. `text/uri-list` carries file paths.
const PREFERRED_MIMES: &[&str] = &["text/uri-list", "text/plain;charset=utf-8", "text/plain"];

/// Limits for reading a drop: on a thread of its own, so longer than a paste,
/// but a drop of a file list or some text is never large.
const DROP_LIMITS: io::Limits = io::Limits {
    idle: std::time::Duration::from_secs(5),
    total: std::time::Duration::from_secs(30),
    max_bytes: 64 * 1024 * 1024,
};

/// Where a window's drag events go.
#[derive(Clone)]
pub(crate) struct Route {
    pub(crate) window_id: TeksiloWindowId,
    pub(crate) poster: Arc<dyn AppEventPoster>,
    /// The window's surface, the origin of a drag it starts.
    pub(crate) surface: WlSurface,
    /// Shared by every clone of the route.
    outbox: Arc<Mutex<Outbox>>,
}

/// A window's drag events, kept in the order they happened. A drop's data is
/// read on a thread of its own, so its `Dropped` is ready only later; what the
/// window is sent meanwhile (the next drag's `Entered`, say) waits behind it,
/// or the framework would apply the old drop to the new drag.
#[derive(Default)]
struct Outbox {
    queue: VecDeque<Slot>,
    next_read: u64,
}

enum Slot {
    Ready(ExternalDragEvent),
    /// A drop whose data is still being read.
    Reading(u64),
}

impl Route {
    pub(crate) fn new(
        window_id: TeksiloWindowId,
        poster: Arc<dyn AppEventPoster>,
        surface: WlSurface,
    ) -> Self {
        Self {
            window_id,
            poster,
            surface,
            outbox: Arc::default(),
        }
    }

    fn outbox(&self) -> MutexGuard<'_, Outbox> {
        self.outbox.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn post(&self, event: ExternalDragEvent) {
        self.outbox().post(event, |event| self.post_now(event));
    }

    fn post_now(&self, event: ExternalDragEvent) {
        self.poster.post_external(Box::new(ExternalDndEventPayload {
            window_id_owner: self.window_id,
            event,
        }));
    }

    /// Hold the window's later events until the drop about to be read is
    /// posted with [`Self::finish_read`].
    fn begin_read(&self) -> u64 {
        self.outbox().begin_read()
    }

    fn finish_read(&self, read: u64, event: ExternalDragEvent) {
        self.outbox()
            .finish_read(read, event, |event| self.post_now(event));
    }
}

impl Outbox {
    /// Post `event` now, or queue it behind a drop still being read.
    fn post(&mut self, event: ExternalDragEvent, mut post_now: impl FnMut(ExternalDragEvent)) {
        if self.queue.is_empty() {
            post_now(event);
        } else {
            self.queue.push_back(Slot::Ready(event));
        }
    }

    fn begin_read(&mut self) -> u64 {
        let read = self.next_read;
        self.next_read += 1;
        self.queue.push_back(Slot::Reading(read));
        read
    }

    /// The drop `read` is ready as `event`: post it, then whatever waited
    /// behind it, up to the next drop still being read.
    fn finish_read(
        &mut self,
        read: u64,
        event: ExternalDragEvent,
        mut post_now: impl FnMut(ExternalDragEvent),
    ) {
        if let Some(slot) = self
            .queue
            .iter_mut()
            .find(|slot| matches!(slot, Slot::Reading(r) if *r == read))
        {
            *slot = Slot::Ready(event);
        }
        while matches!(self.queue.front(), Some(Slot::Ready(_))) {
            if let Some(Slot::Ready(event)) = self.queue.pop_front() {
                post_now(event);
            }
        }
    }
}

/// An outbound drag in flight.
struct Outbound {
    drag: OsDragId,
    /// The window that started it, which hears how it ended.
    owner: Route,
    source: WlDataSource,
    data: OutboundDragData,
    /// Last negotiated action (copy / move).
    action: DndAction,
    /// Set once the drop is performed, so a trailing `cancelled` does not
    /// override the success outcome.
    dropped: bool,
    /// Started by a finger (`wl_touch`) rather than a pointer.
    coarse: bool,
    /// Whether the compositor has shown it took the `start_drag`: an event on
    /// the source, or an `enter`.
    answered: bool,
}

/// Drag-and-drop state, part of [`HubState`].
#[derive(Default)]
pub(crate) struct DndState {
    /// Surface protocol id → the window that owns it.
    routes: HashMap<u32, Route>,
    /// Where the in-flight inbound drag is being delivered.
    active_route: Option<Route>,
    /// The in-flight inbound drag's offer.
    offer: Option<WlDataOffer>,
    /// The `enter` serial of that drag, needed by `accept` and its revisions.
    offer_serial: u32,
    /// The MIME type accepted for it, re-offered when the answer is revised.
    offer_accepted_mime: Option<String>,
    position: Point,
    outbound: Option<Outbound>,
}

impl DndState {
    /// Publish a window's surface, keyed by its protocol id.
    pub(crate) fn add_route(&mut self, key: u32, route: Route) {
        self.routes.insert(key, route);
    }

    /// Withdraw a window's surface. A stale entry would send a later drag to a
    /// window that no longer exists, and Wayland recycles protocol ids.
    pub(crate) fn remove_route(&mut self, key: u32) {
        if let Some(route) = self.routes.remove(&key)
            && self
                .active_route
                .as_ref()
                .is_some_and(|active| active.window_id == route.window_id)
        {
            self.active_route = None;
        }
    }

    fn route_for_window(&self, window_id: TeksiloWindowId) -> Option<&Route> {
        self.routes.values().find(|r| r.window_id == window_id)
    }

    /// Post to the window under the drag. No-op when none is being serviced.
    fn post_routed(&self, event: ExternalDragEvent) {
        if let Some(route) = &self.active_route {
            route.post(event);
        }
    }
}

/// Re-answer the in-flight inbound offer with the widget tree's verdict.
///
/// `accept` and `set_actions` may both be re-issued for the life of the offer,
/// and the compositor's cursor follows the latest answer. A refusal is
/// `accept(serial, None)` plus empty actions: `accept` alone leaves a
/// negotiated action standing and some compositors keep showing the copy
/// cursor, and empty actions alone leave the type accepted.
pub(crate) fn revise_accept(state: &mut HubState, accepted: bool) {
    let dnd = &state.dnd;
    let Some(offer) = dnd.offer.clone() else {
        return;
    };
    if accepted {
        offer.accept(dnd.offer_serial, dnd.offer_accepted_mime.clone());
        if offer.version() >= 3 {
            offer.set_actions(DndAction::Copy, DndAction::Copy);
        }
    } else {
        offer.accept(dnd.offer_serial, None);
        if offer.version() >= 3 {
            offer.set_actions(DndAction::empty(), DndAction::empty());
        }
    }
}

/// Start an outbound drag from `window_id`'s surface.
///
/// The framework is told the drag started **before** the request leaves: the
/// compositor answers `start_drag` with an `enter` on whichever of our surfaces
/// is under the pointer, and the framework must have handed its in-app session
/// over by then. Both go through the one event loop, so posting first orders
/// them.
pub(crate) fn begin_outbound(
    state: &mut HubState,
    window_id: TeksiloWindowId,
    poster: &Arc<dyn AppEventPoster>,
    data: OutboundDragData,
    pointer: teksilo_tokens::PointerKind,
    drag: OsDragId,
) {
    let cancelled = ExternalDragEvent::DragEnded {
        outcome: DropOutcome::Cancelled,
        drag: Some(drag),
    };
    let Some(owner) = state.dnd.route_for_window(window_id).cloned() else {
        // No surface to drag from: the guard declines up front, so this only
        // makes sure the waiting drag still ends.
        poster.post_external(Box::new(ExternalDndEventPayload {
            window_id_owner: window_id,
            event: cancelled,
        }));
        return;
    };
    // `start_drag` needs the serial of the press that opened the current
    // implicit grab: a `wl_pointer::button` for a mouse or pen, a
    // `wl_touch::down` for a finger. Without one held, the compositor would
    // refuse silently and never send a terminal event; report the
    // cancellation instead. Taking the serial also stops counting its press as
    // held: once the grab is converted, its release goes to the compositor's
    // drag grab and never reaches us.
    let Some(serial) = state.press_serials.take_for_drag(pointer) else {
        owner.post(cancelled);
        return;
    };
    // A drag still in flight is over: a seat carries one at a time.
    if let Some(previous) = state.dnd.outbound.take() {
        previous.source.destroy();
        previous.owner.post(ExternalDragEvent::DragEnded {
            outcome: DropOutcome::Cancelled,
            drag: Some(previous.drag),
        });
    }

    owner.post(ExternalDragEvent::DragStarted { drag });

    let source = state
        .manager
        .create_data_source(&state.qh, SourceKind::Drag);
    for mime in outbound_mimes(&data) {
        source.offer(mime);
    }
    if source.version() >= 3 {
        // Copy only: never advertise Move, which would let the destination
        // physically relocate a dragged file. Move-out is an explicit opt-in.
        source.set_actions(DndAction::Copy);
    }
    state
        .device
        .start_drag(Some(&source), &owner.surface, None, serial);
    state.dnd.outbound = Some(Outbound {
        drag,
        owner,
        source,
        data,
        action: DndAction::empty(),
        dropped: false,
        coarse: pointer.is_coarse(),
        answered: false,
    });
}

/// A button release (or, for `coarse`, a touch up) reached our own
/// `wl_pointer` / `wl_touch`. Once the compositor turns the press's implicit
/// grab into a drag, the release goes to the drag and never reaches us; one
/// that does, while the drag of that device class is still unanswered, means
/// the compositor ignored `start_drag` (the release was already on its way, or
/// the grab check failed). Mutter does so without a word and without
/// cancelling the source, so nothing else would ever end the drag, and every
/// later drop on our windows would be taken for a drop of our own.
pub(crate) fn release_reached_us(state: &mut HubState, coarse: bool) {
    if state
        .dnd
        .outbound
        .as_ref()
        .is_some_and(|o| o.coarse == coarse && !o.answered && !o.dropped)
    {
        finish_outbound(state, DropOutcome::Cancelled);
    }
}

/// End the outbound drag at the framework's request (a release before the
/// start was confirmed, or Escape). Destroying the source ends a drag the
/// compositor started; with no source there is nothing to end.
pub(crate) fn cancel_outbound(state: &mut HubState) {
    if state.dnd.outbound.as_ref().is_some_and(|o| !o.dropped) {
        finish_outbound(state, DropOutcome::Cancelled);
    }
}

fn finish_outbound(state: &mut HubState, outcome: DropOutcome) {
    let Some(outbound) = state.dnd.outbound.take() else {
        return;
    };
    outbound.source.destroy();
    // Our own drag ending while it is over one of our windows is the one abort
    // a destination can be told about: the window holding the re-entered
    // session gets no `leave` for a drag the compositor has simply stopped. A
    // live route here can only belong to this drag: a seat carries one drag
    // at a time.
    if state.dnd.active_route.is_some() {
        state.dnd.post_routed(ExternalDragEvent::Cancelled);
        state.dnd.active_route = None;
    }
    outbound.owner.post(ExternalDragEvent::DragEnded {
        outcome,
        drag: Some(outbound.drag),
    });
}

fn outcome_of(action: DndAction) -> DropOutcome {
    if action.contains(DndAction::Move) {
        DropOutcome::OsMove
    } else {
        DropOutcome::OsCopy
    }
}

/// An event on our outbound drag's source.
pub(super) fn source_event(state: &mut HubState, source: &WlDataSource, event: DataSourceEvent) {
    let ours = state
        .dnd
        .outbound
        .as_ref()
        .is_some_and(|o| &o.source == source);
    if !ours {
        // A replaced drag's source: nothing waits on it any more.
        if matches!(event, DataSourceEvent::Cancelled) {
            source.destroy();
        }
        return;
    }
    if let Some(outbound) = &mut state.dnd.outbound {
        outbound.answered = true;
    }
    match event {
        DataSourceEvent::Send { mime_type, fd } => {
            if let Some(outbound) = &state.dnd.outbound {
                let bytes: Arc<[u8]> = outbound_bytes(&outbound.data, &mime_type).into();
                io::serve_in_background(fd, bytes, format!("a drag as {mime_type}"));
            }
        }
        DataSourceEvent::Action {
            dnd_action: WEnum::Value(action),
        } => {
            if let Some(outbound) = &mut state.dnd.outbound {
                outbound.action = action;
            }
        }
        DataSourceEvent::DndDropPerformed => {
            if let Some(outbound) = &mut state.dnd.outbound {
                outbound.dropped = true;
            }
        }
        // The destination finished reading: success.
        DataSourceEvent::DndFinished => {
            let action = state
                .dnd
                .outbound
                .as_ref()
                .map_or(DndAction::empty(), |o| o.action);
            finish_outbound(state, outcome_of(action));
        }
        // Before a drop: rejected or aborted. After one: some compositors end
        // with `cancelled` rather than `dnd_finished` once the target has the
        // data, so it still reports success, or no terminal event would ever
        // fire.
        DataSourceEvent::Cancelled => {
            let (dropped, action) = state
                .dnd
                .outbound
                .as_ref()
                .map_or((false, DndAction::empty()), |o| (o.dropped, o.action));
            let outcome = if dropped {
                outcome_of(action)
            } else {
                DropOutcome::Cancelled
            };
            finish_outbound(state, outcome);
        }
        _ => {}
    }
}

/// A drag event on the device (`selection` and `data_offer` are the hub's).
pub(super) fn device_event(state: &mut HubState, event: DataDeviceEvent) {
    match event {
        DataDeviceEvent::Enter {
            serial,
            surface,
            x,
            y,
            id,
        } => {
            // A drag replacing one we never saw leave: let its offer go.
            if let Some(previous) = state.dnd.offer.take()
                && id.as_ref() != Some(&previous)
            {
                previous.destroy();
            }
            state.dnd.offer = id.clone();
            // A seat carries one drag: if ours is in flight, this is it, and
            // the compositor took its start.
            if let Some(outbound) = &mut state.dnd.outbound {
                outbound.answered = true;
            }
            let Some(route) = state.dnd.routes.get(&surface.id().protocol_id()).cloned() else {
                // Not one of our surfaces (one already detached).
                state.dnd.active_route = None;
                return;
            };
            let mimes = id.as_ref().map(offer_mimes).unwrap_or_default();
            state.dnd.active_route = Some(route);
            state.dnd.position = Point::new(x as f32, y as f32);
            // Accept a type we can read AND negotiate an action, both, or the
            // compositor shows the "forbidden" cursor and blocks the drop.
            state.dnd.offer_serial = serial;
            state.dnd.offer_accepted_mime = pick_mime(&mimes);
            if let Some(offer) = &id {
                if let Some(mime) = state.dnd.offer_accepted_mime.clone() {
                    offer.accept(serial, Some(mime));
                }
                if offer.version() >= 3 {
                    offer.set_actions(DndAction::Copy, DndAction::Copy);
                }
            }
            // The bytes come at the drop; the types let the target decide
            // on hover.
            state.dnd.post_routed(ExternalDragEvent::Entered {
                data: ExternalDropData {
                    formats: mimes,
                    ..Default::default()
                },
                position: state.dnd.position,
            });
        }
        DataDeviceEvent::Motion { x, y, .. } => {
            if state.dnd.active_route.is_none() {
                return;
            }
            state.dnd.position = Point::new(x as f32, y as f32);
            state.dnd.post_routed(ExternalDragEvent::Moved {
                position: state.dnd.position,
            });
        }
        DataDeviceEvent::Leave => {
            state.dnd.post_routed(ExternalDragEvent::Left);
            state.dnd.active_route = None;
            if let Some(offer) = state.dnd.offer.take() {
                offer.destroy();
            }
            state.dnd.offer_accepted_mime = None;
            state.dnd.offer_serial = 0;
        }
        DataDeviceEvent::Drop => {
            let Some(route) = state.dnd.active_route.take() else {
                return;
            };
            let position = state.dnd.position;
            state.dnd.offer_accepted_mime = None;
            state.dnd.offer_serial = 0;
            let offer = state.dnd.offer.take();
            // Our own drag dropping on our own window: the framework recovers
            // the typed payload from its stash, and the bytes would have to
            // come from our own source, so they are not read.
            if state.dnd.outbound.is_some() {
                route.post(ExternalDragEvent::Dropped {
                    data: ExternalDropData::default(),
                    position,
                });
                if let Some(offer) = offer {
                    finish_offer(&offer);
                }
                return;
            }
            let Some(offer) = offer else {
                route.post(ExternalDragEvent::Dropped {
                    data: ExternalDropData::default(),
                    position,
                });
                return;
            };
            receive_drop(state.conn().clone(), offer, route, position);
        }
        _ => {}
    }
}

/// `finish` (version 3) tells the source the transfer is complete; `destroy`
/// is always due.
fn finish_offer(offer: &WlDataOffer) {
    if offer.version() >= 3 {
        offer.finish();
    }
    offer.destroy();
}

/// Read the drop's payload on a thread of its own, then post it and finish the
/// offer. The source is another client, and reading it on the hub's thread
/// would hold up the clipboard for as long as that client takes.
fn receive_drop(
    conn: wayland_client::Connection,
    offer: WlDataOffer,
    route: Route,
    position: Point,
) {
    let mimes = offer_mimes(&offer);
    let Some(mime) = pick_mime(&mimes) else {
        route.post(ExternalDragEvent::Dropped {
            data: ExternalDropData::default(),
            position,
        });
        finish_offer(&offer);
        return;
    };
    let (read, write) = match io::pipe() {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!("teksilo-platform: cannot read a drop: {err}");
            route.post(ExternalDragEvent::Dropped {
                data: ExternalDropData::default(),
                position,
            });
            finish_offer(&offer);
            return;
        }
    };
    offer.receive(mime.clone(), std::os::fd::AsFd::as_fd(&write));
    let _ = conn.flush();
    drop(write);
    let pending = route.begin_read();
    let reader = route.clone();
    let spawned = std::thread::Builder::new()
        .name("teksilo-wayland-drop".into())
        .spawn(move || {
            let data = match io::read_bounded(read, DROP_LIMITS) {
                Ok(bytes) => decode_drop(&mime, &bytes),
                Err(err) => {
                    eprintln!("teksilo-platform: reading a drop failed: {err}");
                    ExternalDropData::default()
                }
            };
            reader.finish_read(pending, ExternalDragEvent::Dropped { data, position });
            finish_offer(&offer);
            let _ = conn.flush();
        });
    if let Err(err) = spawned {
        eprintln!("teksilo-platform: cannot start a thread to read a drop: {err}");
        // The offer went with the closure. The drop still has to end, and the
        // window's later events must not wait behind it for ever.
        route.finish_read(
            pending,
            ExternalDragEvent::Dropped {
                data: ExternalDropData::default(),
                position,
            },
        );
    }
}

/// Pick the best MIME type we can decode from the offered set.
fn pick_mime(offered: &[String]) -> Option<String> {
    PREFERRED_MIMES
        .iter()
        .find_map(|pref| offered.iter().find(|m| m.as_str() == *pref).cloned())
}

fn decode_drop(mime: &str, bytes: &[u8]) -> ExternalDropData {
    let text = String::from_utf8_lossy(bytes).into_owned();
    if mime == "text/uri-list" {
        ExternalDropData::from_uri_list(&text)
    } else {
        ExternalDropData {
            text: Some(text),
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn uri_list_is_preferred_over_text() {
        let offered = vec![
            "text/plain".to_string(),
            "text/uri-list".to_string(),
            "text/plain;charset=utf-8".to_string(),
        ];
        assert_eq!(pick_mime(&offered).as_deref(), Some("text/uri-list"));
    }

    #[test]
    fn an_offer_of_nothing_readable_picks_nothing() {
        assert_eq!(pick_mime(&["image/png".to_string()]), None);
    }

    fn name(event: &ExternalDragEvent) -> &'static str {
        match event {
            ExternalDragEvent::Entered { .. } => "entered",
            ExternalDragEvent::Moved { .. } => "moved",
            ExternalDragEvent::Left => "left",
            ExternalDragEvent::Dropped { .. } => "dropped",
            _ => "other",
        }
    }

    fn dropped() -> ExternalDragEvent {
        ExternalDragEvent::Dropped {
            data: ExternalDropData::default(),
            position: Point::new(0.0, 0.0),
        }
    }

    fn entered() -> ExternalDragEvent {
        ExternalDragEvent::Entered {
            data: ExternalDropData::default(),
            position: Point::new(0.0, 0.0),
        }
    }

    #[test]
    fn events_wait_behind_a_drop_being_read() {
        let mut posted = Vec::new();
        let mut outbox = Outbox::default();
        outbox.post(entered(), |e| posted.push(name(&e)));
        let read = outbox.begin_read();
        // The next drag arrives while the first drop's data is still read.
        outbox.post(entered(), |e| posted.push(name(&e)));
        outbox.post(ExternalDragEvent::Left, |e| posted.push(name(&e)));
        assert_eq!(posted, ["entered"]);
        outbox.finish_read(read, dropped(), |e| posted.push(name(&e)));
        assert_eq!(posted, ["entered", "dropped", "entered", "left"]);
        // Nothing waits any more: the next event goes straight out.
        outbox.post(entered(), |e| posted.push(name(&e)));
        assert_eq!(posted.len(), 5);
    }

    #[test]
    fn drops_finishing_out_of_order_are_posted_in_order() {
        let mut posted = Vec::new();
        let mut outbox = Outbox::default();
        let first = outbox.begin_read();
        outbox.post(entered(), |e| posted.push(name(&e)));
        let second = outbox.begin_read();
        outbox.post(ExternalDragEvent::Left, |e| posted.push(name(&e)));
        // The second drop's data arrives first: it waits for the first.
        outbox.finish_read(second, dropped(), |e| posted.push(name(&e)));
        assert!(posted.is_empty());
        outbox.finish_read(first, dropped(), |e| posted.push(name(&e)));
        assert_eq!(posted, ["dropped", "entered", "dropped", "left"]);
    }

    #[test]
    fn a_dropped_uri_list_becomes_files() {
        let data = decode_drop("text/uri-list", b"file:///tmp/a.txt\r\n");
        assert_eq!(data.files.len(), 1);
    }
}