egui_stack 0.30.2

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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
use egui::{
    Context, CursorIcon, Event, EventFilter, Key, Pos2, Rect, Sense, StrokeKind, Ui, Vec2,
    WidgetInfo,
    accesskit::{Action, ActionData, Orientation, Role},
    pos2,
};

use super::{
    drag_and_drop::{DragData, DragDropState, HoverData, TreeComponent, make_overlay_painter},
    session::Outcome,
    state::State,
    tab_removal::TabRemoval,
};
use crate::NodePath;
use crate::dock_area::tab_removal::ForcedRemoval;
use crate::dock_space::{NoDrop, RestoreDrop, StripDrop, dock_name, remove_empty_docks};
use crate::dock_state::tree::node::shares;
use crate::layout::{Dir, ZoneName};
use crate::tab_viewer::{DockDrop, DropVerdict, OnCloseResponse};
use crate::{
    AllowedSplits, DockArea, DockPainter, DockRules, LinearDir, Node, NodeIndex, OverlayType,
    PartState, RestoreBandPaint, SeparatorAxis, SeparatorPaint, Style, SurfaceIndex,
    TabDestination, TabPath, TabViewer,
    utils::{expand_to_pixel, fade_dock_style, map_to_pixel},
};
use across::Across;

mod across;
mod float_out;
mod ghost;
mod leaf;
mod main_surface;
mod window_surface;

/// How far, in points, the arrow keys and assistive technology move a separator per step.
const SEPARATOR_KEY_STEP: f32 = 16.0;

/// How far, in points, the arrow keys move a separator per step with Shift held.
const SEPARATOR_LARGE_KEY_STEP: f32 = 64.0;

