cydonia 0.1.16

Desktop workspace for the ACP agents you run, keeping what they produce as files on your disk
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
//! Drawing a space: the panes it arranges, the seams between them, and the
//! edges a drag can drop on.
//!
//! The tree is [`artifact::space::Node`] — see there for what the shape
//! means. This is only how it lands on the window.

use crate::{
    model::workspace::Showing,
    view::{
        chrome,
        component::{
            divider,
            menu::{self, Menu},
        },
        leaf::Pane,
        root::Cydonia,
        sidebar::{Carried, EntryDrag},
    },
};
use artifact::space::{Axis as Split, Member, Node, Side, Space};
use bezel::{
    gpui::{
        AnyElement, App, Axis, Context, DragMoveEvent, Empty, MouseButton, SharedString, Window,
        div, prelude::*, px, relative,
    },
    theme::Theme,
    ui::{
        icons, menu::Item, popover, tabs, titlebar::CaptionSide, tooltip::Tooltip, widgets::Content,
    },
};

/// What a seam carries while it is dragged: the split it divides, by its path
/// from the root, and which of that split's children it sits after.
///
/// The path rather than a node id: the tree is rebuilt from the file on every
/// change, so nothing in it has an identity that outlives a drag.
#[derive(Clone, Debug)]
pub struct SeamDrag {
    pub path: Vec<usize>,
    pub at: usize,
}

/// Where a release on a pane lands the entry being dragged.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Landing {
    /// On an edge: the pane divides, and the arrival takes that side.
    Edge(Side),
    /// On the bar: the arrival joins the pane's strip as a tab, and no seam is
    /// made. What the bar is *for* — a pane's whole body is four edges, so
    /// without a target that is not one of them there is nowhere to aim.
    Bar,
}

/// What a pane's `+` makes.
#[derive(Clone, Copy)]
enum New {
    /// On the agent at this index of the settings.
    Session(usize),
    Board,
    Article,
    Table,
}

/// The least of a split a pane may be squeezed to. A pane thinner than this
/// has nothing left to grab it by.
const MIN_SHARE: f64 = 0.08;

/// What an arrival takes of the pane it is dropped on: half, which is also
/// what the split leaves the two of them at.
const HALF: f32 = 0.5;

/// What the pane's name is padded by, and what a bar that is not the window's
/// leading one starts its name at: the fill that marks the focused pane needs
/// room around the text, and room off the pane's own edge so it does not run
/// into the seam.
const TAB_INSET: f32 = 8.;

impl Cydonia {
    /// The space the window is arranged by, taken whole: the tree is walked
    /// while the workspace is drawn from, so it is cloned out first.
    pub(crate) fn arrangement(&self, cx: &App) -> Option<Space> {
        self.workspace.read(cx).active_space().cloned()
    }

    /// The panes of the open space, or nothing where none is open and the
    /// window is showing one entry.
    pub(crate) fn panes(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let space = self.arrangement(cx)?;
        // A zoomed pane stands over the rest, which keep their places
        // underneath — see [`Space::zoom`].
        if let Some(entry) = space.zoomed() {
            return Some(self.pane(&entry, window, cx));
        }
        Some(self.node(&space.tree, &mut Vec::new(), window, cx))
    }

    /// One node: a pane, or a split of them laid out along its axis.
    fn node(
        &self,
        node: &Node<Member>,
        path: &mut Vec<usize>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        match node {
            // `entry` is the pane's name, not what it is showing — the pane
            // resolves its own strip and which of it is in front.
            Node::Leaf { entry, .. } => self.pane(entry, window, cx),
            Node::Split { axis, children, .. } => {
                let axis = *axis;
                let theme = Theme::of(cx).clone();
                let here = path.clone();
                let across = match axis {
                    Split::Horizontal => Axis::Horizontal,
                    Split::Vertical => Axis::Vertical,
                };
                let mut row = div()
                    .size_full()
                    .min_w_0()
                    .min_h_0()
                    .relative()
                    .flex()
                    .map(|el| match axis {
                        Split::Horizontal => el.flex_row(),
                        Split::Vertical => el.flex_col(),
                    })
                    // On the split rather than on each seam: the bounds a drag
                    // is measured against are this split's, and a seam knows
                    // only its own.
                    .on_drag_move(cx.listener({
                        let here = here.clone();
                        move |this, event: &DragMoveEvent<SeamDrag>, _, cx| {
                            let drag = event.drag(cx);
                            if drag.path != here {
                                return;
                            }
                            let bounds = event.bounds;
                            let at = event.event.position;
                            let fraction = match axis {
                                Split::Horizontal => {
                                    (f32::from(at.x - bounds.left()) / f32::from(bounds.size.width))
                                        as f64
                                }
                                Split::Vertical => {
                                    (f32::from(at.y - bounds.top()) / f32::from(bounds.size.height))
                                        as f64
                                }
                            };
                            this.move_seam(&here, drag.at, fraction, cx);
                        }
                    }));
                for (ix, child) in children.iter().enumerate() {
                    path.push(ix);
                    let body = self.node(child, path, window, cx);
                    path.pop();
                    row = row.child(
                        div()
                            .min_w_0()
                            .min_h_0()
                            // Shrinks but does not grow: the shares are of the
                            // whole split and sum to it, and shrinking absorbs
                            // whatever rounding leaves over.
                            .flex_initial()
                            .flex()
                            .flex_col()
                            .map(|el| match axis {
                                Split::Horizontal => el.w(relative(child.ratio() as f32)).h_full(),
                                Split::Vertical => el.h(relative(child.ratio() as f32)).w_full(),
                            })
                            .child(body),
                    );
                }
                // The seams ride the boundary rather than sitting in flow, the
                // way the sidebar's does — a divider taking a column of its own
                // pushes the panes apart into a gap, where what is wanted is
                // one line between two panes that meet.
                let mut edge = 0.;
                for (ix, child) in children.iter().enumerate() {
                    edge += child.ratio() as f32;
                    if ix + 1 == children.len() {
                        break;
                    }
                    let (path, at) = (here.clone(), ix);
                    row = row.child(
                        divider::divider(&theme, across)
                            .id(("pane-seam", seam_id(&here, at)))
                            .absolute()
                            .map(|el| match axis {
                                Split::Horizontal => el
                                    .top_0()
                                    .bottom_0()
                                    .left(relative(edge))
                                    .ml(px(-divider::HIT / 2.)),
                                Split::Vertical => el
                                    .left_0()
                                    .right_0()
                                    .top(relative(edge))
                                    .mt(px(-divider::HIT / 2.)),
                            })
                            .on_drag(SeamDrag { path, at }, |_, _, _, cx| cx.new(|_| Empty)),
                    );
                }
                row.into_any_element()
            }
        }
    }

