egui_stack 0.32.1

Docking system for egui, continuing egui_dock
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! The drag of a space across viewports, as each viewport's area sees it: see
//! [`session`](crate::dock_area::session).

use egui::{Key, Pos2, Rect, Ui};

use super::super::{
    drag_and_drop::{DragData, TreeComponent, make_overlay_painter},
    session::{DragSession, Outcome, RELEASED_PASSES, Report},
    state::State,
};
use crate::dock_space::record_origin;
use crate::layout::ZoneName;
use crate::{
    DockArea, Surface, TabDestination, TabIndex, TabInsert, TabPath, TabViewer, WindowOutlinePaint,
};

/// What an area does with its space's drag this pass.
pub(super) enum Across {
    /// The drag is this viewport's, or there is none: resolved as in one viewport.
    Here,
    /// Another viewport's drag, the pointer over this one: its preview shown here, and what a
    /// release would do reported. With `take`, released where positions are hidden: the drop
    /// is this viewport's if the pointer is over one of its docks.
    Remote { take: bool },
    /// This viewport's drag, the pointer over another viewport that shows the preview.
    Covered,
    /// Settled for this pass: nothing more to resolve.
    Done,
}

impl<Tab> DockArea<'_, Tab> {
    /// Keeps the space's drag session up to date from this viewport's pass: the drag begun
    /// here (`drag_data`) moves the session's pointer, and its release applies what the viewport
    /// under the pointer reported; a drag begun elsewhere gets its pointer converted to this
    /// viewport's points, and `drag_data` set to the session's, for the preview.
    pub(super) fn across(
        &mut self,
        ui: &Ui,
        state: &mut State,
        drag_data: &mut Option<DragData>,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) -> Across {
        if self
            .space
            .as_ref()
            .and_then(|space| space.floating.session.as_ref())
            .is_some_and(|session| !self.source_valid(&session.src))
        {
            if let Some(space) = self.space.as_mut() {
                space.floating.session = None;
            }
            Self::idle(state);
            self.forget_verdicts();
        }
        let Some(space) = self.space.as_mut() else {
            return Across::Here;
        };
        let ctx = ui.ctx();
        let viewport = ctx.viewport_id();
        let rank = space.rank;
        let ppp = ctx.pixels_per_point();
        let (escape, released, bounds, origin, own) = ctx.input(|i| {
            (
                i.key_pressed(Key::Escape),
                i.pointer.primary_released(),
                i.viewport_rect(),
                // Where the viewport is on the desktop, in physical pixels: unknown where the
                // system hides window positions.
                i.viewport().inner_rect.map(|r| r.min.to_vec2() * ppp),
                i.pointer.hover_pos(),
            )
        });

        if let Some(drag) = drag_data.as_ref() {
            // The drag is this viewport's: it keeps the pointer, even past its edges.
            let local = state
                .last_hover_pos
                .or_else(|| ctx.input(|i| i.pointer.latest_pos()))
                .unwrap_or(Pos2::ZERO);
            let others = space
                .docks
                .iter()
                .any(|dock| dock.viewport.is_some_and(|v| v != viewport));
            let session = match &mut space.floating.session {
                Some(session)
                    if session.source == viewport
                        && session.src == drag.src
                        && session.released.is_none() =>
                {
                    session
                }
                slot => slot.insert(DragSession::new(
                    drag.src.clone(),
                    drag.rect,
                    viewport,
                    local,
                )),
            };
            session.pass += 1;
            session.local = local;
            session.desktop = origin.map(|origin| (origin + local.to_vec2() * ppp).to_pos2());
            session.outside = !bounds.contains(local);
            session.cancelled |= escape;
            if session.cancelled {
                *drag_data = None;
                state.dnd = None;
                if released {
                    space.floating.session = None;
                    state.reset_drag();
                    self.forget_verdicts();
                }
                return Across::Done;
            }
            let remote = session.remote(rank).cloned();
            if !released {
                if remote.is_some() {
                    state.dnd = None;
                    return Across::Covered;
                }
                return Across::Here;
            }
            let (src, size) = (session.src.clone(), session.rect.size());
            // Released outside, where no viewport could tell the pointer was over it: the first
            // that sees it over one of its docks within a few passes takes it.
            let wait = remote.is_none() && session.outside && session.desktop.is_none() && others;
            if wait {
                session.released = Some(RELEASED_PASSES);
                state.reset_drag();
                state.dnd = None;
                ctx.request_repaint();
                return Across::Done;
            }
            space.floating.session = None;
            let Some(report) = remote else {
                return Across::Here;
            };
            let rect = Rect::from_min_size(local, size);
            self.release_over(report, src, rect, tab_viewer);
            state.reset_drag();
            state.dnd = None;
            self.forget_verdicts();
            ctx.request_repaint();
            return Across::Done;
        }

        let Some(session) = space.floating.session.as_mut() else {
            Self::idle(state);
            return Across::Here;
        };
        if session.source == viewport {
            // The drag begun here is no longer dragged: let go outside and waiting for another
            // viewport, or aborted (egui stops a drag on Escape).
            return match session.released {
                Some(0) => {
                    // Nobody took it: as over nothing, a new float.
                    let (src, rect) = (
                        session.src.clone(),
                        Rect::from_min_size(session.local, session.rect.size()),
                    );
                    space.floating.session = None;
                    self.release_free(src, rect, tab_viewer);
                    self.forget_verdicts();
                    Across::Done
                }
                Some(left) => {
                    session.released = Some(left - 1);
                    ctx.request_repaint();
                    Across::Here
                }
                None => {
                    space.floating.session = None;
                    Across::Here
                }
            };
        }

        // Another viewport's drag.
        if session.cancelled {
            session.reports.remove(&viewport);
            Self::idle(state);
            return Across::Done;
        }
        let pointer = if session.released.is_some() {
            // Let go: the pointer has come into this window, or not.
            own
        } else {
            session
                .desktop
                .zip(origin)
                .map(|(desktop, origin)| ((desktop.to_vec2() - origin) / ppp).to_pos2())
        };
        let Some(pointer) = pointer.filter(|pointer| bounds.contains(*pointer)) else {
            session.reports.remove(&viewport);
            // Where positions are hidden, each window that could take the drop outlines its
            // docks once the pointer leaves the drag's window.
            let outline =
                session.desktop.is_none() && session.outside && session.released.is_none();
            let src = session.src.clone();
            Self::idle(state);
            if outline {
                self.paint_outlines(ui, &src, tab_viewer);
                ctx.request_repaint();
            }
            return Across::Done;
        };
        let (src, rect, take) = (
            session.src.clone(),
            session.rect,
            session.released.is_some(),
        );
        state.remote = true;
        state.last_hover_pos = Some(pointer);
        state.drag_start.get_or_insert(pointer);
        *drag_data = Some(DragData { src, rect });
        ctx.request_repaint();
        Across::Remote { take }
    }

    /// Leaves another viewport's drag, if this area showed it.
    fn idle(state: &mut State) {
        if std::mem::take(&mut state.remote) {
            state.reset_drag();
            state.dnd = None;
        }
    }

    /// Forgets the bus's verdicts: a drag ended.
    pub(super) fn forget_verdicts(&self) {
        #[cfg(feature = "bus")]
        if let Some(bus) = self.space.as_ref().and_then(|space| space.bus) {
            bus.forget_verdicts();
        }
    }

    /// What a release over this viewport would do, for another viewport's drag: reported to
    /// the session, or, `take`n where positions are hidden, done here.
    pub(super) fn report(
        &mut self,
        ui: &Ui,
        state: &mut State,
        outcome: Outcome,
        unfold: Option<ZoneName>,
        take: bool,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) {
        let viewport = ui.ctx().viewport_id();
        let Some(space) = self.space.as_mut() else {
            return;
        };
        let rank = space.rank;
        let Some(session) = space.floating.session.as_mut() else {
            return;
        };
        if !take {
            let stamp = session.pass;
            session.reports.insert(
                viewport,
                Report {
                    stamp,
                    rank,
                    outcome,
                    unfold,
                },
            );
            return;
        }
        let (src, rect) = (session.src.clone(), session.rect);
        match outcome {
            // Over none of its docks: another viewport may still take it.
            Outcome::Free => return,
            Outcome::Refused => space.floating.session = None,
            Outcome::Drop(_) => space.floating.session = None,
        }
        let report = Report {
            stamp: 0,
            rank,
            outcome,
            unfold,
        };
        self.release_over(report, src, rect, tab_viewer);
        Self::idle(state);
        self.forget_verdicts();
        ui.ctx().request_repaint();
    }

    /// The release of `src` over what `report` says: the move, asked to the veto again; nothing
    /// where refused; a new float at `rect` over nothing.
    fn release_over(
        &mut self,
        report: Report,
        src: TreeComponent,
        rect: Rect,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) {
        if !self.source_valid(&src) {
            return;
        }
        match report.outcome {
            Outcome::Drop(destination) => {
                if !self.destination_valid(&destination) {
                    return;
                }
                let surface = match destination {
                    TabDestination::Node(path, _) => Some(path.surface),
                    TabDestination::EmptySurface(surface) => Some(surface),
                    TabDestination::Window(_) => None,
                };
                // A new window is a tear-off, which the source's rules decide; an existing
                // window is joined, which its own rules and the veto below decide.
                let may = match surface {
                    None => self.component_may_float(&src, tab_viewer),
                    Some(surface) => {
                        self.dock_rules(surface)
                            .is_none_or(|rules| rules.accept_drops)
                            && self.may_join(&src, surface, tab_viewer)
                    }
                };
                if !may {
                    return;
                }
                let dock = match destination {
                    TabDestination::Node(path, _) => self.dock_name(path.surface),
                    TabDestination::EmptySurface(surface) => self.dock_name(surface),
                    TabDestination::Window(_) => None,
                }
                .map(str::to_owned);
                if let Some(space) = &mut self.space {
                    space.drop_zone = dock.zip(report.unfold.clone());
                }
                if self
                    .refusal_of(&src, tab_viewer, &destination, true)
                    .is_none()
                    && self.apply_move(src, destination, tab_viewer)
                    && let (Some(zone), Some(space)) = (report.unfold, &mut self.space)
                {
                    space.no_drop.unfolds.push(zone);
                }
            }
            Outcome::Refused => {}
            Outcome::Free => self.release_free(src, rect, tab_viewer),
        }
    }

    /// `src` released over nothing: a new float at `rect` (this viewport's points), if it may
    /// float and the veto allows it; else it stays where it was.
    fn release_free(
        &mut self,
        src: TreeComponent,
        rect: Rect,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) {
        if !self.floats_on() || !self.source_valid(&src) {
            return;
        }
        let may = self.component_may_float(&src, tab_viewer);
        // Outside the floats' work area: refused, or torn out to a native window.
        let Some(host) = self.release_host(rect.min) else {
            return;
        };
        let destination = TabDestination::Window(rect);
        if may
            && self
                .refusal_of(&src, tab_viewer, &destination, true)
                .is_none()
        {
            self.to_float.push((src, rect, Some(host)));
        }
    }

    /// Whether `src` is still a tab or a leaf of the state.
    pub(super) fn source_valid(&self, src: &TreeComponent) -> bool {
        match *src {
            TreeComponent::Tab(path) => self
                .dock_state
                .leaf(path.node_path())
                .is_ok_and(|leaf| path.tab.0 < leaf.tabs.len()),
            TreeComponent::Node(path) => self
                .dock_state
                .leaf(path)
                .is_ok_and(|leaf| !leaf.tabs.is_empty()),
            TreeComponent::Surface(_) => false,
        }
    }

    /// Whether a destination still refers to a usable surface or leaf.
    pub(super) fn destination_valid(&self, destination: &TabDestination) -> bool {
        match *destination {
            TabDestination::Node(path, ref insert) => {
                self.dock_state.leaf(path).is_ok_and(|leaf| match insert {
                    TabInsert::Insert(index) => index.0 <= leaf.tabs.len(),
                    _ => true,
                })
            }
            TabDestination::EmptySurface(surface) => self
                .dock_state
                .get_surface(surface)
                .and_then(Surface::node_tree)
                .is_some_and(|tree| tree.is_empty()),
            TabDestination::Window(_) => true,
        }
    }

    /// Moves `src`, a tab or a whole leaf, to `destination`, once: unless the source or the
    /// destination is gone (a window closed during the drag). A tab that leaves a dock for a
    /// float's records where it came from; one that lands in a dock no float shows forgets it.
    /// Returns whether it moved.
    pub(super) fn apply_move(
        &mut self,
        src: TreeComponent,
        destination: TabDestination,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) -> bool {
        if !self.source_valid(&src) {
            return false;
        }
        if !self.destination_valid(&destination) {
            return false;
        }
        let to = match destination {
            TabDestination::Node(path, _) => Some(path.surface),
            TabDestination::EmptySurface(surface) => Some(surface),
            TabDestination::Window(_) => None,
        };
        if let Some(to) = to {
            self.track_origins(&src, to, tab_viewer);
        }
        #[cfg(feature = "bus")]
        self.emit_moved(&destination);
        match src {
            TreeComponent::Node(path) => self.dock_state.move_node(path, destination),
            TreeComponent::Tab(path) => {
                let count = self.dock_state[path.node_path()].tabs_count();
                self.dock_state.move_tab(path, destination);
                // Unhide the tab bar on the source leaf when a tab is dragged out.
                if self.hidable_tab_bars
                    && let Ok(leaf) = self.dock_state.leaf_mut(path.node_path())
                    && leaf.tabs.len() < count
                    && leaf.tab_bar_hidden
                {
                    leaf.tab_bar_hidden = false;
                }
            }
            TreeComponent::Surface(_) => return false,
        }
        true
    }

    /// The origins of the tabs of `src` moving to the surface `to`: recorded when they leave a
    /// dock for a float's, forgotten when they land in a dock no float shows, kept from float
    /// to float.
    fn track_origins(
        &mut self,
        src: &TreeComponent,
        to: crate::SurfaceIndex,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) {
        let Some(space) = self.space.as_mut() else {
            return;
        };
        if !space.floating.enabled {
            return;
        }
        let from = src.surface_address();
        let is_float = |surface| {
            space
                .docks
                .iter()
                .any(|dock| dock.surface == surface && dock.floating)
        };
        let from_float = is_float(from) || self.dock_state.is_window(from);
        let to_float = is_float(to);
        if from_float == to_float {
            return;
        }
        let paths: Vec<TabPath> = match *src {
            TreeComponent::Tab(path) => vec![path],
            TreeComponent::Node(path) => (0..self.dock_state[path].tabs_count())
                .map(|i| TabPath::new(path.surface, path.node, TabIndex(i)))
                .collect(),
            TreeComponent::Surface(_) => return,
        };
        if to_float {
            for path in paths {
                record_origin(
                    self.dock_state,
                    space.docks,
                    space.origins,
                    path,
                    &mut |tab| tab_viewer.id(tab),
                );
            }
        } else {
            for path in paths {
                if let Ok(leaf) = self.dock_state.leaf_mut(path.node_path())
                    && let Some(tab) = leaf.tabs.get_mut(path.tab.0)
                {
                    let id = tab_viewer.id(tab);
                    space.origins.retain(|origin| origin.tab != id);
                }
            }
        }
    }

    /// Outlines the docks of this viewport that could take the space's drag of `src`, where
    /// window positions are hidden.
    /// A float is outlined as any dock is: joining it is not tearing off a new one, so the
    /// source's window rules do not apply (see [`may_join`](Self::may_join)).
    fn paint_outlines(&self, ui: &Ui, src: &TreeComponent, tab_viewer: &impl TabViewer<Tab = Tab>) {
        if !self.source_valid(src) {
            return;
        }
        let Some(space) = self.space.as_ref() else {
            return;
        };
        let viewport = ui.ctx().viewport_id();
        let style = self.style.as_ref().unwrap();
        let painter = make_overlay_painter(ui);
        for dock in space.docks.iter() {
            if dock.viewport != Some(viewport) || dock.surface == src.surface_address() {
                continue;
            }
            let Some(rect) = dock.rect else {
                continue;
            };
            let refused = !dock.rules.accept_drops
                || self.dock_target(&dock.name).is_none_or(|target| {
                    let destination = match target {
                        TreeComponent::Node(path) => TabDestination::Node(path, TabInsert::Append),
                        TreeComponent::Surface(surface) => TabDestination::EmptySurface(surface),
                        TreeComponent::Tab(path) => {
                            TabDestination::Node(path.node_path(), TabInsert::Append)
                        }
                    };
                    self.refusal_of(src, tab_viewer, &destination, false)
                        .is_some()
                });
            self.painter.0.window_outline(
                &painter,
                &WindowOutlinePaint {
                    rect,
                    refused,
                    style,
                    visuals: ui.visuals(),
                },
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tab_viewer::{DockDrop, DropVerdict};
    use crate::{DockRules, DockSpace, NodeIndex, NodePath};
    use egui::WidgetText;

    /// Refuses windows to the tab `"restricted"` unless `allow_windows`, and, when `veto`, every
    /// drop into the dock named `vetoed`.
    struct Viewer {
        allow_windows: bool,
        vetoed: Option<String>,
    }

    impl Viewer {
        fn new(allow_windows: bool) -> Self {
            Self {
                allow_windows,
                vetoed: None,
            }
        }
    }

    impl TabViewer for Viewer {
        type Tab = &'static str;

        fn id(&mut self, tab: &mut Self::Tab) -> egui::Id {
            egui::Id::unique(*tab)
        }

        fn title(&mut self, tab: &mut Self::Tab) -> WidgetText {
            (*tab).into()
        }

        fn ui(&mut self, _ui: &mut Ui, _tab: &mut Self::Tab) {}

        fn allowed_in_windows(&self, tab: &mut Self::Tab) -> bool {
            self.allow_windows || *tab != "restricted"
        }

        fn dock_drop_allowed(&self, _tab: &Self::Tab, drop: &DockDrop<'_>) -> DropVerdict {
            if drop.to.is_some() && drop.to == self.vetoed.as_deref() {
                DropVerdict::Refuse(None)
            } else {
                DropVerdict::Allow
            }
        }
    }

    /// A space with the dock `main` (holding `"restricted"` then `"allowed"`, with the rules
    /// `main_rules`) and a float made from the dock `other`, whose name and surface it returns.
    fn space_with_float(
        main_rules: DockRules,
    ) -> (DockSpace<&'static str>, String, crate::SurfaceIndex) {
        let mut space = DockSpace::new();
        space.add_dock("main", main_rules, vec!["restricted", "allowed"]);
        // The float is made without asking the viewer, as an app opening its own window does.
        space.add_dock("other", DockRules::default(), vec!["target"]);
        let other = space.dock_surface("other").unwrap();
        let key = space
            .float_out(
                TabPath::new(other, NodeIndex::root(), TabIndex(0)),
                Rect::from_min_size(Pos2::ZERO, egui::vec2(300.0, 200.0)),
                |tab| egui::Id::unique(*tab),
            )
            .unwrap();
        let target = space.dock_surface(&key).unwrap();
        (space, key, target)
    }

    /// Releases the first tab of `main`, or its whole leaf when `group`, at `destination`.
    fn release(
        space: &mut DockSpace<&'static str>,
        group: bool,
        destination: TabDestination,
        viewer: &mut Viewer,
    ) {
        let main = space.dock_surface("main").unwrap();
        let src = if group {
            TreeComponent::Node(NodePath::new(main, NodeIndex::root()))
        } else {
            TreeComponent::Tab(TabPath::new(main, NodeIndex::root(), TabIndex(0)))
        };
        let mut area = DockArea::dock(space, "main");
        area.release_over(
            Report {
                stamp: 0,
                rank: 0,
                outcome: Outcome::Drop(destination),
                unfold: None,
            },
            src,
            Rect::from_min_size(Pos2::ZERO, egui::vec2(300.0, 200.0)),
            viewer,
        );
    }

    fn float_tabs(
        space: &DockSpace<&'static str>,
        target: crate::SurfaceIndex,
    ) -> Vec<&'static str> {
        space.state()[NodePath::new(target, NodeIndex::root())]
            .tabs()
            .unwrap()
            .to_vec()
    }

    /// Joining a float that already exists is not tearing off a new one: neither the source
    /// dock's `windows` rule nor `allowed_in_windows` keeps the tab out of it.
    #[test]
    fn a_drop_into_an_existing_float_ignores_the_tear_off_rules() {
        for group in [false, true] {
            for main_windows in [false, true] {
                for allow_windows in [false, true] {
                    let (mut space, _, target) =
                        space_with_float(DockRules::default().windows(main_windows));
                    let mut viewer = Viewer::new(allow_windows);
                    {
                        let area = DockArea::dock(&mut space, "main");
                        assert!(area.is_float_dock(target));
                    }
                    release(
                        &mut space,
                        group,
                        TabDestination::Node(
                            NodePath::new(target, NodeIndex::root()),
                            TabInsert::Append,
                        ),
                        &mut viewer,
                    );
                    let tabs = float_tabs(&space, target);
                    assert!(tabs.contains(&"restricted"), "{group} {main_windows}");
                    assert_eq!(tabs.contains(&"allowed"), group);
                }
            }
        }
    }

    /// Tearing a tab or a group off into a new window still follows the source dock's
    /// `windows` rule and `allowed_in_windows`.
    #[test]
    fn tearing_off_a_new_window_still_follows_the_rules() {
        for group in [false, true] {
            for (main_windows, allow_windows, may) in [
                (false, false, false),
                (false, true, false),
                (true, false, false),
                (true, true, true),
            ] {
                let (mut space, _, _) =
                    space_with_float(DockRules::default().windows(main_windows));
                let mut viewer = Viewer::new(allow_windows);
                let rect = Rect::from_min_size(Pos2::new(10.0, 10.0), egui::vec2(200.0, 100.0));
                release(&mut space, group, TabDestination::Window(rect), &mut viewer);
                let main = space.dock_surface("main").unwrap();
                let left = space
                    .state()
                    .leaf(NodePath::new(main, NodeIndex::root()))
                    .map_or(true, |leaf| !leaf.tabs.contains(&"restricted"));
                assert_eq!(left, may, "{group} {main_windows} {allow_windows}");
            }
        }
    }

    /// The float joined decides: its own `accept_drops` rule, or the viewer's veto, still
    /// refuses the drop.
    #[test]
    fn the_target_float_or_the_veto_can_refuse_a_join() {
        for group in [false, true] {
            for by_rules in [false, true] {
                let (mut space, key, target) =
                    space_with_float(DockRules::default().windows(false));
                let mut viewer = Viewer::new(false);
                if by_rules {
                    assert!(space.set_rules(&key, DockRules::default().accept_drops(false)));
                } else {
                    viewer.vetoed = Some(key.clone());
                }
                release(
                    &mut space,
                    group,
                    TabDestination::Node(
                        NodePath::new(target, NodeIndex::root()),
                        TabInsert::Append,
                    ),
                    &mut viewer,
                );
                assert_eq!(
                    float_tabs(&space, target),
                    vec!["target"],
                    "{group} {by_rules}"
                );
            }
        }
    }
}