impl<Tab> DockArea<'_, Tab> {
    /// Shows the docking hierarchy inside a [`Ui`].
    pub fn show_inside(mut self, ui: &mut Ui, tab_viewer: &mut impl TabViewer<Tab = Tab>) {
        self.style
            .get_or_insert(Style::from_egui(ui.style().as_ref()));
        self.window_bounds.get_or_insert(ui.ctx().content_rect());

        let mut state = State::load(ui.ctx(), self.id);
        // The docks of a space share one state: the first of them shown in a pass resolves the
        // drag for all of them, the others only draw.
        let pass = ui.ctx().cumulative_pass_nr();
        let first_in_pass = state.pass != Some(pass);
        state.pass = Some(pass);
        if first_in_pass {
            state.tab_bars.clear();
        }

        let dock_rect = ui.available_rect_before_wrap();
        if let Some(space) = &mut self.space
            && let Some(dock) = space.dock
        {
            space.docks[dock].rect = Some(dock_rect);
            space.docks[dock].viewport = Some(ui.ctx().viewport_id());
        }
        if let Some(space) = &mut self.space {
            space.viewport = Some(ui.ctx().viewport_id());
        }

        if first_in_pass {
            self.resolve_drag(ui, &mut state, tab_viewer, dock_rect);
        }

        let style = self.style.as_ref().unwrap();
        let fade_surface =
            self.hovered_window_surface(&mut state, style.overlay.feel.fade_hold_time, ui.ctx());
        let fade_style = {
            fade_surface.is_some().then(|| {
                let mut fade_style = style.clone();
                fade_dock_style(&mut fade_style, style.overlay.surface_fade_opacity);
                (fade_style, style.overlay.surface_fade_opacity)
            })
        };

        for surface_index in self.surfaces_to_show() {
            self.show_surface_inside(
                surface_index,
                ui,
                tab_viewer,
                &mut state,
                fade_style.as_ref().map(|(style, factor)| {
                    (style, *factor, fade_surface.unwrap_or(SurfaceIndex::main()))
                }),
            );
        }

        for removal in self.to_remove.drain(..).rev() {
            match removal {
                TabRemoval::Tab(path, ForcedRemoval(is_forced)) => {
                    if is_forced {
                        self.dock_state.remove_tab(path);
                    } else {
                        let leaf = &mut self.dock_state.leaf_mut(path.node_path()).unwrap();
                        match tab_viewer.on_close(&mut leaf.tabs[path.tab.0]) {
                            OnCloseResponse::Close => {
                                self.dock_state.remove_tab(path);
                            }
                            OnCloseResponse::Focus => {
                                leaf.active = path.tab;
                                self.new_focused = Some(path.node_path());
                            }
                            OnCloseResponse::Ignore => {
                                // no-op
                            }
                        }
                    }
                }
                TabRemoval::Node(path) => {
                    let mut all_tabs_are_closable = true;
                    for tab in self.dock_state[path].iter_tabs_mut() {
                        if !(tab_viewer.is_closeable(tab)
                            && matches!(tab_viewer.on_close(tab), OnCloseResponse::Close))
                        {
                            all_tabs_are_closable = false;
                        }
                    }
                    if all_tabs_are_closable {
                        self.dock_state.remove_leaf(path);
                    }
                }
                TabRemoval::Window(surface) => {
                    let mut all_tabs_are_closable = true;
                    for node in self.dock_state[surface].iter_mut() {
                        for tab in node.iter_tabs_mut() {
                            if !(tab_viewer.is_closeable(tab)
                                && matches!(tab_viewer.on_close(tab), OnCloseResponse::Close))
                            {
                                all_tabs_are_closable = false;
                            }
                        }
                    }
                    if all_tabs_are_closable {
                        self.dock_state.remove_surface(surface);
                    }
                }
            }
        }

        for path in std::mem::take(&mut self.to_detach).into_iter().rev() {
            let mouse_pos = state.last_hover_pos.unwrap_or(Pos2::ZERO);
            if self.floats_on() {
                let size = self.dock_state[path.node_path()]
                    .rect()
                    .map_or(Vec2::new(100., 150.), |rect| rect.size());
                self.to_float.push((
                    TreeComponent::Tab(path),
                    Rect::from_min_size(mouse_pos, size),
                    None,
                ));
            } else {
                self.dock_state.eject_tab(path, mouse_pos);
            }
        }

        for (path, destination) in std::mem::take(&mut self.to_move_group) {
            match destination {
                TabDestination::Window(rect) if self.floats_on() => {
                    self.to_float.push((TreeComponent::Node(path), rect, None));
                }
                destination => self.dock_state.move_node(path, destination),
            }
        }

        for (source, rect, host) in std::mem::take(&mut self.to_float) {
            self.float_out(ui.ctx(), source, rect, host, tab_viewer);
        }

        if let Some(focused) = self.new_focused {
            self.dock_state.set_focused_node_and_surface(focused);
        }

        if let Some(space) = &mut self.space {
            remove_empty_docks(self.dock_state, space.docks);
        }

        state.store(ui.ctx(), self.id);
    }

    /// Reads what the leaves recorded during the last pass: the dragged tab and what it hovers.
    /// Paints the drop preview and, when the tab is released, moves it. In a space, the drag
    /// is the space's across viewports ([`across`](Self::across)).
    fn resolve_drag(
        &mut self,
        ui: &Ui,
        state: &mut State,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
        dock_rect: Rect,
    ) {
        state.dragged = None;
        state.tab_in_air = None;
        state.dragged_node = None;

        if self.drag_lost(ui, state) {
            // Ends as on Escape: nothing dropped, the ghost gone.
            ui.memory_mut(|mem| {
                mem.data
                    .remove_temp::<Option<DragData>>(self.id.with("drag_data"));
                mem.data
                    .remove_temp::<Option<HoverData>>(self.id.with("hover_data"));
            });
            let viewport = ui.ctx().viewport_id();
            if let Some(space) = self.space.as_mut()
                && space
                    .floating
                    .session
                    .as_ref()
                    .is_some_and(|session| session.source == viewport && session.released.is_none())
            {
                space.floating.session = None;
            }
            state.reset_drag();
            self.forget_no_drop();
            self.forget_verdicts();
            ui.ctx().request_repaint();
            return;
        }

        // Where the pointer is now. On a release, where it was released: a mouse moved and
        // released in one frame drops there, not where it was the frame before. On touch screens
        // hover_pos() is None once released, so the release position comes from interact_pos(),
        // or, without it, the last known position is kept.
        state.last_hover_pos = ui.input(|i| {
            if i.pointer.any_released() {
                i.pointer
                    .interact_pos()
                    .or(i.pointer.hover_pos())
                    .or(state.last_hover_pos)
            } else {
                i.pointer.hover_pos()
            }
        });

        let (mut drag_data, hover_data) = ui.memory_mut(|mem| {
            (
                mem.data.remove_temp(self.id.with("drag_data")).flatten(),
                mem.data.remove_temp(self.id.with("hover_data")).flatten(),
            )
        });

        // The tab whose drag began here: its ghost follows the pointer, even over another
        // viewport, so it stays out of its bar.
        let in_air = match &drag_data {
            Some(DragData {
                src: TreeComponent::Tab(path),
                ..
            }) => Some(*path),
            _ => None,
        };

        // The space's one drag across viewports: begun here, begun in another viewport and
        // shown here, or already settled.
        let (remote, take) = match self.across(ui, state, &mut drag_data, tab_viewer) {
            Across::Here => (false, false),
            Across::Remote { take } => (true, take),
            Across::Covered => {
                drag_data = None;
                (false, false)
            }
            Across::Done => {
                self.forget_no_drop();
                return;
            }
        };
        let hover_data = if drag_data.is_some() {
            hover_data
        } else {
            None
        };
        let released = !remote && ui.input(|i| i.pointer.primary_released());
        // A dragged tab, or a whole group, shows its ghost under the pointer, in the viewport
        // the pointer is over: the source's, or another's of the space.
        let ghost = match &drag_data {
            Some(DragData {
                src: TreeComponent::Node(path),
                ..
            }) => Some((*path, None)),
            Some(DragData {
                src: TreeComponent::Tab(path),
                ..
            }) => Some((path.node_path(), Some(path.tab))),
            _ => None,
        };
        state.tab_in_air = if remote { None } else { in_air };
        if !released
            && !take
            && let Some((path, tab)) = ghost
            && let Some(pointer) = state.last_hover_pos
        {
            self.paint_ghost(ui, path, tab, pointer, tab_viewer);
        }

        // A collapsed zone's restore band wins over whatever lies under it, no-drop zones
        // included; then a folded zone's strip taking drops.
        let restores = self
            .space
            .as_ref()
            .filter(|space| !space.native)
            .map(|space| space.no_drop.restores.clone())
            .unwrap_or_default();
        let bands = restore_bands(
            &restores,
            self.style.as_ref().unwrap().overlay.feel.restore_band,
        );
        let restore = drag_data
            .as_ref()
            .and_then(|_| self.hover_restore(state, &restores, &bands));
        if drag_data.is_some() {
            self.paint_restore_bands(ui, &restores, &bands, restore.as_ref().map(|r| r.2));
        }
        let strip = drag_data
            .as_ref()
            .filter(|_| restore.is_none())
            .and_then(|_| self.hover_strip(state));
        let preview = restore.as_ref().map(|(_, _, i)| restores[*i].restore.rect);
        let drop_zone = match &restore {
            Some((_, zone, i)) => Some((restores[*i].dock.clone(), zone.clone())),
            None => strip
                .as_ref()
                .map(|(_, dock, zone)| (dock.clone(), zone.clone())),
        };
        let unfold = drop_zone.as_ref().map(|(_, zone)| zone.clone());
        if let Some(space) = &mut self.space {
            space.drop_zone = drop_zone;
        }
        let hover_data = restore
            .map(|(hover, _, _)| hover)
            .or_else(|| strip.map(|(hover, _, _)| hover))
            .or(hover_data)
            // Shown for another viewport's drag, this one has no "outside": the drag's own
            // viewport decides what a release over nothing does.
            .or_else(|| (!remote).then(|| self.hover_outside(dock_rect, state, &drag_data))?);
        // Where no tab may land, the drag hovers nothing: released, the tab stays where it was.
        let refused = preview.is_none()
            && hover_data
                .as_ref()
                .is_some_and(|hover| self.refuses_drop(ui.ctx(), state, hover));
        let hover_data = if refused {
            state.dnd = None;
            None
        } else {
            hover_data
        };
        self.forget_no_drop();

        let mut outcome = refused.then_some(Outcome::Refused);
        if let (Some(source), Some(hover)) = (drag_data, hover_data) {
            let style = self.style.as_ref().unwrap();
            let tab_dst = if let Some(preview) = preview {
                // The band is the target, whatever the leaf preference kept.
                state.dnd = Some(DragDropState {
                    hover,
                    drag: source,
                    pointer: state.last_hover_pos.unwrap_or(Pos2::ZERO),
                    locked: None,
                    src_in_window: false,
                    dst_in_window: false,
                });
                self.show_restore_overlay(ui, state, tab_viewer, preview)
            } else {
                state.set_drag_and_drop(source, hover, ui.ctx(), style);
                // The hover comes from the last pass, or is the preferred leaf's kept a while:
                // the part of the leaf under the pointer, tab bar or body, is tested again now.
                if let (Some(dnd), Some(pointer)) = (state.dnd.as_mut(), state.last_hover_pos) {
                    dnd.hover.retarget(pointer);
                }
                self.show_drag_drop_overlay(ui, state, tab_viewer)
            };
            if remote {
                outcome = Some(tab_dst.map_or(Outcome::Refused, Outcome::Drop));
            } else if released && let Some(destination) = tab_dst {
                // Dropped on a folded zone's strip, or a collapsed zone's restore band: the zone
                // is to unfold.
                if let (Some(zone), Some(space)) = (unfold.clone(), &mut self.space) {
                    space.no_drop.unfolds.push(zone);
                }
                let source = state.dnd.as_ref().unwrap().drag.src.clone();
                match destination {
                    // Out of every dock, once the space's floats are drawn: a float.
                    TabDestination::Window(rect) if self.floats_on() => {
                        let host = self.release_host(rect.min);
                        self.to_float.push((source, rect, host));
                    }
                    destination => {
                        self.apply_move(source, destination, tab_viewer);
                    }
                }
                ui.ctx().request_repaint();
            }
        }
        if remote {
            self.report(
                ui,
                state,
                outcome.unwrap_or(Outcome::Free),
                unfold,
                take,
                tab_viewer,
            );
        }

        if released {
            state.reset_drag();
            #[cfg(feature = "bus")]
            if let Some(bus) = self.space.as_ref().and_then(|space| space.bus) {
                bus.forget_verdicts();
            }
        }
    }

    /// Whether the drag begun in this area lost its release, which it then cancels: the window
    /// lost the focus, or the button was pressed again while egui still believed it held. On
    /// Wayland, a screenshot taken during a drag grabs the pointer, and the button is let go
    /// while the compositor holds it: the window never sees that release. egui keeps the
    /// button down until a release comes, and takes the drag up again at each pass meanwhile;
    /// it stays stopped until the button is let go.
    ///
    /// The pointer leaving the window is no sign: a drag goes on past the window's edges, to
    /// another viewport of the space or to a new float.
    fn drag_lost(&self, ui: &Ui, state: &mut State) -> bool {
        let ctx = ui.ctx();
        if let Some(id) = state.drag_lost {
            if ctx.input(|i| i.pointer.any_down()) {
                if ctx.dragged_id() == Some(id) {
                    ctx.stop_dragging();
                }
                return false;
            }
            state.drag_lost = None;
        }
        let Some(dragged) = ctx.dragged_id() else {
            return false;
        };
        if state.drag_start.is_none() || state.remote {
            return false;
        }
        let lost = ctx.input(|i| {
            i.pointer.any_pressed()
                || i.events
                    .iter()
                    .any(|event| matches!(event, Event::WindowFocused(false)))
        });
        if lost {
            state.drag_lost = Some(dragged);
            ctx.stop_dragging();
        }
        lost
    }

    /// Forgets the space's no-drop zones, strips and bands of this frame, once read (the main
    /// window's areas only: they are the main window's).
    fn forget_no_drop(&mut self) {
        if let Some(space) = &mut self.space
            && !space.native
        {
            let unfolds = std::mem::take(&mut space.no_drop.unfolds);
            *space.no_drop = NoDrop {
                unfolds,
                ..NoDrop::default()
            };
        }
    }

    /// The surfaces this area draws: every surface of its [`DockState`], or its dock of a space,
    /// with the floating windows if it is the space's windows dock.
    fn surfaces_to_show(&self) -> Vec<SurfaceIndex> {
        match &self.space {
            None => self.dock_state.valid_surface_indices().to_vec(),
            Some(space) => {
                let dock = space.dock.map(|dock| space.docks[dock].surface);
                let windows = self
                    .dock_state
                    .valid_surface_indices()
                    .into_iter()
                    .filter(|&surface| space.shows_windows && self.dock_state.is_window(surface));
                dock.into_iter().chain(windows).collect()
            }
        }
    }

    /// The rules of the space's dock at `surface`, if it is one.
    fn dock_rules(&self, surface: SurfaceIndex) -> Option<DockRules> {
        let space = self.space.as_ref()?;
        space
            .docks
            .iter()
            .find(|dock| dock.surface == surface)
            .map(|dock| dock.rules)
    }

    /// Whether a drag hovering `hover` may not land there: the pointer is in one of the space's
    /// no-drop zones, unless over a floating window, or the dock under it refuses drops.
    fn refuses_drop(&self, ctx: &Context, state: &State, hover: &HoverData) -> bool {
        let Some(space) = &self.space else {
            return false;
        };
        let surface = hover.dst.surface_address();
        if !hover.outside && self.dock_state.is_window(surface) {
            return false;
        }
        if !hover.outside && self.dock_rules(surface).is_some_and(|r| !r.accept_drops) {
            return true;
        }
        // The space's zones are the main window's; a float over them takes the tab.
        if space.native || (!hover.outside && self.is_float_dock(surface)) {
            return false;
        }
        let Some(pointer) = state.last_hover_pos else {
            return false;
        };
        // Released outside every dock and outside the floats' work area: refused, unless torn
        // out to a native window (`Outside::Native`).
        if hover.outside && space.floating.release_host(space.docks, pointer).is_none() {
            return true;
        }
        let widgets = space
            .no_drop
            .ids
            .iter()
            .filter_map(|&id| ctx.read_response(id).map(|r| r.rect));
        space
            .no_drop
            .rects
            .iter()
            .copied()
            .chain(widgets)
            .any(|rect| rect.contains(pointer))
    }

    /// The name of the space's dock at `surface`, if it is one.
    fn dock_name(&self, surface: SurfaceIndex) -> Option<&str> {
        dock_name(self.space.as_ref()?.docks, surface)
    }

    /// The zone a tab entering the dock `dock` is dropped in: the folded or collapsed zone
    /// whose strip or restore band the drag hovers for that dock, else the zone holding the
    /// dock as [`DockSpace::bind`](crate::DockSpace::bind) last read it; none for no dock.
    #[cfg(feature = "bus")]
    pub(super) fn drop_zone_of(&self, dock: Option<&str>) -> Option<String> {
        let (dock, space) = (dock?, self.space.as_ref()?);
        match &space.drop_zone {
            Some((over, zone)) if over == dock => Some(zone.0.clone()),
            _ => space
                .docks
                .iter()
                .find(|d| d.name == dock)
                .and_then(|d| d.zone.as_ref())
                .map(|zone| zone.0.clone()),
        }
    }

    /// Whether the tab at `path` may become a floating window: the viewer allows it, and the
    /// dock it is in, if any, too.
    pub(super) fn may_float(
        &mut self,
        path: TabPath,
        tab_viewer: &impl TabViewer<Tab = Tab>,
    ) -> bool {
        let dock_allows = self
            .dock_rules(path.surface)
            .is_none_or(|rules| rules.windows);
        let Node::Leaf(leaf) = &mut self.dock_state[path.node_path()] else {
            unreachable!("tab drags can only come from leaf nodes")
        };
        dock_allows && tab_viewer.allowed_in_windows(&mut leaf.tabs[path.tab.0])
    }

    /// Whether the leaf at `path`, dragged whole, may become a floating window: each of its tabs
    /// may.
    pub(super) fn node_may_float(
        &mut self,
        path: NodePath,
        tab_viewer: &impl TabViewer<Tab = Tab>,
    ) -> bool {
        let count = self.dock_state[path].tabs_count();
        (0..count).all(|i| self.may_float((path, crate::TabIndex(i)).into(), tab_viewer))
    }

    /// Whether one of this dock's floating windows, not the one `ui` draws, is the topmost
    /// layer under `pointer`. What lies under it, a docked leaf or a window further down, is
    /// not what a dragged tab hovers, whatever the order the surfaces are drawn in.
    pub(super) fn covered_by_window(&self, ui: &Ui, pointer: Pos2) -> bool {
        let Some(top) = ui.ctx().layer_id_at(pointer) else {
            return false;
        };
        let over_a_float = self
            .space
            .as_ref()
            .is_some_and(|space| !space.native && space.floating.layers.contains(&top));
        top != ui.layer_id()
            && (over_a_float
                || self
                    .dock_state
                    .valid_surface_indices()
                    .iter()
                    .any(|&surface| {
                        self.dock_state.is_window(surface)
                            && window_surface::window_layer_id(surface) == top
                    }))
    }

    /// A strip of a folded zone that takes drops for one of the space's docks
    /// ([`DockSpace::bind`](crate::DockSpace::bind)), under the pointer and under no floating
    /// window: hovered as that dock's tab bar, so a tab released there joins the dock's focused
    /// leaf, else its first, or the dock itself when empty.
    fn hover_strip(&self, state: &State) -> Option<(HoverData, String, ZoneName)> {
        let space = self.space.as_ref()?;
        let pointer = state.last_hover_pos?;
        let StripDrop {
            rect: strip,
            dock: name,
            unfold,
        } = space
            .no_drop
            .strips
            .iter()
            .find(|strip| strip.rect.contains(pointer))?;
        let over_a_window = self
            .dock_state
            .valid_surface_indices()
            .iter()
            .filter_map(|&surface| self.dock_state.get_window_state(surface))
            .any(|window| window.rect().contains(pointer));
        if over_a_window {
            return None;
        }
        let dst = self.dock_target(name)?;
        Some((
            HoverData {
                rect: *strip,
                dst,
                // As a tab bar: the tab joins the leaf, with no split.
                tab: Some(*strip),
                tab_bar: None,
                outside: false,
            },
            name.clone(),
            unfold.clone(),
        ))
    }

    /// Where a tab joining the space's dock named `name` without a split goes: its focused leaf,
    /// else its first, or the dock itself when empty.
    fn dock_target(&self, name: &str) -> Option<TreeComponent> {
        let space = self.space.as_ref()?;
        let surface = space.docks.iter().find(|dock| dock.name == name)?.surface;
        let tree = self.dock_state.get_surface(surface)?.node_tree()?;
        let leaf = tree
            .focused_leaf()
            .filter(|&node| tree.iter().nth(node.0).is_some_and(Node::is_leaf))
            .or_else(|| tree.iter().position(Node::is_leaf).map(NodeIndex));
        Some(match leaf {
            Some(node) => TreeComponent::Node(NodePath::new(surface, node)),
            None => TreeComponent::Surface(surface),
        })
    }

    /// The restore band under the pointer and under no floating window, of a collapsed zone
    /// ([`DockSpace::bind`](crate::DockSpace::bind)): hovered as its dock's tab bar, so a tab
    /// released there joins the dock with no split. With the zone, and the band's index.
    fn hover_restore(
        &self,
        state: &State,
        restores: &[RestoreDrop],
        bands: &[Rect],
    ) -> Option<(HoverData, ZoneName, usize)> {
        let pointer = state.last_hover_pos?;
        let index = bands.iter().position(|band| band.contains(pointer))?;
        let over_a_window = self
            .dock_state
            .valid_surface_indices()
            .iter()
            .filter_map(|&surface| self.dock_state.get_window_state(surface))
            .any(|window| window.rect().contains(pointer));
        if over_a_window {
            return None;
        }
        let restore = &restores[index];
        let dst = self.dock_target(&restore.dock)?;
        let band = bands[index];
        Some((
            HoverData {
                rect: band,
                dst,
                tab: Some(band),
                tab_bar: None,
                outside: false,
            },
            restore.zone.clone(),
            index,
        ))
    }

    /// Paints every restore band while a tab is dragged, `hovered` the one under the pointer.
    fn paint_restore_bands(
        &self,
        ui: &Ui,
        restores: &[RestoreDrop],
        bands: &[Rect],
        hovered: Option<usize>,
    ) {
        if bands.is_empty() {
            return;
        }
        let style = self.style.as_ref().unwrap();
        let painter = make_overlay_painter(ui);
        for (i, (band, restore)) in bands.iter().zip(restores).enumerate() {
            self.painter.0.restore_band(
                &painter,
                &RestoreBandPaint {
                    rect: *band,
                    zone: &restore.zone,
                    hovered: hovered == Some(i),
                    style,
                },
            );
        }
    }

    /// Resolves a drag over a restore band: the tab joins the band's dock with no split, unless
    /// it is already alone in that leaf or the viewer vetoes it; the preview is `rect`, where the
    /// zone would come back.
    fn show_restore_overlay(
        &mut self,
        ui: &Ui,
        state: &mut State,
        tab_viewer: &impl TabViewer<Tab = Tab>,
        rect: Rect,
    ) -> Option<TabDestination> {
        let drag_state = state.dnd.as_mut().unwrap();
        let (src_surface, src_node) = drag_state.drag.src.node_address();
        drag_state.src_in_window = self.dock_state.is_window(src_surface);
        let destination = drag_state.hover.dst.as_tab_destination();
        if (src_surface, src_node) == drag_state.hover.dst.node_address() {
            return None;
        }
        let released = ui.input(|i| i.pointer.primary_released());
        let refusal = self.drop_refusal(state, tab_viewer, &destination, released);
        let allowed = refusal.is_none();
        let style = self.style.as_ref().unwrap();
        let painter: &dyn DockPainter = self.painter.0;
        state.dnd.as_ref().unwrap().paint_preview_in(
            ui,
            style,
            painter,
            rect,
            &destination,
            false,
            refusal,
        );
        allowed.then_some(destination)
    }

    /// The viewer's veto for the dragged tab at `destination`; for a whole leaf, for each of its
    /// tabs, the first refusal said. `None` when allowed.
    fn drop_refusal(
        &self,
        state: &State,
        tab_viewer: &impl TabViewer<Tab = Tab>,
        destination: &TabDestination,
        fresh: bool,
    ) -> Option<Option<egui::WidgetText>> {
        let drag_state = state.dnd.as_ref()?;
        self.refusal_of(&drag_state.drag.src, tab_viewer, destination, fresh)
    }

    /// The veto for `src`, a tab or a whole leaf, at `destination`; see
    /// [`drop_refusal`](Self::drop_refusal).
    pub(super) fn refusal_of(
        &self,
        src: &TreeComponent,
        tab_viewer: &impl TabViewer<Tab = Tab>,
        destination: &TabDestination,
        fresh: bool,
    ) -> Option<Option<egui::WidgetText>> {
        let (src, tabs, group) = match *src {
            TreeComponent::Tab(path) => (path.node_path(), path.tab.0..path.tab.0 + 1, false),
            TreeComponent::Node(path) => (path, 0..self.dock_state[path].tabs_count(), true),
            TreeComponent::Surface(_) => unreachable!("surfaces can't be dragged (yet)"),
        };
        self.group_refusal_asked(src, tabs, group, destination, tab_viewer, fresh)
    }

    /// The viewer's veto for the tabs `tabs` of the leaf at `src` going to `destination`: the
    /// first refusal said, `None` when allowed.
    pub(super) fn group_refusal(
        &self,
        src: NodePath,
        tabs: std::ops::Range<usize>,
        destination: &TabDestination,
        tab_viewer: &impl TabViewer<Tab = Tab>,
        fresh: bool,
    ) -> Option<Option<egui::WidgetText>> {
        let group = tabs.start == 0 && tabs.end == self.dock_state[src].tabs_count();
        self.group_refusal_asked(src, tabs, group, destination, tab_viewer, fresh)
    }

    /// The veto for the tabs `tabs` of the leaf at `src` (the whole leaf when `group`) going to
    /// `destination`: the space's bus, when it has one (asked again only when `fresh` or for a
    /// destination not asked since the last release), else the viewer's.
    fn group_refusal_asked(
        &self,
        src: NodePath,
        tabs: std::ops::Range<usize>,
        group: bool,
        destination: &TabDestination,
        tab_viewer: &impl TabViewer<Tab = Tab>,
        fresh: bool,
    ) -> Option<Option<egui::WidgetText>> {
        let to = match *destination {
            TabDestination::Node(path, _) => self.dock_name(path.surface),
            TabDestination::EmptySurface(surface) => self.dock_name(surface),
            TabDestination::Window(_) => None,
        };
        #[cfg(feature = "bus")]
        if let Some(bus) = self.space.as_ref().and_then(|space| space.bus) {
            use crate::bus::{DropAsk, DropTarget};
            let target = match *destination {
                TabDestination::Window(_) => DropTarget::NewWindow,
                TabDestination::EmptySurface(_) => DropTarget::EmptyDock,
                TabDestination::Node(_, crate::TabInsert::Append) => DropTarget::Append,
                TabDestination::Node(_, crate::TabInsert::Insert(index)) => {
                    DropTarget::Insert(index.0)
                }
                TabDestination::Node(_, crate::TabInsert::Split(split)) => DropTarget::Split(split),
            };
            let to_surface = match *destination {
                TabDestination::Node(path, _) => Some(path.surface),
                TabDestination::EmptySurface(surface) => Some(surface),
                TabDestination::Window(_) => None,
            };
            let leaf_tabs = self.dock_state[src]
                .tabs()
                .expect("drags can only come from leaf nodes");
            let ask = DropAsk {
                tabs: leaf_tabs[tabs].iter().map(bus.key).collect(),
                group,
                from: self.dock_name(src.surface).map(str::to_owned),
                to: to.map(str::to_owned),
                from_float: self.is_float_dock(src.surface),
                to_float: to_surface.is_some_and(|surface| self.is_float_dock(surface)),
                target,
                zone: self.drop_zone_of(to),
            };
            return bus
                .drop_refusal(ask, fresh)
                .map(|reason| (!reason.is_empty()).then(|| reason.into()));
        }
        let _ = (group, fresh);
        let drop = DockDrop {
            destination,
            from: self.dock_name(src.surface),
            to,
        };
        let leaf_tabs = self.dock_state[src]
            .tabs()
            .expect("drags can only come from leaf nodes");
        leaf_tabs[tabs]
            .iter()
            .find_map(|tab| match tab_viewer.dock_drop_allowed(tab, &drop) {
                DropVerdict::Allow => None,
                DropVerdict::Refuse(reason) => Some(reason),
            })
    }

    /// With [`OverlayType::Zones`], a tab dragged outside the dock, where none of its surfaces
    /// is under the pointer, hovers "outside": dropped there, it opens in a new window.
    fn hover_outside(
        &self,
        dock_rect: Rect,
        state: &State,
        drag_data: &Option<DragData>,
    ) -> Option<HoverData> {
        if drag_data.is_none()
            || self.style.as_ref().unwrap().overlay.overlay_type != OverlayType::Zones
        {
            return None;
        }
        let pointer = state.last_hover_pos?;
        let viewport = self.space.as_ref().and_then(|space| space.viewport);
        let in_a_dock = match &self.space {
            None => dock_rect.contains(pointer),
            Some(space) => space
                .docks
                .iter()
                .filter(|dock| dock.viewport.is_none_or(|v| Some(v) == viewport))
                .filter_map(|dock| dock.rect)
                .any(|rect| rect.contains(pointer)),
        };
        let over_a_float = self.space.as_ref().is_some_and(|space| {
            !space.native
                && space
                    .floating
                    .rects
                    .iter()
                    .any(|rect| rect.contains(pointer))
        });
        let over_a_window = over_a_float
            || self
                .dock_state
                .valid_surface_indices()
                .iter()
                .filter_map(|&surface| self.dock_state.get_window_state(surface))
                .any(|window| window.rect().contains(pointer));
        (!in_a_dock && !over_a_window).then_some(HoverData {
            rect: Rect::NOTHING,
            dst: TreeComponent::Surface(SurfaceIndex::main()),
            tab: None,
            tab_bar: None,
            outside: true,
        })
    }

    /// Returns some when windows are fading, and what surface index is being hovered over
    #[inline(always)]
    fn hovered_window_surface(
        &self,
        state: &mut State,
        hold_time: f32,
        ctx: &Context,
    ) -> Option<SurfaceIndex> {
        if let Some(dnd_state) = &state.dnd
            && dnd_state.is_locked(self.style.as_ref().unwrap(), ctx)
        {
            state.window_fade =
                Some((ctx.input(|i| i.time), dnd_state.hover.dst.surface_address()));
        }

        state.window_fade.and_then(|(time, surface)| {
            ctx.request_repaint();
            (hold_time > (ctx.input(|i| i.time) - time) as f32).then_some(surface)
        })
    }

    /// Resolve where a dragged tab would land given it's dropped this frame, returns `None` when the resulting drop is an invalid move.
    fn show_drag_drop_overlay(
        &mut self,
        ui: &Ui,
        state: &mut State,
        tab_viewer: &impl TabViewer<Tab = Tab>,
    ) -> Option<TabDestination> {
        let drag_state = state.dnd.as_mut().unwrap();

        let deserted_node = {
            match (
                drag_state.drag.src.node_address(),
                drag_state.hover.dst.node_address(),
            ) {
                ((src_surf, Some(src_node)), (dst_surf, Some(dst_node))) => {
                    src_surf == dst_surf
                        && src_node == dst_node
                        && self.dock_state[src_surf][src_node].tabs_count() == 1
                }
                _ => false,
            }
        };

        // Not all scenarios can house all splits.
        let restricted_splits = if drag_state.hover.dst.is_surface() || deserted_node {
            AllowedSplits::None
        } else {
            AllowedSplits::All
        };
        let (src_surface, dst_surface) = (
            drag_state.drag.src.surface_address(),
            drag_state.hover.dst.surface_address(),
        );
        // The dock under the pointer may refuse splits.
        let dock_splits = if drag_state.hover.outside {
            AllowedSplits::All
        } else {
            self.dock_rules(dst_surface)
                .map_or(AllowedSplits::All, |rules| rules.splits)
        };
        let allowed_splits = self.allowed_splits & restricted_splits & dock_splits;

        // A whole leaf dragged onto itself goes nowhere.
        if let TreeComponent::Node(src) = drag_state.drag.src
            && !drag_state.hover.outside
            && drag_state.hover.dst.node_address() == (src.surface, Some(src.node))
        {
            return None;
        }
        let allowed_in_window = match drag_state.drag.src {
            TreeComponent::Tab(path) => self.may_float(path, tab_viewer),
            TreeComponent::Node(path) => self.node_may_float(path, tab_viewer),
            TreeComponent::Surface(_) => unreachable!("surfaces can't be dragged (yet)"),
        };
        let drag_state = state.dnd.as_mut().unwrap();
        drag_state.src_in_window = self.dock_state.is_window(src_surface);
        drag_state.dst_in_window =
            !drag_state.hover.outside && self.dock_state.is_window(dst_surface);
        let style = self.style.as_ref().unwrap();

        if let Some(pointer) = state.last_hover_pos {
            drag_state.pointer = pointer;
        }

        let window_bounds = self.window_bounds.unwrap();
        let painter: &dyn DockPainter = self.painter.0;
        let (destination, from_buttons) =
            match (style.overlay.overlay_type, drag_state.is_on_title_bar()) {
                (OverlayType::HighlightedAreas, _) | (_, true) => (
                    drag_state.resolve_traditional(
                        ui,
                        style,
                        painter,
                        allowed_splits,
                        allowed_in_window,
                    ),
                    false,
                ),
                (OverlayType::Widgets, false) => (
                    drag_state.resolve_icon_based(
                        ui,
                        style,
                        painter,
                        allowed_splits,
                        allowed_in_window,
                    ),
                    true,
                ),
                (OverlayType::Zones, false) => (
                    drag_state.resolve_zones(ui, style, painter, allowed_splits, allowed_in_window),
                    false,
                ),
            };
        let destination = destination?;
        let from_buttons = from_buttons && !matches!(destination, TabDestination::Window(_));

        // Last, the viewer's veto for this tab at this destination; asked afresh at release.
        let released = ui.input(|i| i.pointer.primary_released());
        let refusal = self.drop_refusal(state, tab_viewer, &destination, released);
        let allowed = refusal.is_none();
        let drag_state = state.dnd.as_ref().unwrap();
        drag_state.paint_preview(
            ui,
            style,
            painter,
            &destination,
            from_buttons,
            refusal,
            window_bounds,
        );
        allowed.then_some(destination)
    }

    /// Show a single surface of a [`DockState`].
    fn show_surface_inside(
        &mut self,
        surf_index: SurfaceIndex,
        ui: &mut Ui,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
        state: &mut State,
        fade_style: Option<(&Style, f32, SurfaceIndex)>,
    ) {
        if !self.dock_state.is_window(surf_index) {
            self.show_root_surface_inside(ui, tab_viewer, state, surf_index);
        } else {
            self.show_window_surface(ui, surf_index, tab_viewer, state, fade_style);
        }
    }

    fn render_nodes(
        &mut self,
        ui: &mut Ui,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
        state: &mut State,
        surf_index: SurfaceIndex,
        fade_style: Option<(&Style, f32)>,
    ) {
        // First compute all rect sizes in the node graph, parents before their children.
        let max_rect = self.allocate_area_for_root_node(ui, surf_index);
        for node_index in self.dock_state[surf_index].breadth_first_index_iter() {
            let path = NodePath {
                surface: surf_index,
                node: node_index,
            };
            if self.dock_state[path].is_parent() {
                self.compute_rect_sizes(ui, path, max_rect);
            }
        }

        // Then, draw the bodies of each leaves.
        for node_index in self.dock_state[surf_index].breadth_first_index_iter() {
            let path = NodePath {
                surface: surf_index,
                node: node_index,
            };
            if self.dock_state[path].is_leaf() {
                self.show_leaf(ui, state, path, tab_viewer, fade_style);
            }
        }

        // Finally, draw separators so that their "interaction zone" is above
        // bodies (see `SeparatorStyle::extra_interact_width`).
        let fade_style = fade_style.map(|(style, _)| style);
        for node_index in self.dock_state[surf_index].breadth_first_index_iter() {
            let path = NodePath {
                surface: surf_index,
                node: node_index,
            };
            for separator in separators(&self.dock_state[path]) {
                let name = self.separator_name(path, separator, tab_viewer);
                self.show_separator(ui, path, separator, &name, fade_style);
            }
        }
    }

    fn allocate_area_for_root_node(&mut self, ui: &mut Ui, surface: SurfaceIndex) -> Rect {
        let style = self.style.as_ref().unwrap();
        let mut rect = ui.available_rect_before_wrap();

        if let Some(margin) = style.dock_area_padding {
            rect.min += margin.left_top();
            rect.max -= margin.right_bottom();
        }

        ui.painter().rect_stroke(
            rect,
            style.main_surface_border_rounding,
            style.main_surface_border_stroke,
            StrokeKind::Inside,
        );
        if !self.dock_state.is_window(surface) {
            rect = rect.expand(-style.main_surface_border_stroke.width / 2.0);
        }
        ui.allocate_rect(rect, Sense::hover());

        if self.dock_state[surface].is_empty() {
            return rect;
        }
        self.dock_state[surface][NodeIndex::root()].set_rect(rect);
        rect
    }

    fn compute_rect_sizes(&mut self, ui: &Ui, path: NodePath, max_rect: Rect) {
        let style = self.style.as_ref().unwrap();
        let pixels_per_point = ui.ctx().pixels_per_point();
        let tree = &self.dock_state[path.surface];
        let linear = match &tree[path.node] {
            Node::Linear(linear) => linear,
            Node::Grid(_) => return self.compute_grid_rect_sizes(ui, path, max_rect),
            _ => unreachable!("only containers have children"),
        };
        let rect = linear.rect;
        debug_assert!(!rect.any_nan() && rect.is_finite());
        let rect = expand_to_pixel(rect, pixels_per_point);

        // Collapsed children of a column keep the height of their tab bars.
        let collapsed: Vec<Option<i32>> = linear
            .children()
            .iter()
            .map(|&child| {
                (linear.dir == LinearDir::Vertical && tree[child].is_collapsed())
                    .then(|| tree[child].collapsed_leaf_count())
            })
            .collect();
        let axis = linear.dir;
        let (start, size) = match axis {
            LinearDir::Horizontal => (rect.min.x, rect.width()),
            LinearDir::Vertical => (rect.min.y, rect.height()),
        };
        let boundaries = boundaries(linear, &collapsed, size, style.tab_bar.height);
        let children = linear.children().to_vec();

        let half = style.separator.width * 0.5;
        let last = children.len() - 1;
        for (index, child) in children.into_iter().enumerate() {
            let mut child_rect = rect;
            let (min, max) = match axis {
                LinearDir::Horizontal => (&mut child_rect.min.x, &mut child_rect.max.x),
                LinearDir::Vertical => (&mut child_rect.min.y, &mut child_rect.max.y),
            };
            if index > 0 {
                *min = map_to_pixel(
                    start + boundaries[index - 1] + half,
                    pixels_per_point,
                    f32::round,
                );
            }
            if index < last {
                *max = map_to_pixel(
                    start + boundaries[index] - half,
                    pixels_per_point,
                    f32::round,
                );
            }
            let child_rect = rect.intersect(child_rect).intersect(max_rect);
            self.dock_state[path.surface][child].set_rect(child_rect);
        }
    }

    /// Lays out the children of the grid at `path` in its cells, row by row.
    fn compute_grid_rect_sizes(&mut self, ui: &Ui, path: NodePath, max_rect: Rect) {
        let style = self.style.as_ref().unwrap();
        let pixels_per_point = ui.ctx().pixels_per_point();
        let half = style.separator.width * 0.5;
        let Node::Grid(grid) = &mut self.dock_state[path.surface][path.node] else {
            unreachable!("a grid node")
        };
        grid.fit_shares();
        let grid = grid.clone();
        debug_assert!(!grid.rect.any_nan() && grid.rect.is_finite());
        let rect = expand_to_pixel(grid.rect, pixels_per_point);

        // The span of the cell `index` of `count` along one axis, between its lines.
        let span = |shares: &[f32], index: usize, count: usize, start: f32, size: f32| {
            let min = if index > 0 {
                map_to_pixel(
                    start + size * shares::boundary(shares, index - 1) + half,
                    pixels_per_point,
                    f32::round,
                )
            } else {
                start
            };
            let max = if index + 1 < count {
                map_to_pixel(
                    start + size * shares::boundary(shares, index) - half,
                    pixels_per_point,
                    f32::round,
                )
            } else {
                start + size
            };
            (min, max)
        };
        let (columns, rows) = (grid.columns(), grid.rows());
        for (index, &child) in grid.children().iter().enumerate() {
            let (column, row) = grid.cell(index);
            let (min_x, max_x) = span(grid.col_shares(), column, columns, rect.min.x, rect.width());
            let (min_y, max_y) = span(grid.row_shares(), row, rows, rect.min.y, rect.height());
            let child_rect = Rect::from_min_max(pos2(min_x, min_y), pos2(max_x, max_y));
            let child_rect = rect.intersect(child_rect).intersect(max_rect);
            self.dock_state[path.surface][child].set_rect(child_rect);
        }
    }

    /// The accessible name of a separator of the container at `path`: "Resize between {first}
    /// and {second}", named after the active tab of the first leaf on each side, or "Resize"
    /// when a side has none (a grid's line, an empty leaf).
    fn separator_name(
        &mut self,
        path: NodePath,
        separator_of: SeparatorOf,
        tab_viewer: &mut impl TabViewer<Tab = Tab>,
    ) -> String {
        let surface = &mut self.dock_state[path.surface];
        let pair = match (&surface[path.node], separator_of) {
            (Node::Linear(linear), SeparatorOf::Linear(index)) => {
                Some([linear.children()[index], linear.children()[index + 1]])
            }
            _ => None,
        };
        let mut title = |side: NodeIndex| {
            let leaf = surface.first_leaf(side)?;
            let leaf = surface[leaf].get_leaf_mut()?;
            let active = leaf.active.0;
            let tab = leaf.tabs.get_mut(active)?;
            Some(tab_viewer.title(tab).text().to_owned())
        };
        match pair.map(|[first, second]| (title(first), title(second))) {
            Some((Some(first), Some(second))) => self
                .labels
                .separator_between
                .replace("{first}", &first)
                .replace("{second}", &second),
            _ => self.labels.separator.to_string(),
        }
    }

    /// Shows a separator of the container at `path`, named `label`.
    fn show_separator(
        &mut self,
        ui: &mut Ui,
        path: NodePath,
        separator_of: SeparatorOf,
        label: &str,
        fade_style: Option<&Style>,
    ) {
        let tree = &self.dock_state[path.surface];
        // If either of the children is collapsed, we don't want the user to interact with the separator
        if let (Node::Linear(linear), SeparatorOf::Linear(index)) = (&tree[path.node], separator_of)
        {
            let pair = [linear.children()[index], linear.children()[index + 1]];
            if linear.dir == LinearDir::Vertical && pair.iter().any(|&c| tree[c].is_collapsed()) {
                return;
            }
        }

        let style = fade_style.unwrap_or_else(|| self.style.as_ref().unwrap());
        let pixels_per_point = ui.ctx().pixels_per_point();
        let painter = self.painter.0;

        // The separator stands after the share `index`, moving it and the next one.
        let (horizontal, rect, shares, index) =
            match (&mut self.dock_state[path.surface][path.node], separator_of) {
                (Node::Linear(linear), SeparatorOf::Linear(index)) => (
                    linear.dir == LinearDir::Horizontal,
                    linear.rect,
                    &mut linear.shares,
                    index,
                ),
                (Node::Grid(grid), SeparatorOf::Column(index)) => {
                    (true, grid.rect, &mut grid.col_shares, index)
                }
                (Node::Grid(grid), SeparatorOf::Row(index)) => {
                    (false, grid.rect, &mut grid.row_shares, index)
                }
                _ => unreachable!("a separator of this container"),
            };
        let dim = |v: Vec2| if horizontal { v.x } else { v.y };
        let along = |r: Rect| {
            if horizontal {
                (r.min.x, r.max.x)
            } else {
                (r.min.y, r.max.y)
            }
        };
        let set_along = |r: &mut Rect, min: f32, max: f32| {
            if horizontal {
                (r.min.x, r.max.x) = (min, max);
            } else {
                (r.min.y, r.max.y) = (min, max);
            }
        };

        let (start, end) = along(rect);
        let range = end - start;
        let mut separator = rect;
        let midpoint = start + range * shares::boundary(shares, index);
        set_along(
            &mut separator,
            midpoint - style.separator.width * 0.5,
            midpoint + style.separator.width * 0.5,
        );

        let mut expand = Vec2::ZERO;
        if horizontal {
            expand.x += style.separator.extra_interact_width / 2.0;
        } else {
            expand.y += style.separator.extra_interact_width / 2.0;
        }
        let interact_rect = separator.expand2(expand);

        let cursor = if horizontal {
            CursorIcon::ResizeHorizontal
        } else {
            CursorIcon::ResizeVertical
        };
        let response = ui
            .allocate_rect(interact_rect, Sense::click_and_drag())
            .on_hover_and_drag_cursor(cursor);

        // A focused separator moves with the arrow keys along its axis, by a larger step
        // with Shift, and Enter resets it. The arrows across its axis still move the focus.
        if response.has_focus() {
            ui.memory_mut(|m| {
                m.set_focus_lock_filter(
                    response.id,
                    EventFilter {
                        horizontal_arrows: horizontal,
                        vertical_arrows: !horizontal,
                        tab: false,
                        escape: false,
                    },
                )
            });
        }

        let (back_key, forward_key) = if horizontal {
            (Key::ArrowLeft, Key::ArrowRight)
        } else {
            (Key::ArrowUp, Key::ArrowDown)
        };
        let (arrow_key_offset, reset) = if response.has_focus() {
            ui.input(|i| {
                let step = if i.modifiers.shift {
                    SEPARATOR_LARGE_KEY_STEP
                } else {
                    SEPARATOR_KEY_STEP
                };
                let offset = if i.key_pressed(back_key) {
                    Some(-step)
                } else if i.key_pressed(forward_key) {
                    Some(step)
                } else {
                    None
                };
                (offset, i.key_pressed(Key::Enter))
            })
        } else {
            (None, false)
        };

        set_along(
            &mut separator,
            map_to_pixel(
                midpoint - style.separator.width * 0.5,
                pixels_per_point,
                f32::round,
            ),
            map_to_pixel(
                midpoint + style.separator.width * 0.5,
                pixels_per_point,
                f32::round,
            ),
        );

        painter.separator(
            ui.painter(),
            &SeparatorPaint {
                rect: separator,
                axis: if horizontal {
                    SeparatorAxis::Vertical
                } else {
                    SeparatorAxis::Horizontal
                },
                state: PartState::NONE
                    .with(PartState::HOVERED, response.hovered())
                    .with(PartState::PRESSED, response.is_pointer_button_down_on())
                    .with(PartState::FOCUSED, response.has_focus())
                    .with(PartState::DRAGGED, response.dragged()),
                style,
            },
        );

        // Update the shares after drawing the separator, otherwise it may overlap on other
        // separators / bodies when shrunk fast.
        // Assistive technology moves the separator by the arrow keys' step.
        let accesskit_step = if range > 0.0 {
            (SEPARATOR_KEY_STEP / range).min(1.0)
        } else {
            0.0
        };
        let (accesskit_steps, accesskit_value) = ui.input(|i| {
            let steps = i.num_accesskit_action_requests(response.id, Action::Increment) as f32
                - i.num_accesskit_action_requests(response.id, Action::Decrement) as f32;
            let value = i
                .accesskit_action_requests(response.id, Action::SetValue)
                .filter_map(|request| match request.data {
                    Some(ActionData::NumericValue(value)) => Some(value as f32),
                    _ => None,
                })
                .last();
            (steps, value)
        });
        // Each child of the pair keeps at least `separator.extra` points.
        let min_part = if range > 0.0 {
            (style.separator.extra / range).min(1.0)
        } else {
            0.0
        };
        if range > 0.0 {
            let delta = arrow_key_offset.unwrap_or(dim(response.drag_delta()));
            let boundary = shares::boundary(shares, index);
            let target = accesskit_value.unwrap_or(boundary)
                + delta / range
                + accesskit_steps * accesskit_step;
            if target != boundary {
                shares::move_boundary(shares, index, target - boundary, min_part);
            }
        }

        if response.double_clicked() || reset {
            shares::even_pair(shares, index);
        }

        // Expose the separator as a splitter whose value is its position in the node, from 0
        // to 1: for two children, the split's fraction.
        let value = shares::boundary(shares, index);
        let pair_start = if index == 0 {
            0.0
        } else {
            shares::boundary(shares, index - 1)
        };
        let pair_end = shares::boundary(shares, index + 1);
        let (min, max) = if range > 0.0 {
            let min = pair_start + min_part;
            let max = pair_end - min_part;
            (min.min(max), max.max(min))
        } else {
            (value, value)
        };
        let enabled = ui.is_enabled();
        response.widget_info(|| {
            let mut info = WidgetInfo::labeled(Role::Splitter, enabled, label);
            info.value = Some(f64::from(value));
            info
        });
        ui.ctx().accesskit_node_builder(response.id, |node| {
            node.set_orientation(if horizontal {
                Orientation::Vertical
            } else {
                Orientation::Horizontal
            });
            node.set_min_numeric_value(f64::from(min));
            node.set_max_numeric_value(f64::from(max));
            node.set_numeric_value_step(f64::from(accesskit_step));
            if range > 0.0 {
                node.add_action(Action::SetValue);
                if value < max {
                    node.add_action(Action::Increment);
                }
                if min < value {
                    node.add_action(Action::Decrement);
                }
            }
        });
    }
}