    /// One pane: the entries it holds, and whichever of them is in front.
    ///
    /// `entry` is the pane's *name* — the first of its strip, which is what
    /// the space keeps and what every drop and close here is aimed at. What
    /// the pane is showing is [`Self::front_of`], and the two are the same
    /// thing only for a pane holding one entry.
    fn pane(&self, entry: &Member, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        // The pane at the window's top left, which is the one that has to keep
        // clear of the traffic lights.
        let first = self
            .arrangement(cx)
            .and_then(|space| space.entries().first().cloned())
            .as_ref()
            == Some(entry);
        // And the one at its top right, which carries the caption buttons
        // unless the right panel stands between it and the edge.
        let last = self.changes.is_none()
            && self
                .arrangement(cx)
                .and_then(|space| space.zoomed().or_else(|| top_right(&space.tree)))
                .as_ref()
                == Some(entry);
        let theme = Theme::of(cx).clone();
        let stack = self.workspace.read(cx).stack_of(entry);
        let front = self.front_of(entry, &stack);
        let showing = self.workspace.read(cx).showing_of(&front);
        let key = key_of(entry);
        let held = entry.clone();
        let body = match showing {
            // The entry has gone since the space named it. The pane says so
            // rather than standing empty: a blank pane reads as a bug, and the
            // space is about to drop the member anyway — see
            // [`crate::model::workspace::Workspace::prune_spaces`].
            None => theme
                .empty_state(
                    icons::files::File,
                    "This entry has gone",
                    "It was deleted after the space was made.",
                )
                .into_any_element(),
            Some((project, showing)) => self.pane_body(project, showing, Some(&front), window, cx),
        };
        let composer = match showing {
            Some((_, Showing::Session(_))) => self
                .leaves
                .iter()
                .find(|leaf| leaf.entry.as_ref() == Some(&front))
                .map(|leaf| crate::view::detail::footer(leaf.composer.clone(), None)),
            _ => None,
        };
        let landing = self
            .pane_landing
            .as_ref()
            .filter(|(on, _)| on == entry)
            .map(|(_, at)| *at);
        div()
            .id(SharedString::from(format!("pane-{key}")))
            // With the context but without this, a pane claims chords that
            // never reach it: an action runs through the focused element's
            // ancestors, and a pane showing a board holds nothing that takes
            // the focus — see [`crate::view::leaf::Leaf::focus`].
            // The front's leaf, not the pane's own name: the body, the
            // composer and [`Cydonia::focus_pane`] all answer for the tab in
            // front, and a pane tracking a handle nothing focuses reads as
            // unfocused while the window's focus sits on an element no frame
            // draws — which the root then takes back. See
            // [`Cydonia::leaf_of`], whose fallback is the focused leaf: two
            // panes that both miss would track one handle and both light up.
            .track_focus(&self.leaf_of(Some(&front)).focus.clone())
            .group("pane")
            .size_full()
            .min_w_0()
            .min_h_0()
            // A flex column, not just a box: every pane draws itself with
            // `flex_1`, which fills nothing at all outside one.
            .flex()
            .flex_col()
            .relative()
            .overflow_hidden()
            // No fill: the panes sit on the detail column's one surface, and a
            // wash per pane would draw the arrangement as a row of cards
            // rather than one plane divided. The focus is said on the pane's
            // name — see [`Self::pane_bar`].
            //
            // Which edge the pointer is over decides what a release does, so
            // it is tracked while the drag is in the air and drawn by the mark
            // below.
            .on_drag_move(cx.listener({
                let on = held.clone();
                move |this, event: &DragMoveEvent<EntryDrag>, _, cx| {
                    this.aim_pane(&on, true, event.bounds, event.event.position, cx);
                }
            }))
            .on_drop(cx.listener({
                let on = held.clone();
                move |this, drag: &EntryDrag, window, cx| {
                    if let Some(arriving) = this.dropped(drag, cx) {
                        this.drop_entry(&arriving, &on, window, cx);
                    }
                }
            }))
            // Pressing anywhere in a pane is how the focus moves to it, the
            // same way a click into the sidebar selects a row.
            //
            // The tab in front, not the pane's name: a leaf is held by what it
            // shows — see [`Cydonia::leaf_of`] — so a pane showing its second
            // tab would be named by a member no leaf answers to, and the press
            // would leave the focus where it was.
            .on_mouse_down(
                MouseButton::Left,
                cx.listener({
                    let on = front.clone();
                    move |this, _, window, cx| this.focus_pane(&on, window, cx)
                }),
            )
            .child(self.pane_bar(entry, &stack, &front, first, last, &theme, window, cx))
            .child(body)
            .children(composer)
            .children(landing.map(|at| landing_mark(at, &theme)))
            .into_any_element()
    }

