drawbar 0.6.0

Your Nord's sounds, in a window: browse, edit and send programs, samples and pianos, in the browser or on the desktop
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
//! The centre: one tab per open document, plus the library and the keyboard.
//!
//! A document tab is a view of an asset on this computer. Opening something off the
//! instrument copies it here first, so what a tab holds is always a working copy —
//! editing it changes nothing on the instrument until it is sent back. The library and
//! the keyboard are views of what is already there, so they hold nothing.

use eframe::egui;
use nord_usb::ObjectClass;

use crate::browser::{Act, Kind};
use crate::icon::{painted, Glyph};
use crate::panel::{GAP, GLYPH, PAD};
use crate::shell::new_button;
use crate::workspace::Workspace;

/// ⚠️ The strip's own scroll id. The strip and the document body are drawn into the same
/// `Ui`, and egui salts an unsalted `ScrollArea` with that `Ui` alone — two of them there
/// share one state, and a wheel over the body moves the strip instead of the document.
pub const SCROLL: &str = "tab_strip";

/// How tall the strip is.
pub const HEIGHT: f32 = 26.0;

/// Which of the centre's views a tab shows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Spot {
    Document(u64),
    Library,
    Keyboard,
}

pub struct Tabs {
    /// ⚠️ [`Spot::Library`] is the first of these and stays there: it is what the centre
    /// falls back to, so nothing closes it and nothing moves it.
    open: Vec<Spot>,
    active: Option<Spot>,
    /// Which class the keyboard tab is switched to, as the tree last asked. There is one
    /// keyboard tab, so the class it is on is the tab's state rather than a tab of its
    /// own.
    keyboard: Option<ObjectClass>,
}

impl Default for Tabs {
    fn default() -> Tabs {
        Tabs {
            open: vec![Spot::Library],
            active: Some(Spot::Library),
            keyboard: None,
        }
    }
}

impl Tabs {
    /// Open a document, or bring the tab already on it forward.
    pub fn open(&mut self, id: u64) {
        if !self.holds(id) {
            self.open.push(Spot::Document(id));
        }
        self.active = Some(Spot::Document(id));
    }

    /// Bring a tab forward, opening the keyboard if that is what is asked for.
    ///
    /// ⚠️ There is one keyboard, so showing it is opening it. The library is always
    /// open, and a document tab is made by [`Tabs::open`] alone.
    pub fn show(&mut self, spot: Spot) {
        let held = self.open.contains(&spot);
        match (held, spot) {
            (true, _) => {}
            (false, Spot::Keyboard) => self.open.push(Spot::Keyboard),
            (false, Spot::Library | Spot::Document(_)) => return,
        }
        self.active = Some(spot);
    }

    /// Switch the keyboard tab to a class. Bringing the tab forward is [`Tabs::show`];
    /// this says what it opens on.
    pub fn keyboard_on(&mut self, class: ObjectClass) {
        self.keyboard = Some(class);
    }

    /// The class the keyboard tab is switched to, if anything has asked for one.
    pub fn keyboard_class(&self) -> Option<ObjectClass> {
        self.keyboard
    }

    /// Move the tab at `from` to sit where the one at `to` is, the rest closing up
    /// behind it. An index the strip does not hold moves nothing.
    ///
    /// The keyboard moves like any other tab. ⚠️ The library is the first tab and stays
    /// there: it is never what moves, and a tab let go over it lands after it.
    pub fn reorder(&mut self, from: usize, to: usize) {
        let to = to.max(1);
        if from == 0 || from == to || from >= self.open.len() || to >= self.open.len() {
            return;
        }
        let tab = self.open.remove(from);
        self.open.insert(to, tab);
    }

    /// Shut a tab, falling back to whatever is nearest the front.
    ///
    /// ⚠️ The library is where every close lands, so asking to close it does nothing.
    pub fn close(&mut self, spot: Spot) {
        if spot == Spot::Library {
            return;
        }
        self.open.retain(|held| *held != spot);
        if self.active == Some(spot) {
            self.active = self.open.last().copied();
        }
    }