/// A separator of a container: the one after the child `index` of a linear node, or the line
/// after the column or the row `index` of a grid.
#[derive(Clone, Copy, Debug)]
enum SeparatorOf {
    Linear(usize),
    Column(usize),
    Row(usize),
}

/// The separators of `node`: one between each pair of neighbours of a linear node, one on each
/// line between two columns then between two rows of a grid.
fn separators<Tab>(node: &Node<Tab>) -> Vec<SeparatorOf> {
    match node {
        Node::Linear(linear) => (0..linear.len().saturating_sub(1))
            .map(SeparatorOf::Linear)
            .collect(),
        Node::Grid(grid) => (0..grid.columns() - 1)
            .map(SeparatorOf::Column)
            .chain((0..grid.rows() - 1).map(SeparatorOf::Row))
            .collect(),
        _ => Vec::new(),
    }
}

/// Where the separators of `linear` stand, in points from its start along its axis: one per
/// pair of neighbours. Collapsed children of a column (`Some(number of collapsed leaves)`)
/// keep the height of their tab bars; the others share the rest. If all are collapsed, the
/// last one takes the rest.
fn boundaries(
    linear: &crate::LinearNode,
    collapsed: &[Option<i32>],
    size: f32,
    tab_bar_height: f32,
) -> Vec<f32> {
    let n = linear.len();
    let sizes: Vec<f32> = if collapsed.iter().all(Option::is_none) {
        (0..n).map(|i| size * linear.fraction(i)).collect()
    } else {
        let fixed: f32 = collapsed
            .iter()
            .flatten()
            .map(|&count| count as f32 * tab_bar_height)
            .sum();
        let open_total: f32 = (0..n)
            .filter(|&i| collapsed[i].is_none())
            .map(|i| linear.shares()[i])
            .sum();
        let open_count = collapsed.iter().filter(|c| c.is_none()).count() as f32;
        let rest = (size - fixed).max(0.0);
        let mut sizes: Vec<f32> = (0..n)
            .map(|i| match collapsed[i] {
                Some(count) => count as f32 * tab_bar_height,
                None if open_total > 0.0 => rest * linear.shares()[i] / open_total,
                None => rest / open_count,
            })
            .collect();
        if open_count == 0.0 {
            let others: f32 = sizes[..n - 1].iter().sum();
            sizes[n - 1] = size - others;
        }
        sizes
    };
    sizes
        .iter()
        .take(n - 1)
        .scan(0.0, |acc, s| {
            *acc += s;
            Some(*acc)
        })
        .collect()
}