    /// Which of a pane's entries it is showing.
    ///
    /// Kept on the window and not in the file — see [`Cydonia::fronts`] — so a
    /// space reopens with each pane on the first of its strip. What is
    /// remembered falls back to that as well once it is no longer in the
    /// strip, which is what a closed tab leaves behind.
    pub(crate) fn front_of(&self, pane: &Member, stack: &[Member]) -> Member {
        self.fronts
            .get(&key_of(pane))
            .filter(|front| stack.contains(front))
            .or_else(|| stack.first())
            .unwrap_or(pane)
            .clone()
    }

    /// Note a tab as the one most recently brought to the front, which is
    /// where a close falls back to — see [`Cydonia::tab_history`].
    fn remember_front(&mut self, tab: &Member) {
        self.tab_history.retain(|seen| seen != tab);
        self.tab_history.push(tab.clone());
    }

    /// Show one of a pane's tabs, and put the focus on it — a tab pressed is a
    /// pane entered, the same as a press anywhere else in one.
    pub(crate) fn show_tab(
        &mut self,
        pane: &Member,
        tab: &Member,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.fronts.insert(key_of(pane), tab.clone());
        self.remember_front(tab);
        // Before the focus moves: a tab the space has gained since the last
        // frame has no leaf yet, and [`Cydonia::focus_pane`] moves nothing it
        // cannot find.
        self.sync_leaves(window, cx);
        self.focused = usize::MAX;
        self.focus_pane(tab, window, cx);
        cx.notify();
    }

    /// The single pane, wrapped so an entry dropped on its edge makes the
    /// space that puts the two side by side.
    pub(crate) fn lone_pane(&self, body: AnyElement, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let Some(on) = self
            .workspace
            .read(cx)
            .active
            .zip(self.showing(cx))
            .and_then(|(project, pane)| self.member_showing(project, pane, cx))
        else {
            return body;
        };
        let landing = self
            .pane_landing
            .as_ref()
            .filter(|(at, _)| *at == on)
            .map(|(_, at)| *at);
        div()
            .id("lone-pane")
            .size_full()
            .min_w_0()
            .min_h_0()
            .relative()
            .flex()
            .flex_col()
            .on_drag_move(cx.listener({
                let at = on.clone();
                move |this, event: &DragMoveEvent<EntryDrag>, _, cx| {
                    this.aim_pane(&at, false, event.bounds, event.event.position, cx);
                }
            }))
            .on_drop(cx.listener({
                let at = on.clone();
                move |this, drag: &EntryDrag, window, cx| {
                    if let Some(arriving) = this.dropped(drag, cx) {
                        this.drop_entry(&arriving, &at, window, cx);
                    }
                }
            }))
            .child(body)
            .children(landing.map(|at| landing_mark(at, &theme)))
            .into_any_element()
    }

    /// The member a drag names, once it has landed.
    ///
    /// A session carried with no file yet is given one here: a space names
    /// its members by file, so there is nothing to put in one until this runs.
    /// Minting it at the drop rather than at the drag keeps a gesture that
    /// went nowhere from leaving a session behind on disk.
    pub(crate) fn dropped(&mut self, drag: &EntryDrag, cx: &mut Context<Self>) -> Option<Member> {
        match drag {
            EntryDrag::Member(member) => Some(member.clone()),
            EntryDrag::Session { project, id } => {
                let (project, id) = (*project, *id);
                self.workspace.update(cx, |workspace, cx| {
                    workspace.retain_session(id, cx)?;
                    workspace.member_of(project, Showing::Session(id))
                })
            }
        }
    }

    /// The member that names what a single pane is on.
    fn member_showing(
        &self,
        project: usize,
        pane: crate::view::leaf::Pane,
        cx: &App,
    ) -> Option<Member> {
        use crate::view::leaf::Pane;
        let workspace = self.workspace.read(cx);
        let open = workspace.projects.get(project)?;
        let showing = match pane {
            Pane::Chat => Showing::Session(open.active?),
            Pane::Board => Showing::Board(open.board?),
            Pane::Article => Showing::Article(open.article?),
            Pane::Table => Showing::Table(open.table?),
        };
        workspace.member_of(project, showing)
    }