    /// What the centre is drawing.
    pub fn showing(&self) -> Option<Spot> {
        self.active
    }

    /// The document the centre is on, if it is on one.
    pub fn active(&self) -> Option<u64> {
        match self.active {
            Some(Spot::Document(id)) => Some(id),
            _ => None,
        }
    }

    /// The document tab nearest the front, whether or not it is showing.
    pub fn last_document(&self) -> Option<u64> {
        self.active().or_else(|| {
            self.open.iter().rev().find_map(|spot| match spot {
                Spot::Document(id) => Some(*id),
                Spot::Library | Spot::Keyboard => None,
            })
        })
    }

    /// Whether a tab is open on this document, in front or behind.
    pub fn holds(&self, id: u64) -> bool {
        self.open.contains(&Spot::Document(id))
    }

    /// Drop tabs whose asset is no longer on this computer.
    pub fn prune(&mut self, workspace: &Workspace) {
        self.open.retain(|spot| match spot {
            Spot::Document(id) => workspace.entities().iter().any(|e| e.id == *id),
            Spot::Library | Spot::Keyboard => true,
        });
        if self.active.is_some_and(|spot| !self.open.contains(&spot)) {
            self.active = self.open.last().copied();
        }
    }

    /// The strip. The open view draws itself below it.
    ///
    /// ⚠️ The scroll area is a direct child of the caller's `Ui`, and its salt is
    /// [`SCROLL`]: the document body below carries its own, and two unsalted areas in one
    /// `Ui` would share a state.
    pub fn ui(&mut self, ui: &mut egui::Ui, workspace: &Workspace, acts: &mut Vec<Act>) {
        let rect = egui::Rect::from_min_size(
            egui::pos2(ui.max_rect().left(), ui.cursor().top()),
            egui::vec2(ui.available_width(), HEIGHT),
        );
        ui.painter()
            .rect_filled(rect, 0.0, ui.visuals().window_fill);

        let mut close = None;
        let mut activate = None;
        let mut dropped = None;
        let mut painted: Vec<(usize, egui::Rect)> = Vec::new();
        egui::ScrollArea::horizontal()
            .id_salt(SCROLL)
            .max_height(HEIGHT)
            // A bar inside 26 px would take a third of the strip it is scrolling.
            .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
            .auto_shrink([false; 2])
            .show(ui, |ui| {
                ui.spacing_mut().item_spacing = egui::Vec2::ZERO;
                ui.horizontal(|ui| {
                    for (index, spot) in self.open.iter().copied().enumerate() {
                        let Some(face) = face(spot, workspace) else {
                            continue;
                        };
                        let drawn = paint(ui, &face, self.active == Some(spot));
                        painted.push((index, drawn.tab.rect));
                        let mut label = drawn.tab;
                        if label.dragged() {
                            ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
                        }
                        if let Some(at) = label
                            .drag_stopped()
                            .then(|| ui.ctx().pointer_interact_pos())
                            .flatten()
                        {
                            dropped = Some((index, at.x));
                        }
                        if let Some(hint) = &face.hint {
                            label = label.on_hover_text(hint);
                        }
                        if label.clicked() {
                            activate = Some(spot);
                        }
                        if drawn.close.is_some_and(|shut| shut.clicked()) {
                            close = Some(spot);
                        }
                    }
                    let ink = crate::app::caption(ui.visuals());
                    new_button(ui, Glyph::Plus, ink, acts);
                });
            });
        if let Some(spot) = activate {
            self.active = Some(spot);
        }
        if let Some(spot) = close {
            self.close(spot);
        }
        if let Some((from, x)) = dropped {
            if let Some(to) = landing(&painted, x) {
                self.reorder(from, to);
            }
        }
    }
}