/// The restore bands of `restores`, in the same order: each `breadth` wide along its zone's
/// former boundary, on the side the zone would come back on. Bands on the same boundary, the same
/// side and overlapping across it stack in tree order, the first nearest the boundary's start.
pub(crate) fn restore_bands(restores: &[RestoreDrop], breadth: f32) -> Vec<Rect> {
    let along = |dir: Dir, rect: Rect| match dir {
        Dir::Horizontal => rect.min.x,
        Dir::Vertical => rect.min.y,
    };
    let across = |dir: Dir, rect: Rect| match dir {
        Dir::Horizontal => (rect.min.y, rect.max.y),
        Dir::Vertical => (rect.min.x, rect.max.x),
    };
    let same_boundary = |a: &RestoreDrop, b: &RestoreDrop| {
        let (a, b) = (&a.restore, &b.restore);
        let (a_min, a_max) = across(a.dir, a.line);
        let (b_min, b_max) = across(b.dir, b.line);
        a.dir == b.dir
            && a.towards_end == b.towards_end
            && (along(a.dir, a.line) - along(b.dir, b.line)).abs() < 0.5
            && a_min < b_max
            && b_min < a_max
    };
    restores
        .iter()
        .enumerate()
        .map(|(i, drop)| {
            let restore = &drop.restore;
            let before = restores[..i]
                .iter()
                .filter(|other| same_boundary(drop, other))
                .count();
            let count = restores
                .iter()
                .filter(|other| same_boundary(drop, other))
                .count();
            let line = along(restore.dir, restore.line);
            // Laid out from the boundary's start in tree order.
            let from = if restore.towards_end {
                line + before as f32 * breadth
            } else {
                line - (count - before) as f32 * breadth
            };
            let (min, max) = across(restore.dir, restore.line);
            match restore.dir {
                Dir::Horizontal => Rect::from_min_max(pos2(from, min), pos2(from + breadth, max)),
                Dir::Vertical => Rect::from_min_max(pos2(min, from), pos2(max, from + breadth)),
            }
        })
        .collect()
}