    /// How much of the detail column's width a pane has. The whole of it where
    /// no space is open, or where the entry is not one a pane is on.
    pub(crate) fn width_share(&self, entry: Option<&Member>, cx: &App) -> f32 {
        let Some(entry) = entry else {
            return 1.;
        };
        self.arrangement(cx)
            .and_then(|space| match space.zoomed() {
                // A zoomed pane has the window to itself.
                Some(zoomed) if zoomed == *entry => Some(1.),
                Some(_) => None,
                None => space.tree.share_of(entry, Split::Horizontal),
            })
            .unwrap_or(1.) as f32
    }

    /// One pane's bar: what it is on, and the way out of the arrangement.
    ///
    /// A tab rather than a title, because a pane is where an entry is open and
    /// that is what a tab has always meant here — see
    /// [`crate::view::component::panel`], which holds several.
    ///
    /// The first pane is the one at the window's top left, so it carries what
    /// the window puts there: the traffic lights' clearance, and the fold that
    /// brings the sidebar back. Both are the band's when no space is open —
    /// see [`Self::pane_header`], which this follows.
    #[allow(clippy::too_many_arguments)]
    fn pane_bar(
        &self,
        pane: &Member,
        stack: &[Member],
        front: &Member,
        first: bool,
        last: bool,
        theme: &Theme,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let key = key_of(pane);
        // The lights are the window's and are drawn over whatever is at its
        // top left, so their clearance is taken by the pane that lands there
        // and nowhere another pane can see it. Fullscreen has none.
        let fold = first && !self.sidebar_open;
        let left = fold && chrome::has(CaptionSide::Left, window, cx);
        let right = last && chrome::has(CaptionSide::Right, window, cx);
        let lead = match (first, self.sidebar_open || window.is_fullscreen()) {
            _ if left => 0.,
            (true, true) => crate::view::root::HEADER_INSET,
            (true, false) => crate::view::root::TOOLBAR_INSET,
            (false, _) => TAB_INSET,
        };
        // The bar is a drop target of its own — see [`Landing::Bar`] — so it
        // is lit while a drag is aimed at it rather than at an edge.
        let aimed = self.pane_landing.as_ref() == Some(&(pane.clone(), Landing::Bar));
        crate::view::root::band()
            .group("pane-bar")
            .w_full()
            .gap(px(2.))
            .pl(px(lead))
            .when(right, |el| el.pr_0())
            .when(aimed, |el| el.bg(theme.element_hover))
            .children(
                left.then(|| chrome::caption(CaptionSide::Left, window, cx))
                    .flatten(),
            )
            // The fold belongs to whichever column runs along the window's left
            // edge, so with the sidebar gone it is this pane's.
            .children(fold.then(|| self.fold_toggle(cx).into_any_element()))
            .children(fold.then(|| self.app_menu(window, cx)).flatten())
            // The tabs in a strip of their own, which scrolls sideways once
            // they no longer fit: the bar's other children are the pane's
            // chrome and keep their places while it does.
            .child(
                tabs::bar(SharedString::from(format!("pane-strip-{key}"))).children(
                    stack
                        .iter()
                        .map(|tab| self.pane_tab(pane, tab, tab == front, theme, cx)),
                ),
            )
            .children(self.pane_project(front, cx).map(|project| {
                self.menu_button(
                    SharedString::from(format!("pane-add-{key}")),
                    Some("pane-bar"),
                    icons::math::Plus,
                    Menu::PaneAdd(key.clone()),
                    cx,
                )
                .children(self.pane_add_menu(pane, project, window, cx))
            }))
            .child(chrome::grip(
                SharedString::from(format!("pane-grip-{key}")),
                &self.drag,
                window,
            ))
            .child(
                self.menu_button(
                    SharedString::from(format!("pane-menu-{key}")),
                    Some("pane"),
                    icons::layout::Ellipsis,
                    Menu::Pane(key.clone()),
                    cx,
                )
                .children(self.pane_menu(pane, window, cx)),
            )
            .children(
                right
                    .then(|| chrome::caption(CaptionSide::Right, window, cx))
                    .flatten(),
            )
            .into_any_element()
    }