/// Which tab a drag was let go over: the one the pointer is inside, or the tab at
/// whichever end it was carried past.
fn landing(painted: &[(usize, egui::Rect)], x: f32) -> Option<usize> {
    let (first, left) = painted.first()?;
    let (last, right) = painted.last()?;
    if x < left.left() {
        return Some(*first);
    }
    if x > right.right() {
        return Some(*last);
    }
    painted
        .iter()
        .find(|(_, rect)| rect.x_range().contains(x))
        .map(|(index, _)| *index)
}

/// A tab as it is drawn: what it wears, what it says, and whether it is saved.
struct Face {
    glyph: Glyph,
    name: String,
    /// It holds something other than what it was last saved as, which the name says by
    /// going italic and wearing a star — the mark it wears everywhere else.
    unsaved: bool,
    /// What a hover says: the whole of the name a tab shows short, and what else there
    /// is to know about this tab.
    hint: Option<String>,
    /// The × at the end. The library has none: it is what a close falls back to.
    shut: bool,
}

fn face(spot: Spot, workspace: &Workspace) -> Option<Face> {
    match spot {
        Spot::Library => Some(Face {
            glyph: Glyph::LibraryBig,
            name: "Library".into(),
            unsaved: false,
            hint: None,
            shut: false,
        }),
        Spot::Keyboard => Some(Face {
            glyph: Glyph::Keyboard,
            name: "Keyboard".into(),
            unsaved: false,
            hint: None,
            shut: true,
        }),
        Spot::Document(id) => {
            let entity = workspace.get(id)?;
            Some(Face {
                glyph: Kind::of(entity.entity.as_ref()).glyph(),
                name: entity.name.clone(),
                unsaved: entity.is_unsaved(),
                hint: Some(match workspace.is_view(id) {
                    true => format!("{} — the instrument's copy, viewed in place", entity.name),
                    false => entity.name.clone(),
                }),
                shut: true,
            })
        }
    }
}

/// What a click on a drawn tab landed on.
struct Drawn {
    tab: egui::Response,
    /// The ×, on every tab that has one.
    close: Option<egui::Response>,
}

/// The × at the end of every tab.
const SHUT: f32 = 11.0;

fn paint(ui: &mut egui::Ui, face: &Face, active: bool) -> Drawn {
    let visuals = ui.visuals().clone();
    let ink = match active {
        true => visuals.widgets.active.fg_stroke.color,
        false => crate::app::caption(&visuals),
    };
    let mut text = egui::RichText::new(crate::browser::starred(&face.name, face.unsaved))
        .text_style(crate::app::ui());
    if face.unsaved {
        text = text.italics();
    }
    let galley = egui::WidgetText::from(text.color(ink)).into_galley(
        ui,
        Some(egui::TextWrapMode::Extend),
        f32::INFINITY,
        crate::app::ui(),
    );

    let closes = match face.shut {
        true => GAP + SHUT,
        false => 0.0,
    };
    let width = PAD + GLYPH + GAP + galley.size().x + closes + PAD;
    let (rect, tab) =
        ui.allocate_exact_size(egui::vec2(width, HEIGHT), egui::Sense::click_and_drag());
    let painter = ui.painter().clone();

    if active {
        painter.rect_filled(rect, 0.0, visuals.panel_fill);
        painter.hline(
            rect.x_range(),
            rect.bottom() - 1.0,
            egui::Stroke::new(2.0_f32, crate::app::accent(&visuals)),
        );
    }
    painter.vline(
        rect.right() - 0.5,
        rect.y_range(),
        egui::Stroke::new(1.0_f32, visuals.widgets.noninteractive.bg_stroke.color),
    );

    let mut x = rect.left() + PAD;
    let box_ = |x: f32, size: f32| {
        egui::Rect::from_min_size(
            egui::pos2(x, rect.center().y - size / 2.0),
            egui::vec2(size, size),
        )
    };
    painted(ui, face.glyph, box_(x, GLYPH), ink);
    x += GLYPH + GAP;
    painter.galley(
        egui::pos2(x, rect.center().y - galley.size().y / 2.0),
        galley.clone(),
        egui::Color32::PLACEHOLDER,
    );
    x += galley.size().x;
    let close = face.shut.then(|| {
        let shut = box_(x + GAP, SHUT);
        painted(ui, Glyph::X, shut, ink.gamma_multiply(0.5));
        ui.interact(shut, tab.id.with("close"), egui::Sense::click())
    });
    Drawn { tab, close }
}