    /// One tab: what it is on, and the `×` that takes it out.
    ///
    /// Every tab carries the close, the pane's first included. There is no
    /// separate control for closing the pane, because there is no separate
    /// thing to close: a pane is its strip, and the last `×` takes the pane
    /// with the tab. The focus mark is on the tab rather than on the pane,
    /// since the panes are one plane divided and take no fill of their own.
    fn pane_tab(
        &self,
        pane: &Member,
        tab: &Member,
        front: bool,
        theme: &Theme,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let toolbar = self
            .workspace
            .read(cx)
            .showing_of(tab)
            .and_then(|(project, showing)| self.toolbar_of(project, showing, cx));
        // A number is a project's own, and an arrangement can hold panes from
        // several — so the tab says which project the number is counted in.
        let project = self
            .workspace
            .read(cx)
            .projects
            .iter()
            .find(|open| open.path == tab.project)
            .map(|open| open.name())
            .unwrap_or_default();
        // The pane in front *and* the tab in front of that pane: a background
        // pane's own front tab is not where the window's attention is.
        let focused = front && self.leaf().entry.as_ref() == Some(tab);
        let key = key_of(tab);
        let title = SharedString::from(
            toolbar
                .as_ref()
                .map(|toolbar| toolbar.title.clone())
                .unwrap_or_default(),
        );
        let mut label = tabs::Label::new(title.clone());
        // A number is the badge rather than part of the name: the name
        // truncates and the reference has to survive that.
        if let Some(number) = toolbar.as_ref().and_then(|toolbar| toolbar.number) {
            label = label.with_badge(format!("{project}#{number}"));
        }
        // A tab that is showing but not focused still has to read as the one
        // its pane is on, or a background pane's strip says nothing about what
        // is under it — which is [`tabs::State::Front`].
        let state = match (focused, front) {
            (true, _) => tabs::State::Focused,
            (false, true) => tabs::State::Front,
            (false, false) => tabs::State::Resting,
        };
        tabs::tab(theme, key.clone(), label, state)
            .on_click(cx.listener({
                let (on, shown) = (pane.clone(), tab.clone());
                move |this, _, window, cx| this.show_tab(&on, &shown, window, cx)
            }))
            // Carried to another pane's bar to join its strip, or to an edge
            // to be pulled out into a pane of its own. The same drag the
            // sidebar makes, down to the ghost: where a tab came from is not
            // something the pane it lands on has to know.
            .on_drag(EntryDrag::Member(tab.clone()), move |_, _, _, cx| {
                let label = title.clone();
                cx.new(|_| Carried(label))
            })
            .child(
                tabs::close(theme, key, tabs::Close::OnHover)
                    .tooltip(move |window, cx| Tooltip::text("Close tab", window, cx))
                    .on_click(cx.listener({
                        let shut = tab.clone();
                        move |this, _, window, cx| {
                            cx.stop_propagation();
                            this.close_pane(&shut, window, cx);
                        }
                    })),
            )
            .into_any_element()
    }

    /// What the `···` on a pane's bar offers: what can be done to the *pane*.
    ///
    /// Nothing about the entry it is on — no rename, no archive, no delete.
    /// Those act on a thing that has its own row in the sidebar and its own
    /// band when it is opened on its own, and `../desktop`'s rule for a `···`
    /// is that it carries only what has no affordance elsewhere. A delete one
    /// click from the moves would also be a delete nobody meant.
    ///
    /// Closing is not here either: it keeps the button on the bar.
    fn pane_menu(
        &self,
        entry: &Member,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Option<AnyElement> {
        let key = key_of(entry);
        if self.menu.as_ref() != Some(&Menu::Pane(key.clone())) {
            return None;
        }
        let zoomed = self
            .arrangement(cx)
            .and_then(|space| space.zoomed())
            .is_some_and(|at| at == *entry);

        let mut rows = vec![menu::row(
            match zoomed {
                true => Item::action("Restore").with_icon(icons::arrows::Shrink),
                false => Item::action("Expand").with_icon(icons::arrows::Expand),
            },
            {
                let on = entry.clone();
                move |this, _, cx| this.zoom_focused(&on, cx)
            },
        )];
        // Only the ways this pane can actually go: a move with nothing across
        // the seam is a row that does nothing, and a menu of those teaches
        // that the menu does nothing.
        for (side, label, icon) in [
            (Side::Left, "Move left", icons::arrows::ArrowLeft),
            (Side::Right, "Move right", icons::arrows::ArrowRight),
            (Side::Above, "Move up", icons::arrows::ArrowUp),
            (Side::Below, "Move down", icons::arrows::ArrowDown),
        ] {
            if self
                .workspace
                .read(cx)
                .neighbour_pane(entry, side)
                .is_none()
            {
                continue;
            }
            let on = entry.clone();
            rows.push(menu::row(
                Item::action(label).with_icon(icon),
                move |this, window, cx| this.move_pane(&on, side, window, cx),
            ));
        }
        let id = SharedString::from(format!("pane-menu-card-{key}"));
        Some(popover::anchored_menu_below(
            id.clone(),
            self.menu_card(id, rows, window, cx),
            None,
        ))
    }

    /// Exchange a pane with the one across the seam, and keep the focus on it
    /// — the pane moved, not the attention.
    fn move_pane(
        &mut self,
        entry: &Member,
        side: Side,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let moved = self
            .workspace
            .update(cx, |workspace, cx| workspace.move_pane(entry, side, cx));
        if moved {
            self.sync_leaves(window, cx);
            self.focus_pane(entry, window, cx);
        }
    }

    /// Stand a pane over the others, or put it back.
    fn zoom_focused(&mut self, entry: &Member, cx: &mut Context<Self>) {
        self.workspace
            .update(cx, |workspace, cx| workspace.zoom_pane(entry, cx));
    }

    /// Drop one pane from the arrangement.
    pub(crate) fn close_pane(
        &mut self,
        entry: &Member,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        // The pane the tab was in, if it survives losing it: what the window
        // lands on next is that pane's new front, not whatever leaf happens to
        // sit where the closed one did.
        let stack = self.workspace.read(cx).stack_of(entry);
        let kept = (stack.len() > 1)
            .then(|| {
                // The tab that was in front before this one, so closing walks
                // back the way the reader came. Nothing remembered — a pane
                // never left its first tab — falls back to a neighbour in the
                // strip: the one to its left, or the one to its right for the
                // first.
                let recent = self
                    .tab_history
                    .iter()
                    .rev()
                    .find(|tab| *tab != entry && stack.contains(tab))
                    .cloned();
                recent.or_else(|| {
                    stack
                        .iter()
                        .position(|tab| tab == entry)
                        .map(|at| match at {
                            0 => stack[1].clone(),
                            at => stack[at - 1].clone(),
                        })
                })
            })
            .flatten();
        self.tab_history.retain(|tab| tab != entry);
        // The entry left when this close took the space with it. Without
        // putting the pane on its kind the window drops back to whatever the
        // single pane was last showing, which is not what was on screen.
        let alone = self
            .workspace
            .update(cx, |workspace, cx| workspace.close_pane(entry, cx));
        self.fronts.remove(&key_of(entry));
        if let Some(kept) = &kept
            && let Some(pane) = self.workspace.read(cx).stack_of(kept).first().cloned()
        {
            self.fronts.insert(key_of(&pane), kept.clone());
        }
        // The pane left alone is the one to keep, not the one just closed:
        // [`Cydonia::sync_leaves`] keeps whichever leaf is focused when it
        // finds no space, and the focus is still on the pane going away.
        if let Some((member, _)) = &alone
            && let Some(at) = self
                .leaves
                .iter()
                .position(|leaf| leaf.entry.as_ref() == Some(member))
        {
            self.focused = at;
        }
        self.sync_leaves(window, cx);
        if let Some((_, showing)) = alone {
            self.show_pane(pane_of(showing), cx);
        }
        if let Some(entry) = kept.or_else(|| self.leaf().entry.clone()) {
            self.focused = usize::MAX;
            self.focus_pane(&entry, window, cx);
        }
        cx.notify();
    }

    /// What one pane draws, whichever kind of entry it is on.
    pub(crate) fn pane_body(
        &self,
        project: usize,
        showing: Showing,
        on: Option<&Member>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        match showing {
            Showing::Session(id) => self.conversation(Some(id), on, window, cx),
            Showing::Board(at) => self.board(project, at, on, window, cx),
            // An entry can be named and not yet loaded — an article holds no
            // editor until it is opened. The front door stands in for the
            // moment in between.
            Showing::Article(at) => self
                .article(project, at, on, window, cx)
                .unwrap_or_else(|| self.launch(window, cx)),
            Showing::Table(at) => self
                .table(project, at, on, window, cx)
                .unwrap_or_else(|| self.launch(window, cx)),
        }
    }

    /// Which edge of a pane a pointer at this fraction of it is nearest.
    ///
    /// The four answers tile the pane, so there is nowhere in it a release
    /// means nothing — a target that lights up and then does nothing when let
    /// go of is worse than no target at all.
    pub(crate) fn side_at(across: f32, down: f32) -> Side {
        [
            (across, Side::Left),
            (1. - across, Side::Right),
            (down, Side::Above),
            (1. - down, Side::Below),
        ]
        .into_iter()
        .fold((f32::MAX, Side::Left), |(near, held), (at, side)| {
            match at < near {
                true => (at, side),
                false => (near, held),
            }
        })
        .1
    }

    /// Step the focus to the pane next along the arrangement.
    ///
    /// The order is the order the panes are laid out — left to right, and each
    /// column top to bottom — so this walks the window rather than jumping
    /// about it. `select-pane -LRUD` measured off the bounds would be truer to
    /// tmux; it needs each pane's frame, which nothing here keeps yet.
    pub(crate) fn step_pane(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {
        // Panes, not members: a pane holding three tabs is one stop on the
        // walk, and ⌃⇥ is what steps through what it holds.
        let panes = match self.arrangement(cx) {
            Some(space) => space.panes(),
            None => return,
        };
        if panes.len() < 2 {
            return;
        }
        let here = self.leaf().entry.clone();
        let at = here
            .and_then(|front| {
                let stack = self.workspace.read(cx).stack_of(&front);
                let pane = stack.first()?;
                panes.iter().position(|named| named == pane)
            })
            .unwrap_or(0);
        let landing = (at as isize + step).rem_euclid(panes.len() as isize) as usize;
        let Some(pane) = panes.get(landing) else {
            return;
        };
        let stack = self.workspace.read(cx).stack_of(pane);
        let front = self.front_of(pane, &stack);
        self.focused = usize::MAX;
        self.focus_pane(&front, window, cx);
    }

    /// Close the tab in front — and with it the pane, where it was the pane's
    /// last. The keyboard's half of the `×` on a tab.
    pub(crate) fn close_focused_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(entry) = self.leaf().entry.clone() else {
            return;
        };
        self.close_pane(&entry, window, cx);
    }

    /// Stand the pane in front over the others, or put it back.
    pub(crate) fn zoom_focused_pane(&mut self, cx: &mut Context<Self>) {
        let Some(entry) = self.leaf().entry.clone() else {
            return;
        };
        self.workspace.update(cx, |workspace, cx| {
            workspace.zoom_pane(&entry, cx);
        });
        cx.notify();
    }

    /// Open a space: the window is arranged by it until another entry is
    /// opened on its own.
    pub(crate) fn open_space(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
        self.workspace.update(cx, |workspace, cx| {
            workspace.open_space(ix, cx);
        });
        self.sync_leaves(window, cx);
        // The focus lands on the first pane the arrangement lays out, which is
        // the one at its top left.
        if let Some(entry) = self.leaves.first().and_then(|leaf| leaf.entry.clone()) {
            self.focused = 0;
            self.focus_pane(&entry, window, cx);
        }
        cx.notify();
    }

    /// Note which edge of a pane the pointer is over, so the mark can say
    /// where a release would put what is in the air.
    /// `bar` says whether this pane has a strip to drop onto. The window
    /// showing one entry has none — there is no space yet, so there is no
    /// pane to join — and its top row is an edge like any other.
    fn aim_pane(
        &mut self,
        entry: &Member,
        bar: bool,
        bounds: bezel::gpui::Bounds<bezel::gpui::Pixels>,
        at: bezel::gpui::Point<bezel::gpui::Pixels>,
        cx: &mut Context<Self>,
    ) {
        if !bounds.contains(&at) {
            // Left this pane: whichever one the pointer is now inside says so
            // for itself, and a release outside them all means nothing.
            if self
                .pane_landing
                .as_ref()
                .is_some_and(|(on, _)| on == entry)
            {
                self.pane_landing = None;
                cx.notify();
            }
            return;
        }
        // The bar wins over the edges it overlaps. It is one row tall against
        // a whole pane, so without this the top edge would swallow every drop
        // aimed at a strip and the bar would be unreachable.
        let landing = match bar && at.y - bounds.top() <= px(crate::view::root::HEADER_HEIGHT) {
            true => Landing::Bar,
            false => {
                let across = f32::from(at.x - bounds.left()) / f32::from(bounds.size.width);
                let down = f32::from(at.y - bounds.top()) / f32::from(bounds.size.height);
                Landing::Edge(Self::side_at(across, down))
            }
        };
        if self.pane_landing.as_ref() != Some(&(entry.clone(), landing)) {
            self.pane_landing = Some((entry.clone(), landing));
            cx.notify();
        }
    }

    /// A release on a pane: beside it where the pointer was over an edge, and
    /// on it where it was over the middle.
    fn drop_entry(
        &mut self,
        arriving: &Member,
        target: &Member,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some((_, landing)) = self.pane_landing.take() else {
            return;
        };
        match landing {
            Landing::Edge(side) => {
                self.workspace.update(cx, |workspace, cx| {
                    workspace.arrange(target, arriving, side, cx)
                });
                self.sync_leaves(window, cx);
                self.focused = usize::MAX;
                self.focus_pane(arriving, window, cx);
                cx.notify();
            }
            Landing::Bar => self.add_tab(target, arriving.clone(), window, cx),
        }
    }

    /// Put `arriving` in `pane`'s strip as its front tab, and focus it.
    pub(crate) fn add_tab(
        &mut self,
        pane: &Member,
        arriving: Member,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.workspace.update(cx, |workspace, cx| {
            workspace.stack_pane(pane, &arriving, cx)
        });
        // The pane's name can have changed under the move — a tab dragged out
        // of a strip leaves the one behind it holding the pane — so the strip
        // is read back rather than assumed.
        let stack = self.workspace.read(cx).stack_of(&arriving);
        if let Some(pane) = stack.first().cloned() {
            self.fronts.insert(key_of(&pane), arriving.clone());
            self.remember_front(&arriving);
        }
        self.sync_leaves(window, cx);
        self.focused = usize::MAX;
        self.focus_pane(&arriving, window, cx);
        cx.notify();
    }

    /// The open project a pane's front tab is in.
    fn pane_project(&self, front: &Member, cx: &App) -> Option<usize> {
        self.workspace
            .read(cx)
            .showing_of(front)
            .map(|(project, _)| project)
    }

    /// What the `+` in a pane's bar starts: the sidebar's `+` for the
    /// project of the pane's front tab, landing as a tab of the pane.
    fn pane_add_menu(
        &self,
        pane: &Member,
        project: usize,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Option<AnyElement> {
        let key = key_of(pane);
        if self.menu.as_ref() != Some(&Menu::PaneAdd(key.clone())) {
            return None;
        }
        let workspace = self.workspace.read(cx);
        let features = &workspace.settings.features;
        let (sessions, boards, tables) = (features.sessions, features.boards, features.tables);
        let agents: Vec<(String, Option<icons::Icon>)> = workspace
            .settings
            .agents
            .iter()
            .map(|entry| (entry.name.clone(), workspace.agent_icon(&entry.name)))
            .collect();
        let mut rows = Vec::new();
        if sessions && agents.len() > 1 {
            let picks = agents
                .into_iter()
                .enumerate()
                .map(|(at, (name, icon))| {
                    let icon = icon.unwrap_or_else(|| icons::social::MessageCircle.into());
                    let pane = pane.clone();
                    menu::row(
                        Item::action(name).with_icon(icon),
                        move |this, window, cx| {
                            this.new_in_pane(&pane, project, New::Session(at), window, cx)
                        },
                    )
                })
                .collect();
            rows.push(menu::submenu(
                "New session",
                icons::social::MessageCirclePlus,
                picks,
            ));
        } else if sessions && agents.len() == 1 {
            let pane = pane.clone();
            rows.push(menu::row(
                Item::action("New session").with_icon(icons::social::MessageCirclePlus),
                move |this, window, cx| {
                    this.new_in_pane(&pane, project, New::Session(0), window, cx)
                },
            ));
        }
        for (shown, label, icon, kind) in [
            (
                boards,
                "New board",
                icons::Icon::from(icons::development::SquareKanban),
                New::Board,
            ),
            (
                true,
                "New article",
                icons::files::FilePlus.into(),
                New::Article,
            ),
            (tables, "New table", icons::files::Table2.into(), New::Table),
        ] {
            if !shown {
                continue;
            }
            let pane = pane.clone();
            rows.push(menu::row(
                Item::action(label).with_icon(icon),
                move |this, window, cx| this.new_in_pane(&pane, project, kind, window, cx),
            ));
        }
        let id = SharedString::from(format!("pane-add-card-{key}"));
        Some(popover::anchored_menu_below(
            id.clone(),
            self.menu_card(id, rows, window, cx),
            None,
        ))
    }

    /// Make an entry in `project` and open it as the front tab of `pane`.
    fn new_in_pane(
        &mut self,
        pane: &Member,
        project: usize,
        kind: New,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.commit(cx);
        if let New::Board = kind {
            return self.ask_new_board_into(project, Some(pane.clone()), window, cx);
        }
        let member = self.workspace.update(cx, |workspace, cx| {
            workspace.select_project(project, cx);
            let showing = match kind {
                New::Session(at) => {
                    let agent = workspace.settings.agents.get(at).cloned()?;
                    let id = workspace.new_session(agent, None, cx)?;
                    // A space names its members by file, and a new session
                    // has none until its first turn.
                    workspace.retain_session(id, cx)?;
                    Showing::Session(id)
                }
                New::Article => Showing::Article(workspace.new_article(cx)?),
                New::Table => Showing::Table(workspace.new_table(cx)?),
                New::Board => return None,
            };
            workspace.member_of(project, showing)
        });
        if let Some(member) = member {
            self.add_tab(pane, member, window, cx);
        }
    }

    /// Put the seam after `at` where the pointer left it.
    fn move_seam(&mut self, path: &[usize], at: usize, fraction: f64, cx: &mut Context<Self>) {
        self.workspace.update(cx, |workspace, cx| {
            let Some(space) = workspace.active_space_mut() else {
                return;
            };
            let Some(split) = space.tree.at_path_mut(path) else {
                return;
            };
            if split.resize(at, fraction, MIN_SHARE) {
                cx.notify();
            }
        });
    }
}

/// The half of the pane a release would give the arrival.
fn landing_mark(landing: Landing, theme: &Theme) -> AnyElement {
    let mark = div().absolute().bg(theme.text_muted.opacity(0.28));
    match landing {
        // The bar's own row rather than half the pane: what a drop there makes
        // is a tab, and shading half the window would promise a seam.
        Landing::Bar => mark
            .top_0()
            .left_0()
            .right_0()
            .h(px(crate::view::root::HEADER_HEIGHT)),
        Landing::Edge(Side::Left) => mark.left_0().top_0().bottom_0().w(relative(HALF)),
        Landing::Edge(Side::Right) => mark.right_0().top_0().bottom_0().w(relative(HALF)),
        Landing::Edge(Side::Above) => mark.top_0().left_0().right_0().h(relative(HALF)),
        Landing::Edge(Side::Below) => mark.bottom_0().left_0().right_0().h(relative(HALF)),
    }
    .into_any_element()
}

/// A member as something that can be an element id: which project, and which
/// of its things. Two projects can hold the same id, so the path is part of
/// it.
fn key_of(member: &Member) -> SharedString {
    SharedString::from(format!(
        "{}::{:?}::{}",
        member.project.display(),
        member.kind,
        member.id
    ))
}

/// A seam's place in the window, as something that can be an element id.
fn seam_id(path: &[usize], at: usize) -> usize {
    path.iter()
        .fold(1usize, |id, step| id.wrapping_mul(31).wrapping_add(*step))
        .wrapping_mul(31)
        .wrapping_add(at)
}

/// The pane one entry is read in.
fn pane_of(showing: Showing) -> Pane {
    match showing {
        Showing::Session(_) => Pane::Chat,
        Showing::Board(_) => Pane::Board,
        Showing::Article(_) => Pane::Article,
        Showing::Table(_) => Pane::Table,
    }
}

#[cfg(test)]
#[path = "../../tests/unit/open_entries.rs"]
mod open_entry_tests;

/// The pane at a tree's top right: the last of a row, the first of a column.
fn top_right(node: &Node<Member>) -> Option<Member> {
    match node {
        Node::Leaf { entry, .. } => Some(entry.clone()),
        Node::Split { axis, children, .. } => match axis {
            Split::Horizontal => children.last(),
            Split::Vertical => children.first(),
        }
        .and_then(top_right),
    }
}