/// Every string a frame painted, headers and button labels included.
#[cfg(test)]
pub(crate) fn words(output: &egui::FullOutput) -> Vec<String> {
    fn walk(shape: &egui::Shape, into: &mut Vec<String>) {
        match shape {
            egui::Shape::Text(text) => into.push(text.galley.text().to_string()),
            egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, into)),
            _ => {}
        }
    }
    let mut said = Vec::new();
    for clipped in &output.shapes {
        walk(&clipped.shape, &mut said);
    }
    said
}

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

    fn workspace() -> Workspace {
        Workspace::new(egui::Context::default())
    }

    /// Opening the same asset twice is the same tab, brought forward.
    #[test]
    fn opening_an_asset_that_is_already_open_just_activates_it() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.open(2);
        tabs.open(1);
        assert_eq!(tabs.open.len(), 3, "the library, and the two documents");
        assert_eq!(tabs.active(), Some(1));
    }

    /// Closing what is in front falls back to another tab, and closing the last document
    /// falls back to the library.
    #[test]
    fn closing_the_active_tab_falls_back_to_another() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.open(2);
        tabs.close(Spot::Document(2));
        assert_eq!(tabs.active(), Some(1));
        tabs.close(Spot::Document(1));
        assert_eq!(tabs.active(), None);
        assert_eq!(tabs.showing(), Some(Spot::Library));
    }

    /// ⚠️ The library is where a close lands, so it is not itself closable — and the
    /// strip is never empty, whatever is asked of it.
    #[test]
    fn closing_the_library_does_nothing_and_leaves_the_strip_standing() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.show(Spot::Keyboard);
        for spot in [
            Spot::Library,
            Spot::Document(1),
            Spot::Keyboard,
            Spot::Library,
        ] {
            tabs.close(spot);
        }
        assert_eq!(tabs.open, vec![Spot::Library]);
        assert_eq!(tabs.showing(), Some(Spot::Library));
    }

    /// Closing a tab that is not in front leaves the front one showing.
    #[test]
    fn closing_a_background_tab_leaves_the_front_one_showing() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.open(2);
        tabs.close(Spot::Document(1));
        assert_eq!(tabs.active(), Some(2));
    }

    /// Whether a tab is open is its own question, not one inferred from what it is over
    /// — a document over nothing at all is still open.
    #[test]
    fn a_tab_says_whether_it_is_open_whatever_it_holds() {
        let mut tabs = Tabs::default();
        assert!(!tabs.holds(1));
        // Nothing in the workspace under this id, so the tab stands for nothing.
        tabs.open(1);
        tabs.open(2);
        assert!(tabs.holds(1) && tabs.holds(2), "both are open");
        assert!(!tabs.holds(3));

        // Behind the front one still counts.
        tabs.close(Spot::Document(2));
        assert!(tabs.holds(1) && !tabs.holds(2));
        tabs.close(Spot::Document(1));
        assert!(!tabs.holds(1));
    }

    /// The one mark a tab wears: an unsaved document's name goes italic and takes a
    /// star, which is what it wears in the tree and the table as well.
    #[test]
    fn a_tab_over_an_unsaved_document_wears_a_star() {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(crate::app::metrics);
        let mut ws = Workspace::new(ctx.clone());
        let mut log = crate::log::Log::default();
        let id = ws
            .create(crate::workspace::Fresh::Program, &mut log)
            .unwrap();
        ws.rename(id, "Africa Split".into());
        let mut tabs = Tabs::default();
        tabs.open(id);

        let strip = |tabs: &mut Tabs, ws: &Workspace| {
            let input = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(600.0, 300.0),
                )),
                ..Default::default()
            };
            let output = ctx.run(input, |ctx| {
                egui::CentralPanel::default()
                    .frame(egui::Frame::new())
                    .show(ctx, |ui| {
                        tabs.ui(ui, ws, &mut Vec::new());
                    });
            });
            words(&output)
        };

        let said = strip(&mut tabs, &ws);
        assert!(said.contains(&"Africa Split".to_string()), "{said:?}");

        let bytes = ws.get(id).unwrap().bytes.clone();
        let (_, edited) =
            crate::fields::apply(&bytes, &[("center_panel.gain".into(), "96".into())]).unwrap();
        ws.replace_bytes(id, edited, &mut log);

        let said = strip(&mut tabs, &ws);
        assert!(said.contains(&"Africa Split*".to_string()), "{said:?}");
    }

    /// There is one library and one keyboard, so asking for either twice is one tab
    /// brought forward — and a document opened between them does not make a second.
    #[test]
    fn the_library_and_the_keyboard_are_each_one_tab() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.show(Spot::Keyboard);
        tabs.show(Spot::Library);
        assert_eq!(tabs.open.len(), 3);
        assert_eq!(tabs.showing(), Some(Spot::Library));
        // The centre is on the library, so no document is open in it.
        assert_eq!(tabs.active(), None);
        assert_eq!(tabs.last_document(), Some(1));
    }

    /// A document is opened with its bytes or not at all: `show` cannot make one, and
    /// asking it to leaves what was in front where it was.
    #[test]
    fn showing_a_document_that_no_tab_holds_changes_nothing() {
        let mut tabs = Tabs::default();
        tabs.show(Spot::Library);
        tabs.show(Spot::Document(7));
        assert_eq!(tabs.showing(), Some(Spot::Library));
        assert!(!tabs.holds(7));
    }

    /// Moving a tab closes the strip up behind it, wherever it came from and wherever it
    /// lands. ⚠️ The library stays first: neither end of a move may be it.
    #[test]
    fn reordering_moves_one_tab_and_closes_the_strip_up_behind_it() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.open(2);
        tabs.show(Spot::Keyboard);
        let order = |tabs: &Tabs| tabs.open.clone();

        tabs.reorder(1, 3);
        assert_eq!(
            order(&tabs),
            vec![
                Spot::Library,
                Spot::Document(2),
                Spot::Keyboard,
                Spot::Document(1)
            ]
        );
        tabs.reorder(3, 1);
        assert_eq!(
            order(&tabs),
            vec![
                Spot::Library,
                Spot::Document(1),
                Spot::Document(2),
                Spot::Keyboard
            ]
        );
        tabs.reorder(0, 2);
        assert_eq!(
            order(&tabs),
            vec![
                Spot::Library,
                Spot::Document(1),
                Spot::Document(2),
                Spot::Keyboard
            ],
            "the library itself never moves"
        );
        tabs.reorder(2, 0);
        assert_eq!(
            order(&tabs),
            vec![
                Spot::Library,
                Spot::Document(2),
                Spot::Document(1),
                Spot::Keyboard
            ],
            "a tab let go over the library lands after it"
        );
        assert_eq!(
            tabs.showing(),
            Some(Spot::Keyboard),
            "moving is not showing"
        );
    }

    /// An index the strip does not hold is not a move, so nothing is dropped and nothing
    /// panics on the way.
    #[test]
    fn reordering_past_the_end_of_the_strip_moves_nothing() {
        let mut tabs = Tabs::default();
        tabs.open(1);
        tabs.open(2);
        let before = tabs.open.clone();
        for (from, to) in [(0, 0), (0, 2), (5, 1), (9, 9)] {
            tabs.reorder(from, to);
        }
        assert_eq!(tabs.open, before);
    }

    /// Where a drop lands: the tab under the pointer, or the tab at whichever end it was
    /// carried past.
    #[test]
    fn a_drop_lands_on_the_tab_under_it_or_on_the_end_it_passed() {
        let box_ = |left: f32, right: f32| {
            egui::Rect::from_min_max(egui::pos2(left, 0.0), egui::pos2(right, HEIGHT))
        };
        let painted = [(0, box_(0.0, 60.0)), (1, box_(60.0, 130.0))];
        assert_eq!(landing(&painted, 30.0), Some(0));
        assert_eq!(landing(&painted, 100.0), Some(1));
        assert_eq!(landing(&painted, -40.0), Some(0), "carried off the left");
        assert_eq!(landing(&painted, 900.0), Some(1), "carried off the right");
        assert_eq!(landing(&[], 30.0), None, "an empty strip takes no drop");
    }

    /// Dragging a tab across its neighbour and letting go swaps the two. Nothing is
    /// activated by it: a release that moved is a drop, not a click.
    #[test]
    fn dragging_a_tab_across_its_neighbour_swaps_them() {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(crate::app::metrics);
        let mut ws = Workspace::new(ctx.clone());
        let mut log = crate::log::Log::default();
        let first = ws
            .create(crate::workspace::Fresh::Program, &mut log)
            .unwrap();
        let second = ws.create(crate::workspace::Fresh::Live, &mut log).unwrap();
        // Long enough that the tab reaches well past the library's own, which is the one
        // tab a drag may not start on.
        ws.rename(
            first,
            "Africa Split, the one with the long tail".to_string(),
        );
        let mut tabs = Tabs::default();
        tabs.open(first);
        tabs.open(second);

        // Inside the first document's tab, and far past the right of the last one.
        let (from, to) = (
            egui::pos2(200.0, HEIGHT / 2.0),
            egui::pos2(4_000.0, HEIGHT / 2.0),
        );
        let button = |pos, pressed| egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed,
            modifiers: egui::Modifiers::NONE,
        };
        let frames: [Vec<egui::Event>; 5] = [
            vec![egui::Event::PointerMoved(from)],
            vec![button(from, true)],
            vec![egui::Event::PointerMoved(to)],
            vec![button(to, false)],
            Vec::new(),
        ];
        for events in frames {
            let input = egui::RawInput {
                events,
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(600.0, 300.0),
                )),
                ..Default::default()
            };
            let _ = ctx.run(input, |ctx| {
                egui::CentralPanel::default()
                    .frame(egui::Frame::new())
                    .show(ctx, |ui| {
                        tabs.ui(ui, &ws, &mut Vec::new());
                    });
            });
        }

        assert_eq!(
            tabs.open,
            vec![Spot::Library, Spot::Document(second), Spot::Document(first)],
            "the dragged tab landed past its neighbour"
        );
        assert_eq!(
            tabs.showing(),
            Some(Spot::Document(second)),
            "a drop is not a click, so what was in front stayed in front"
        );
    }

    /// Pruning drops documents the list no longer holds; the two singletons are views of
    /// what is there rather than of an asset, so nothing prunes them.
    #[test]
    fn pruning_takes_documents_and_leaves_the_singletons() {
        let (mut tabs, mut ws) = (Tabs::default(), workspace());
        let mut log = crate::log::Log::default();
        let id = ws
            .create(crate::workspace::Fresh::Program, &mut log)
            .unwrap();
        tabs.open(id);
        ws.remove(id, &mut log);
        tabs.prune(&ws);
        assert!(!tabs.holds(id));
        assert_eq!(tabs.showing(), Some(Spot::Library));
    }
}