Skip to main content

egui_pop_views/tree/
mod.rs

1//! A live tree over a source the application implements.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! - **Lazy, asynchronous**: a branch's children are asked for the
7//!   first time it is expanded ([`TreeSource::load`]); the source
8//!   answers now or later, from any thread, through the [`Sink`] it is
9//!   given. Meanwhile the branch shows a loading row; a failure shows
10//!   the reason and a retry button.
11//! - **Live**: the application inserts, removes, moves, renames or
12//!   reloads nodes at any time through a [`TreeHandle`]; the selection
13//!   and the expansion are keyed by node, so they survive.
14//! - **Selection** (single or multiple), **keyboard** (arrows,
15//!   Page Up/Down, Home/End, Left/Right to close, open or move to the
16//!   parent, Space, Ctrl+A, Enter, F2, type-ahead), **drag and drop**
17//!   (before, after or inside a node), **rename in place**.
18//! - **Rows** are [list items](crate::item): an icon
19//!   ([`TreeView::icon`]), weak text on the right ([`TreeView::trailing`]),
20//!   action buttons shown on hover ([`TreeView::actions`]), indent guides
21//!   ([`TreeView::guides`]) and widgets of the application's at their
22//!   right end ([`TreeView::row_widgets`]) that act on their row without
23//!   selecting it, and a context menu for the row clicked
24//!   ([`TreeView::context_menu`], [`TreeView::context_ui`]).
25//! - **Virtualised**: rows are flattened once per change and only the
26//!   rows in view are built, so 100 000 nodes cost a screenful.
27//! - Each moment is a step (`tree.load`, `tree.expand`, `tree.select`,
28//!   `tree.drop`, `tree.rename`, `tree.activate`, `tree.context`, see
29//!   [`crate::steps`]) and a [`Signal`] in the output.
30//!
31//! ```
32//! use egui_pop_views::tree::{Node, Sink, TreeSource, TreeState, TreeView};
33//!
34//! /// Folders named by their path, two levels deep.
35//! struct Folders;
36//!
37//! impl TreeSource<String> for Folders {
38//!     fn load(&self, parent: Option<&String>, sink: Sink<String>) {
39//!         // A real source answers from a thread.
40//!         let base = parent.cloned().unwrap_or_default();
41//!         let depth = base.matches('/').count();
42//!         sink.deliver(
43//!             (0..3)
44//!                 .map(|i| {
45//!                     let key = format!("{base}/{i}");
46//!                     if depth < 1 { Node::branch(key, format!("Folder {i}")) } else { Node::leaf(key, format!("File {i}")) }
47//!                 })
48//!                 .collect(),
49//!         );
50//!     }
51//! }
52//!
53//! fn ui(ui: &mut egui::Ui, state: &mut TreeState<String>) {
54//!     let out = TreeView::new("folders").label("Folders").show(ui, state, &Folders);
55//!     for signal in out.signals {
56//!         // Apply drops and renames to the application's data...
57//!         let _ = signal;
58//!     }
59//! }
60//! ```
61
62pub mod filter;
63pub mod model;
64
65use std::sync::{Arc, Mutex};
66
67use crate::app_link::AppHandle;
68use crate::app_link::Outcome;
69use crate::shared::SelectionService;
70use egui::{
71    Context, Id, Modifiers, Rect, Response, Role, TextEdit, Ui, UiBuilder, WidgetInfo, pos2, vec2,
72};
73#[cfg(feature = "api")]
74use egui_pop_api::menus;
75use egui_pop_core::icon::Source;
76use egui_pop_core::kit::{KitCx, Part, State, Tone};
77use egui_pop_core::strings::{self, tr, tr_args};
78use egui_pop_core::theme::Tokens;
79use egui_pop_model::ids::{MenuId, StepId};
80use egui_pop_model::selection::SelectionItem;
81use serde_json::{Value as Json, json};
82
83pub use filter::{FilterField, Query};
84pub use model::{Children, Edit, Model, Node, Position, Row};
85
86use crate::item::{self, Disclosure, ItemAction};
87use crate::nav::{self, Nav, TypeAhead};
88use crate::rows::{self, Scroll};
89use crate::select::{Key, Mode, Proposal, Selection};
90use crate::shared;
91use crate::steps::{
92    self, TREE_ACTION, TREE_ACTIVATE, TREE_CONTEXT, TREE_DROP, TREE_EXPAND, TREE_LOAD, TREE_RENAME,
93    TREE_SELECT,
94};
95use crate::strings as s;
96
97/// What the application implements: a branch's children, on demand.
98pub trait TreeSource<K: Key> {
99    /// Asks for the children of `parent` (`None`: the roots). Answer
100    /// through `sink` now or later, from any thread. Not called again
101    /// for that branch until it is reloaded.
102    fn load(&self, parent: Option<&K>, sink: Sink<K>);
103
104    /// Whether `keys` may be dropped `position` of `target`: `Err` with
105    /// the reason refuses it. Asked while dragging (a refused target is
106    /// marked so) and by `tree.drop`'s default, after the step's hooks;
107    /// the view's own veto ([`TreeView::can_drop`]) is asked too. By
108    /// default every drop is allowed.
109    fn can_drop(&self, keys: &[K], target: &K, position: Position) -> Result<(), String> {
110        let _ = (keys, target, position);
111        Ok(())
112    }
113
114    /// What the filter searches for a node ([`TreeState::set_filter`]):
115    /// by default its plain name ([`Node::name`]). Add words the label
116    /// does not show (a description, tags, a path) after the name; the
117    /// row highlights what matches in its label only.
118    fn match_text(&self, node: &Node<K>) -> String {
119        node.name().to_string()
120    }
121
122    /// A node's item in the application-wide selection
123    /// ([`TreeView::shared`]): by default its key's
124    /// ([`SelectionItem::from_key`]). Give the id other widgets showing
125    /// the same thing use.
126    fn item(&self, key: &K) -> SelectionItem {
127        SelectionItem::from_key(key)
128    }
129}
130
131/// How many edits wait at most for a tree's next pass. A tree its host
132/// no longer draws (a tab behind another) still receives its source's
133/// and the application's edits; past this many, they are dropped and
134/// the tree loads every branch again at its next pass
135/// ([`TreeState::dropped`] counts them, and a `tree.overflowed` event
136/// says so on the journal when the view has the application).
137pub const EDITS_WAITING: usize = 4096;
138
139struct Inbox<K> {
140    edits: Vec<Edit<K>>,
141    ctx: Option<Context>,
142    /// Edits were dropped: every branch is loaded again.
143    overflowed: bool,
144    /// Edits dropped since the tree was made.
145    dropped: u64,
146}
147
148/// The application's hand on a tree's view: edits from any thread,
149/// applied at the next pass (which they wake).
150pub struct TreeHandle<K> {
151    inbox: Arc<Mutex<Inbox<K>>>,
152}
153
154impl<K> Clone for TreeHandle<K> {
155    fn clone(&self) -> Self {
156        Self {
157            inbox: self.inbox.clone(),
158        }
159    }
160}
161
162impl<K> std::fmt::Debug for TreeHandle<K> {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        f.write_str("TreeHandle")
165    }
166}
167
168impl<K> TreeHandle<K> {
169    fn push(&self, edit: Edit<K>) {
170        let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
171        if inbox.edits.len() >= EDITS_WAITING {
172            // Not drawn for long: the waiting edits and this one give way
173            // to loading everything again.
174            inbox.dropped += inbox.edits.len() as u64 + 1;
175            inbox.edits = Vec::new();
176            inbox.overflowed = true;
177        } else {
178            inbox.edits.push(edit);
179        }
180        if let Some(ctx) = &inbox.ctx {
181            ctx.request_repaint();
182        }
183    }
184
185    /// A node under `parent` at `index` (`None`: last). Under a branch
186    /// not loaded yet it is left out: it comes with the branch.
187    pub fn insert(&self, parent: Option<K>, index: Option<usize>, node: Node<K>) {
188        self.push(Edit::Insert {
189            parent,
190            index,
191            node,
192        });
193    }
194
195    /// A node and what is under it.
196    pub fn remove(&self, key: K) {
197        self.push(Edit::Remove(key));
198    }
199
200    /// A node to another place (a move into itself is refused).
201    pub fn move_to(&self, key: K, parent: Option<K>, index: Option<usize>) {
202        self.push(Edit::Move { key, parent, index });
203    }
204
205    pub fn rename(&self, key: K, label: impl Into<String>) {
206        self.push(Edit::Rename {
207            key,
208            label: label.into(),
209        });
210    }
211
212    /// A node's label, name and kind.
213    pub fn update(&self, node: Node<K>) {
214        self.push(Edit::Update(node));
215    }
216
217    /// Loads a branch again (`None`: the roots); its children stay on
218    /// screen until the new ones come.
219    pub fn reload(&self, parent: Option<K>) {
220        self.push(Edit::Reload(parent));
221    }
222
223    /// Sets a branch's children directly (a source that replaced the
224    /// `tree.load` step answers this way).
225    pub fn set_children(&self, parent: Option<K>, result: Result<Vec<Node<K>>, String>) {
226        self.push(Edit::Children {
227            parent,
228            ticket: None,
229            result,
230        });
231    }
232}
233
234/// Where a source answers one request.
235#[derive(Debug)]
236pub struct Sink<K> {
237    handle: TreeHandle<K>,
238    parent: Option<K>,
239    ticket: u64,
240}
241
242impl<K> Sink<K> {
243    /// The branch asked for (`None`: the roots).
244    pub fn parent(&self) -> Option<&K> {
245        self.parent.as_ref()
246    }
247
248    /// The branch's children, in order.
249    pub fn deliver(self, children: Vec<Node<K>>) {
250        self.answer(Ok(children));
251    }
252
253    /// The branch could not be loaded.
254    pub fn fail(self, reason: impl Into<String>) {
255        self.answer(Err(reason.into()));
256    }
257
258    fn answer(self, result: Result<Vec<Node<K>>, String>) {
259        self.handle.push(Edit::Children {
260            parent: self.parent,
261            ticket: Some(self.ticket),
262            result,
263        });
264    }
265}
266
267#[derive(Clone, Debug)]
268struct Renaming<K> {
269    key: K,
270    text: String,
271    focus: bool,
272}
273
274#[derive(Clone, Debug)]
275struct Drag<K> {
276    keys: Vec<K>,
277    /// The drop the pointer points at (refused ones too: their step
278    /// says why).
279    target: Option<(K, Position)>,
280}
281
282/// A tree's state between passes: the cache, the selection, where it is
283/// scrolled.
284pub struct TreeState<K: Key> {
285    model: Model<K>,
286    selection: Selection<K>,
287    inbox: Arc<Mutex<Inbox<K>>>,
288    scroll: Scroll,
289    type_ahead: TypeAhead,
290    renaming: Option<Renaming<K>>,
291    drag: Option<Drag<K>>,
292    /// The row last right-clicked, and the node its menu is for.
293    context: Option<(K, K)>,
294    /// A selection waiting for nodes not loaded yet.
295    pending: Option<(Vec<K>, Option<K>)>,
296    /// A node to bring into view at the next pass.
297    reveal: Option<K>,
298    /// The filter as typed, and its words.
299    filter: String,
300    query: Query,
301    /// The query changed since the matches were last computed.
302    filter_fresh: bool,
303    /// The model's version the matches were computed for.
304    filtered_at: Option<u64>,
305    /// The filter field drawn with the tree, if any.
306    pub(crate) field: Option<Id>,
307    /// The field takes the focus at its next draw.
308    pub(crate) field_focus: bool,
309    /// The tree takes the focus at its next draw.
310    pub(crate) focus_tree: bool,
311    /// The flattening last reported to agents.
312    pub(crate) reported: Option<u64>,
313    /// The shared selection's revision and the model's version last
314    /// followed.
315    seen: Option<(u64, u64)>,
316}
317
318impl<K: Key> Default for TreeState<K> {
319    fn default() -> Self {
320        Self {
321            model: Model::default(),
322            selection: Selection::default(),
323            inbox: Arc::new(Mutex::new(Inbox {
324                edits: Vec::new(),
325                ctx: None,
326                overflowed: false,
327                dropped: 0,
328            })),
329            scroll: Scroll::default(),
330            type_ahead: TypeAhead::default(),
331            renaming: None,
332            drag: None,
333            context: None,
334            pending: None,
335            reveal: None,
336            filter: String::new(),
337            query: Query::default(),
338            filter_fresh: false,
339            filtered_at: None,
340            field: None,
341            field_focus: false,
342            focus_tree: false,
343            reported: None,
344            seen: None,
345        }
346    }
347}
348
349impl<K: Key> std::fmt::Debug for TreeState<K> {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        f.debug_struct("TreeState")
352            .field("nodes", &self.model.len())
353            .field("rows", &self.model.rows_now().len())
354            .field("selection", &self.selection)
355            .finish()
356    }
357}
358
359impl<K: Key> TreeState<K> {
360    pub fn new() -> Self {
361        Self::default()
362    }
363
364    /// The application's hand on the view: edits from any thread.
365    pub fn handle(&self) -> TreeHandle<K> {
366        TreeHandle {
367            inbox: self.inbox.clone(),
368        }
369    }
370
371    pub fn selection(&self) -> &Selection<K> {
372        &self.selection
373    }
374
375    /// Sets the selection without running a step (restoring a saved
376    /// state, following another view). Nodes the view has not loaded yet
377    /// (under a branch not opened, or still loading) are queued: the
378    /// selection takes each as it loads, and once all have come the
379    /// cursor's row is brought into view. Open their ancestors
380    /// ([`TreeState::set_expanded`]) so that they load. The user
381    /// selecting, or another call, drops what was queued.
382    pub fn set_selection(&mut self, keys: impl IntoIterator<Item = K>, cursor: Option<K>) {
383        self.pending = Some((keys.into_iter().collect(), cursor));
384        self.settle(false);
385    }
386
387    /// The selection queued by [`TreeState::set_selection`] for nodes
388    /// not loaded yet.
389    pub fn pending_selection(&self) -> Option<(&[K], Option<&K>)> {
390        self.pending
391            .as_ref()
392            .map(|(k, c)| (k.as_slice(), c.as_ref()))
393    }
394
395    /// What the view knows: nodes, children, expansion, rows.
396    pub fn model(&self) -> &Model<K> {
397        &self.model
398    }
399
400    /// Opens or closes a branch without running a step (restoring a
401    /// saved state).
402    pub fn set_expanded(&mut self, key: &K, expanded: bool) {
403        self.model.set_expanded(key, expanded);
404    }
405
406    /// Starts renaming a node in place, from its plain name
407    /// ([`Node::name`]).
408    pub fn rename(&mut self, key: &K) {
409        if let Some(n) = self.model.node(key) {
410            self.renaming = Some(Renaming {
411                key: key.clone(),
412                text: n.name().to_string(),
413                focus: true,
414            });
415        }
416    }
417
418    /// Brings a node's row into view at the next pass, if its row is
419    /// there by then (open its ancestors first).
420    pub fn reveal(&mut self, key: &K) {
421        self.reveal = Some(key.clone());
422    }
423
424    /// Filters the tree (empty: no filter), from its next draw: the nodes
425    /// matching every word ([the filter](crate::tree::filter) says how) show with their
426    /// ancestors, the rest is hidden, and the cursor goes to the first
427    /// match when its row hides. A [`FilterField`] types it.
428    pub fn set_filter(&mut self, text: impl Into<String>) {
429        let text = text.into();
430        if text != self.filter {
431            self.query = Query::new(&text);
432            self.filter = text;
433            self.filter_fresh = true;
434        }
435    }
436
437    /// The filter as typed.
438    pub fn filter(&self) -> &str {
439        &self.filter
440    }
441
442    /// While the tree filters: how many nodes match, and how many it has
443    /// loaded.
444    pub fn filter_count(&self) -> Option<(usize, usize)> {
445        self.model.matches().map(|n| (n, self.model.len()))
446    }
447
448    /// Computes the matches again when the query or the nodes changed;
449    /// returns whether the query did.
450    fn refilter(&mut self, source: &dyn TreeSource<K>) -> bool {
451        let fresh = std::mem::take(&mut self.filter_fresh);
452        if !fresh && self.filtered_at == Some(self.model.version()) {
453            return false;
454        }
455        self.filtered_at = Some(self.model.version());
456        let matched = (!self.query.is_empty()).then(|| {
457            self.model
458                .nodes()
459                .filter(|n| self.query.matches(&source.match_text(n)))
460                .map(|n| n.key.clone())
461                .collect()
462        });
463        self.model.set_matches(matched, fresh);
464        if fresh {
465            self.model.rows();
466            let cursor = self.selection.cursor().cloned();
467            if self.query.is_empty() {
468                // Back to the whole tree: where the cursor was.
469                self.reveal = cursor;
470            } else if cursor.as_ref().and_then(|c| self.row_of(c)).is_none() {
471                let first = self
472                    .model
473                    .rows_now()
474                    .iter()
475                    .filter_map(Row::key)
476                    .find(|k| self.model.is_match(k))
477                    .cloned();
478                if let Some(k) = &first {
479                    self.reveal = Some(k.clone());
480                }
481                if first.is_some() {
482                    self.selection.set_cursor(first);
483                }
484            }
485        }
486        fresh
487    }
488
489    /// Whether a node is being renamed.
490    pub fn renaming(&self) -> Option<&K> {
491        self.renaming.as_ref().map(|r| &r.key)
492    }
493
494    /// Selects what is known of the queued selection; once all of it
495    /// is known, it is no longer queued (and its cursor is brought into
496    /// view if `reveal`).
497    fn settle(&mut self, reveal: bool) {
498        let Some((keys, cursor)) = &self.pending else {
499            return;
500        };
501        let model = &self.model;
502        let known: Vec<K> = keys.iter().filter(|k| model.contains(k)).cloned().collect();
503        let at = cursor.clone().filter(|c| model.contains(c));
504        let complete = known.len() == keys.len() && at.is_some() == cursor.is_some();
505        self.selection.set(known, at.clone());
506        if complete {
507            self.pending = None;
508            if reveal {
509                self.reveal = at;
510            }
511        }
512    }
513
514    /// Edits dropped since the tree was made: they waited past
515    /// [`EDITS_WAITING`] while the tree was not drawn, and every branch
516    /// was loaded again instead.
517    pub fn dropped(&self) -> u64 {
518        self.inbox.lock().unwrap_or_else(|e| e.into_inner()).dropped
519    }
520
521    /// Edits waiting for the next pass (at most [`EDITS_WAITING`]).
522    pub fn waiting(&self) -> usize {
523        self.inbox
524            .lock()
525            .unwrap_or_else(|e| e.into_inner())
526            .edits
527            .len()
528    }
529
530    /// Applies the edits waiting (loading every branch again when edits
531    /// were dropped); returns whether there were any.
532    fn drain(&mut self) -> bool {
533        let (edits, overflowed) = {
534            let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
535            (
536                std::mem::take(&mut inbox.edits),
537                std::mem::take(&mut inbox.overflowed),
538            )
539        };
540        if overflowed {
541            self.model.reload_all();
542        }
543        let any = !edits.is_empty() || overflowed;
544        let cursor_at = self
545            .selection
546            .cursor()
547            .and_then(|c| self.row_of(c))
548            .unwrap_or(0);
549        for e in edits {
550            self.model.apply(e);
551        }
552        if any {
553            let model = &self.model;
554            let had_cursor = self.selection.cursor().is_some();
555            self.selection.retain(|k| model.contains(k));
556            // Nodes a queued selection waited for may have come.
557            let queued = self.pending.is_some();
558            self.settle(true);
559            if self
560                .renaming
561                .as_ref()
562                .is_some_and(|r| !self.model.contains(&r.key))
563            {
564                self.renaming = None;
565            }
566            // The cursor's node went: the cursor stays where it was.
567            if had_cursor && !queued && self.selection.cursor().is_none() {
568                let rows = self.model.rows();
569                let near = (0..rows.len())
570                    .map(|d| cursor_at.saturating_sub(d).min(rows.len() - 1))
571                    .find_map(|i| rows[i].key().cloned());
572                self.selection.set_cursor(near);
573            }
574        }
575        any
576    }
577
578    fn row_of(&self, key: &K) -> Option<usize> {
579        self.model
580            .rows_now()
581            .iter()
582            .position(|r| r.key() == Some(key))
583    }
584}
585
586/// What happened in a tree this pass.
587#[derive(Clone, Debug, PartialEq)]
588pub enum Signal<K> {
589    /// A branch's children were asked for (`None`: the roots).
590    Load {
591        key: Option<K>,
592    },
593    Expand {
594        key: K,
595        expanded: bool,
596    },
597    Select {
598        keys: Vec<K>,
599        cursor: Option<K>,
600    },
601    /// Nodes dropped; the view moved them, the application moves them in
602    /// its data.
603    Drop {
604        keys: Vec<K>,
605        target: K,
606        position: Position,
607    },
608    /// A node renamed (`from` and `to` are plain names, [`Node::name`]);
609    /// the view shows the new name (a node with a name of its own keeps
610    /// its label until the application updates it), the application
611    /// renames it in its data.
612    Rename {
613        key: K,
614        from: String,
615        to: String,
616    },
617    /// A leaf opened (Enter, double click).
618    Activate {
619        key: K,
620    },
621    /// A row's context menu opened (a right click), for that node; the
622    /// selection is left as it is.
623    Context {
624        key: K,
625    },
626    /// A step was vetoed.
627    Vetoed {
628        step: StepId,
629        reason: String,
630    },
631}
632
633/// What [`TreeView::show`] returns.
634#[derive(Debug)]
635pub struct TreeOutput<K> {
636    /// The tree as one focusable widget.
637    pub response: Response,
638    pub signals: Vec<Signal<K>>,
639}
640
641enum Action<K> {
642    Load(Option<K>),
643    Expand(K, bool),
644    Select(Proposal<K>),
645    Drop(Vec<K>, K, Position),
646    Rename(K, String),
647    Activate(K),
648}
649
650/// What draws a row's icon.
651type IconFn<'a, K> = Box<dyn Fn(&Node<K>) -> Option<Source> + 'a>;
652/// What allows a drop, or refuses it with the reason.
653type Allows<'a, K> = dyn Fn(&[K], &K, Position) -> Result<(), String> + 'a;
654/// What refuses a drop at the call site.
655type DropFn<'a, K> = Box<Allows<'a, K>>;
656/// What adds a row's widgets, or fills its context menu.
657type RowFn<'a, K> = Box<dyn FnMut(&mut Ui, &Node<K>) + 'a>;
658/// What gives a row's trailing text.
659type TrailingFn<'a, K> = Box<dyn Fn(&Node<K>) -> Option<String> + 'a>;
660/// What gives a row's action buttons.
661type ActionsFn<'a, K> = Box<dyn Fn(&Node<K>) -> Vec<ItemAction> + 'a>;
662/// What follows an action clicked on a row.
663type OnActionFn<'a, K> = Box<dyn FnMut(&K, &str) + 'a>;
664
665/// A row's context menu.
666enum ContextMenu<'a, K> {
667    /// Declared, with its commands.
668    #[cfg_attr(
669        not(feature = "api"),
670        allow(dead_code, reason = "only the api feature builds declared menus")
671    )]
672    Declared(&'a AppHandle, MenuId),
673    /// Drawn by the application.
674    Ui(RowFn<'a, K>),
675}
676
677/// The tree widget.
678///
679/// Need (data): a tree, lazy and keyboard-driven.
680pub struct TreeView<'a, K: Key> {
681    id: String,
682    label: Option<String>,
683    mode: Mode,
684    app: Option<&'a AppHandle>,
685    drag_drop: bool,
686    rename: bool,
687    activate_on_click: bool,
688    height: Option<f32>,
689    icon: Option<IconFn<'a, K>>,
690    guides: bool,
691    trailing: Option<TrailingFn<'a, K>>,
692    actions: Option<ActionsFn<'a, K>>,
693    on_action: Option<OnActionFn<'a, K>>,
694    row_widgets: Option<RowFn<'a, K>>,
695    context: Option<ContextMenu<'a, K>>,
696    can_drop: Option<DropFn<'a, K>>,
697    shared: Option<&'a SelectionService>,
698}
699
700impl<K: Key> std::fmt::Debug for TreeView<'_, K> {
701    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
702        f.debug_struct("TreeView")
703            .field("id", &self.id)
704            .field("label", &self.label)
705            .field("mode", &self.mode)
706            .field("app", &self.app.is_some())
707            .field("drag_drop", &self.drag_drop)
708            .field("rename", &self.rename)
709            .field("activate_on_click", &self.activate_on_click)
710            .field("height", &self.height)
711            .field("icon", &self.icon.is_some())
712            .field("guides", &self.guides)
713            .field("trailing", &self.trailing.is_some())
714            .field("actions", &self.actions.is_some())
715            .field("on_action", &self.on_action.is_some())
716            .field("row_widgets", &self.row_widgets.is_some())
717            .field("context", &self.context.is_some())
718            .field("can_drop", &self.can_drop.is_some())
719            .field("shared", &self.shared.is_some())
720            .finish()
721    }
722}
723
724impl<'a, K: Key> TreeView<'a, K> {
725    /// A tree named `id` in steps and signals.
726    pub fn new(id: impl Into<String>) -> Self {
727        Self {
728            id: id.into(),
729            label: None,
730            mode: Mode::Single,
731            app: None,
732            drag_drop: false,
733            rename: false,
734            activate_on_click: false,
735            height: None,
736            icon: None,
737            guides: false,
738            trailing: None,
739            actions: None,
740            on_action: None,
741            row_widgets: None,
742            context: None,
743            can_drop: None,
744            shared: None,
745        }
746    }
747
748    /// Its accessible name.
749    pub fn label(mut self, label: impl Into<String>) -> Self {
750        self.label = Some(label.into());
751        self
752    }
753
754    pub fn mode(mut self, mode: Mode) -> Self {
755        self.mode = mode;
756        self
757    }
758
759    /// Runs its moments as steps of this application.
760    #[cfg(feature = "api")]
761    pub fn app(mut self, app: &'a AppHandle) -> Self {
762        self.app = Some(app);
763        self
764    }
765
766    /// Binds the tree to the application-wide selection
767    /// (`egui_pop_api::selection`, the service under `SELECTION`): its
768    /// loaded nodes ([`TreeSource::item`]) show selected and hovered when
769    /// they are so anywhere, and what it selects (still through
770    /// `tree.select`) goes there: a plain click or move replaces the whole
771    /// selection, Ctrl changes only the tree's items. The tree is then in
772    /// the selection's focus surface, where Alt+Left and Alt+Right walk
773    /// its history.
774    #[cfg(feature = "api")]
775    pub fn shared(mut self, selection: &'a SelectionService) -> Self {
776        self.shared = Some(selection);
777        self
778    }
779
780    /// Nodes may be dragged and dropped (`tree.drop` decides).
781    pub fn drag_drop(mut self, on: bool) -> Self {
782        self.drag_drop = on;
783        self
784    }
785
786    /// Refuses drops here, in addition to the source's
787    /// ([`TreeSource::can_drop`]) and to `tree.drop`'s hooks: `Err` with
788    /// the reason. A refused target is marked while dragging; dropped
789    /// there, `tree.drop`'s default refuses it and the output carries
790    /// [`Signal::Vetoed`] with the reason.
791    pub fn can_drop(
792        mut self,
793        allow: impl Fn(&[K], &K, Position) -> Result<(), String> + 'a,
794    ) -> Self {
795        self.can_drop = Some(Box::new(allow));
796        self
797    }
798
799    /// Whether the source and the view allow a drop.
800    fn allows(
801        &self,
802        source: &dyn TreeSource<K>,
803        keys: &[K],
804        target: &K,
805        position: Position,
806    ) -> Result<(), String> {
807        source.can_drop(keys, target, position)?;
808        match &self.can_drop {
809            Some(allow) => allow(keys, target, position),
810            None => Ok(()),
811        }
812    }
813
814    /// Nodes may be renamed in place (F2).
815    pub fn rename(mut self, on: bool) -> Self {
816        self.rename = on;
817        self
818    }
819
820    /// A click acts as Enter does: a leaf opens (`tree.activate`), a
821    /// branch opens or closes. For a tree that navigates, whose rows are
822    /// its links; the second click of a double click adds nothing.
823    pub fn activate_on_click(mut self, on: bool) -> Self {
824        self.activate_on_click = on;
825        self
826    }
827
828    /// Its height (default: what is available).
829    pub fn height(mut self, height: f32) -> Self {
830        self.height = Some(height);
831        self
832    }
833
834    /// Each row's icon, between the triangle and the label (`None`: no
835    /// icon on that row), drawn in the row's text colour at the inline
836    /// icon size. A name of the icon vocabulary is given with
837    /// `Source::named` (`"folder"`, `"phosphor:image"`); the icon each row
838    /// shows is reported to agents (the `icons` collector's `drawn`).
839    pub fn icon(mut self, icon: impl Fn(&Node<K>) -> Option<Source> + 'a) -> Self {
840        self.icon = Some(Box::new(icon));
841        self
842    }
843
844    /// Draws a guide down each row for each of its levels (the kit's
845    /// `list-guide`).
846    pub fn guides(mut self, on: bool) -> Self {
847        self.guides = on;
848        self
849    }
850
851    /// Each row's weak text on its right (a count, a type; `None`: none),
852    /// in the row's muted tone, before its actions and widgets.
853    pub fn trailing(mut self, text: impl Fn(&Node<K>) -> Option<String> + 'a) -> Self {
854        self.trailing = Some(Box::new(text));
855        self
856    }
857
858    /// Each row's action buttons (a visibility eye, remove), right to left
859    /// before its widgets: shown on the row under the pointer, the
860    /// selected rows and the cursor's row while the tree has the focus,
861    /// pinned ones always. A click runs `tree.action`, then
862    /// [`TreeView::on_action`]; it does not select the row. Tab from the
863    /// tree reaches the cursor's buttons ([the keyboard](crate::item#keyboard)),
864    /// and screen readers find them on the row as custom actions.
865    pub fn actions(mut self, actions: impl Fn(&Node<K>) -> Vec<ItemAction> + 'a) -> Self {
866        self.actions = Some(Box::new(actions));
867        self
868    }
869
870    /// Called with the row's key and the action's id when an action
871    /// button was clicked and `tree.action` was not vetoed.
872    pub fn on_action(mut self, act: impl FnMut(&K, &str) + 'a) -> Self {
873        self.on_action = Some(Box::new(act));
874        self
875    }
876
877    /// Widgets at each row's right end, added right to left (a
878    /// visibility toggle, a lock): they act on their row without
879    /// selecting it, and the label is cut before them. Called for the
880    /// rows in view only, in an `Ui` whose ids are the row's own.
881    pub fn row_widgets(mut self, widgets: impl FnMut(&mut Ui, &Node<K>) + 'a) -> Self {
882        self.row_widgets = Some(Box::new(widgets));
883        self
884    }
885
886    /// A declared menu (`Ctx::menu_item`, commands) opened on a row's
887    /// right click, for that row: `{"tree": id, "key": key}` is merged
888    /// into its commands' arguments and seen by their `when` clauses as
889    /// `args.key`, whatever is selected. It runs `tree.context`, then
890    /// `menu.open`.
891    #[cfg(feature = "api")]
892    pub fn context_menu(mut self, app: &'a AppHandle, menu: MenuId) -> Self {
893        self.context = Some(ContextMenu::Declared(app, menu));
894        self
895    }
896
897    /// A context menu the application draws, opened on a row's right
898    /// click and given that row's node, whatever is selected. It runs
899    /// `tree.context`.
900    pub fn context_ui(mut self, menu: impl FnMut(&mut Ui, &Node<K>) + 'a) -> Self {
901        self.context = Some(ContextMenu::Ui(Box::new(menu)));
902        self
903    }
904
905    /// Draws the tree; runs what the user did as steps.
906    pub fn show(
907        self,
908        ui: &mut Ui,
909        state: &mut TreeState<K>,
910        source: &dyn TreeSource<K>,
911    ) -> TreeOutput<K> {
912        shared::surface(ui, self.shared.is_some(), |ui| {
913            // With a filter field, its keys are bound on the tree's surface.
914            if state.field.is_some() {
915                egui_pop_core::focus::scope(ui, filter::SURFACE, &[], |ui| {
916                    self.draw(ui, state, source)
917                })
918            } else {
919                self.draw(ui, state, source)
920            }
921        })
922    }
923
924    fn draw(
925        mut self,
926        ui: &mut Ui,
927        state: &mut TreeState<K>,
928        source: &dyn TreeSource<K>,
929    ) -> TreeOutput<K> {
930        let id = Id::unique(("egui_pop_views::tree", &self.id));
931        state
932            .inbox
933            .lock()
934            .unwrap_or_else(|e| e.into_inner())
935            .ctx
936            .get_or_insert_with(|| ui.ctx().clone());
937        let mut signals = Vec::new();
938        let overflowed = state
939            .inbox
940            .lock()
941            .unwrap_or_else(|e| e.into_inner())
942            .overflowed;
943        state.drain();
944        if overflowed && let Some(app) = self.app {
945            // Not drawn for long, it dropped edits: agents see it.
946            app.publish(
947                "egui_pop.tree",
948                None,
949                "tree.overflowed",
950                json!({ "tree": self.id, "dropped": state.dropped() }),
951            );
952        }
953        // Branches shown expanded and never loaded are asked for, once.
954        for _ in 0..4 {
955            let wanted = state.model.take_wanted();
956            if wanted.is_empty() {
957                break;
958            }
959            for parent in wanted {
960                self.run(state, source, Action::Load(parent), &mut signals);
961            }
962            state.drain();
963        }
964        if state.refilter(source)
965            && let Some((n, total)) = state.filter_count()
966        {
967            egui_pop_core::a11y::announce(
968                ui.ctx(),
969                strings::tr_with(
970                    ui.ctx(),
971                    &s::TREE_FILTER_ANNOUNCE,
972                    &[("count", n.into()), ("total", total.into())],
973                ),
974                egui_pop_core::a11y::Politeness::Polite,
975            );
976        }
977
978        if let Some(service) = self.shared {
979            let version = state.model.version();
980            let TreeState {
981                model,
982                selection,
983                seen,
984                ..
985            } = &mut *state;
986            shared::follow(
987                service,
988                selection,
989                seen,
990                version,
991                model.nodes().map(|n| (n.key.clone(), source.item(&n.key))),
992            );
993        }
994        egui_pop_core::focus::reads_keys(ui.ctx(), id, &nav::READS);
995        let focused = ui.memory(|m| m.has_focus(id));
996        // Ctrl+F or `/` (`tree.filter`) asked for the field.
997        if focused && state.field.is_some() && filter::take_request(ui.ctx()) {
998            state.field_focus = true;
999            ui.ctx().request_repaint();
1000        }
1001        let focus_tree = std::mem::take(&mut state.focus_tree);
1002        let mut actions = Vec::new();
1003        let row_h = rows::height(ui);
1004        if focused && state.renaming.is_none() {
1005            self.keys(ui, state, row_h, &mut actions);
1006        }
1007
1008        if let Some(key) = state.reveal.take() {
1009            state.model.rows();
1010            state.scroll.reveal = state.row_of(&key);
1011        }
1012        let label = self.label.clone().unwrap_or_else(|| tr(ui.ctx(), &s::TREE));
1013        let icon = self.icon.take();
1014        let trailing = self.trailing.take();
1015        let item_actions = self.actions.take();
1016        let focused_id = ui.memory(|m| m.focused());
1017        // The cursor row's actions, drawn after the tree takes its place
1018        // in the Tab order; the actions clicked.
1019        let mut late = None;
1020        let mut clicked: Vec<(K, String)> = Vec::new();
1021        let mut row_widgets = self.row_widgets.take();
1022        let mut context_menu = self.context.take();
1023        let tree = self.id.as_str();
1024        let app = self.app;
1025        state.model.rows();
1026        let TreeState {
1027            model,
1028            selection,
1029            scroll,
1030            renaming,
1031            drag,
1032            context,
1033            query,
1034            ..
1035        } = state;
1036        let count = model.rows_now().len();
1037        // A filter that matches nothing says so in a row.
1038        let no_match = count == 0 && model.is_filtered();
1039        let shown = if no_match { 1 } else { count };
1040        let mut take_focus = false;
1041        let shared = self.shared;
1042        let mut hovering: Option<SelectionItem> = None;
1043        let mut cursor_row = None;
1044        let (_, response, inner) = rows::show(
1045            ui,
1046            id,
1047            &label,
1048            Role::Tree,
1049            scroll,
1050            shown,
1051            row_h,
1052            self.height,
1053            |ui, visible| {
1054                let indent = ui.spacing().indent;
1055                let pointer = ui.input(|i| i.pointer.interact_pos());
1056                for i in visible.range.clone() {
1057                    let rect = (visible.rect_of)(i);
1058                    if no_match {
1059                        pseudo(ui, rect, rect.left() + indent, |ui| {
1060                            ui.weak(tr(ui.ctx(), &s::TREE_FILTER_NONE));
1061                        });
1062                        continue;
1063                    }
1064                    let row = model.rows_now()[i].clone();
1065                    let depth = row.depth();
1066                    let x = rect.left() + depth as f32 * indent;
1067                    match row {
1068                        Row::Node { key, .. } => {
1069                            let node = match model.node(&key) {
1070                                Some(n) => n.clone(),
1071                                None => continue,
1072                            };
1073                            let r = ui.interact(rect, id.with(("row", &key)), rows::ROW_SENSE);
1074                            // The context menu key opens the cursor row's menu.
1075                            let by_key = focused
1076                                && context_menu.is_some()
1077                                && selection.cursor() == Some(&key)
1078                                && egui_pop_core::pointer::claim::menu_key(ui.ctx(), true);
1079                            if by_key || egui_pop_core::pointer::claim::opens_context_menu(&r) {
1080                                *context = open_context(app, tree, &key, &mut signals);
1081                            }
1082                            // The menu, for the node the step settled on.
1083                            if let Some((_, target)) =
1084                                context.as_ref().filter(|(row, _)| *row == key)
1085                            {
1086                                match context_menu.as_mut() {
1087                                    #[cfg(not(feature = "api"))]
1088                                    Some(ContextMenu::Declared(app, _)) => match **app {},
1089                                    #[cfg(feature = "api")]
1090                                    Some(ContextMenu::Declared(app, menu)) => {
1091                                        menus::context_menu_opened(
1092                                            &r,
1093                                            app,
1094                                            menu,
1095                                            json!({ "tree": tree, "key": target }),
1096                                            by_key,
1097                                        );
1098                                    }
1099                                    Some(ContextMenu::Ui(add)) => {
1100                                        if let Some(n) = model.node(target) {
1101                                            egui_pop_core::pointer::claim::context_menu_opened(
1102                                                &r,
1103                                                by_key,
1104                                                |ui| add(ui, n),
1105                                            );
1106                                        }
1107                                    }
1108                                    None => {}
1109                                }
1110                            }
1111                            let selected = selection.contains(&key);
1112                            let cursor = (focused && selection.cursor() == Some(&key))
1113                                || r.context_menu_opened();
1114                            if focused && selection.cursor() == Some(&key) {
1115                                cursor_row = Some(r.id);
1116                            }
1117                            let mut hovered = r.contains_pointer() && drag.is_none();
1118                            // Hovered here, or the same item hovered elsewhere.
1119                            if let Some(service) = shared {
1120                                let item = source.item(&key);
1121                                if hovered {
1122                                    hovering = Some(item);
1123                                } else {
1124                                    hovered = service.is_hovered(&item);
1125                                }
1126                            }
1127                            let row_state = rows::state(
1128                                selected,
1129                                hovered,
1130                                cursor && egui_pop_core::focus::ring_shown(ui.ctx()),
1131                            );
1132                            let source = icon.as_ref().and_then(|f| f(&node));
1133                            let row_actions =
1134                                item_actions.as_ref().map(|f| f(&node)).unwrap_or_default();
1135                            let action_focused = focused_id.is_some_and(|f| {
1136                                (0..row_actions.len()).any(|k| item::action_id(r.id, k) == f)
1137                            });
1138                            let at_cursor =
1139                                selection.cursor() == Some(&key) && (focused || action_focused);
1140                            let revealed =
1141                                (r.contains_pointer() && drag.is_none()) || selected || at_cursor;
1142                            let placed = item::Frame {
1143                                kit: visible.kit,
1144                                state: row_state,
1145                                depth,
1146                                guides: self.guides,
1147                                disclosure: if node.branch {
1148                                    Disclosure::branch(model.is_open(&key))
1149                                } else {
1150                                    Disclosure::Leaf
1151                                },
1152                                handle: false,
1153                                icon: source.as_ref(),
1154                            }
1155                            .paint(ui, rect, revealed);
1156                            let color = placed.color;
1157                            let toggle = placed.toggle.unwrap_or(rect);
1158                            if let Some(name) = source.as_ref().and_then(Source::icon_name) {
1159                                egui_pop_core::icon::registry::record(
1160                                    ui.ctx(),
1161                                    "tree",
1162                                    &node.label,
1163                                    name,
1164                                );
1165                            }
1166                            let left = placed.left;
1167                            // The row's widgets, from the right end; the
1168                            // label stops before them.
1169                            let mut right = rect.right();
1170                            if let Some(add) = row_widgets.as_mut() {
1171                                let mut child = ui.new_child(
1172                                    UiBuilder::new()
1173                                        .id_salt(("row_widgets", &key))
1174                                        .max_rect(Rect::from_min_max(
1175                                            pos2(left, rect.top()),
1176                                            rect.max,
1177                                        ))
1178                                        .layout(egui::Layout::right_to_left(egui::Align::Center)),
1179                                );
1180                                add(&mut child, &node);
1181                                let used = child.min_rect();
1182                                if used.width() > 0.0 {
1183                                    right = used.left() - ui.spacing().item_spacing.x;
1184                                }
1185                            }
1186                            // Its actions, before the widgets; the
1187                            // cursor's come after the tree in the Tab
1188                            // order.
1189                            let shown: Vec<usize> = (0..row_actions.len())
1190                                .filter(|&k| revealed || row_actions[k].is_pinned())
1191                                .collect();
1192                            let spots = item::action_rects(ui, rect, right, shown.len());
1193                            if let Some(last) = spots.last() {
1194                                right = last.left();
1195                            }
1196                            if at_cursor && !shown.is_empty() {
1197                                late = Some((
1198                                    key.clone(),
1199                                    r.id,
1200                                    row_state,
1201                                    shown
1202                                        .iter()
1203                                        .map(|&k| row_actions[k].clone())
1204                                        .collect::<Vec<_>>(),
1205                                    shown.clone(),
1206                                    spots.clone(),
1207                                ));
1208                            } else {
1209                                for (&k, spot) in shown.iter().zip(&spots) {
1210                                    let a = &row_actions[k];
1211                                    let id = item::action_id(r.id, k);
1212                                    if item::action_button(ui, visible.kit, id, *spot, a, row_state)
1213                                        .clicked()
1214                                    {
1215                                        clicked.push((key.clone(), a.id().to_string()));
1216                                    }
1217                                }
1218                            }
1219                            if let Some(text) = trailing.as_ref().and_then(|f| f(&node)) {
1220                                right = item::paint_trailing(
1221                                    ui,
1222                                    visible.kit,
1223                                    row_state,
1224                                    rect,
1225                                    left,
1226                                    right,
1227                                    &text,
1228                                );
1229                            }
1230                            let text_rect = Rect::from_min_max(
1231                                pos2(left, rect.top()),
1232                                pos2(right.max(left), rect.bottom()),
1233                            );
1234                            let editing = renaming.as_ref().is_some_and(|r| r.key == key);
1235                            let mut elided = false;
1236                            if editing {
1237                                let ren = renaming.as_mut().expect("renaming");
1238                                let mut child = ui.new_child(
1239                                    UiBuilder::new()
1240                                        .max_rect(text_rect.shrink2(vec2(0.0, 1.0)))
1241                                        .layout(egui::Layout::left_to_right(egui::Align::Center)),
1242                                );
1243                                let edit = child.add(
1244                                    TextEdit::singleline(&mut ren.text)
1245                                        .id(id.with("rename"))
1246                                        .desired_width(text_rect.width() - 4.0),
1247                                );
1248                                egui_pop_core::a11y::name(
1249                                    &edit,
1250                                    Role::TextInput,
1251                                    &tr_args(ui.ctx(), &s::RENAME, &[("name", node.name())]),
1252                                );
1253                                if ren.focus {
1254                                    edit.request_focus();
1255                                    ren.focus = false;
1256                                } else if edit.lost_focus() {
1257                                    if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1258                                        actions.push(Action::Rename(key.clone(), ren.text.clone()));
1259                                    }
1260                                    *renaming = None;
1261                                    take_focus = true;
1262                                }
1263                            } else {
1264                                let font = egui::TextStyle::Body.resolve(ui.style());
1265                                let hits = if model.is_filtered() {
1266                                    query.positions(&node.label)
1267                                } else {
1268                                    Vec::new()
1269                                };
1270                                elided = if hits.is_empty() {
1271                                    item::paint_label(ui, rect, left, right, &node.label, color)
1272                                } else {
1273                                    // What matches, in the row's accent tone,
1274                                    // underlined (as the palette marks it).
1275                                    let strong = visible
1276                                        .kit
1277                                        .list_item
1278                                        .style_toned(Tone::Accent, row_state)
1279                                        .text;
1280                                    let job = filter::highlighted(
1281                                        &node.label,
1282                                        &hits,
1283                                        font,
1284                                        color,
1285                                        strong,
1286                                    );
1287                                    item::paint_label_job(ui, rect, left, right, job, color)
1288                                };
1289                            }
1290                            let name = node.label.clone();
1291                            r.widget_info(move || {
1292                                WidgetInfo::selected(Role::Button, true, selected, &name)
1293                            });
1294                            // A folder says whether it is open: a screen
1295                            // reader reads "expanded" or "collapsed".
1296                            if node.branch {
1297                                let open = model.is_open(&key);
1298                                ui.ctx()
1299                                    .accesskit_node_builder(r.id, |n| n.set_expanded(open));
1300                            }
1301                            let r = if elided {
1302                                item::full_label_tip(r, &node.label)
1303                            } else {
1304                                r
1305                            };
1306                            let labels: Vec<String> =
1307                                row_actions.iter().map(|a| a.label().to_string()).collect();
1308                            item::custom_actions(ui, r.id, &labels);
1309                            if let Some(a) =
1310                                item::requested_action(ui, r.id).and_then(|k| row_actions.get(k))
1311                            {
1312                                clicked.push((key.clone(), a.id().to_string()));
1313                            }
1314                            let double = r.double_clicked();
1315                            if double && self.activate_on_click {
1316                                // The first click did it.
1317                            } else if double {
1318                                if node.branch {
1319                                    actions.push(Action::Expand(key.clone(), !model.is_open(&key)));
1320                                } else {
1321                                    actions.push(Action::Activate(key.clone()));
1322                                }
1323                            } else if r.clicked() {
1324                                take_focus = true;
1325                                let on_toggle = pointer.is_some_and(|p| toggle.contains(p));
1326                                if node.branch && on_toggle {
1327                                    actions.push(Action::Expand(key.clone(), !model.is_open(&key)));
1328                                } else if let Some(j) = node_index(model, i) {
1329                                    let nodes = model.node_rows();
1330                                    let key_at = |j: usize| {
1331                                        model.rows_now()[nodes[j]]
1332                                            .key()
1333                                            .cloned()
1334                                            .expect("a node row")
1335                                    };
1336                                    let mods = ui.input(|i| i.modifiers);
1337                                    actions.push(Action::Select(selection.click(
1338                                        self.mode,
1339                                        nodes.len(),
1340                                        &key_at,
1341                                        j,
1342                                        mods,
1343                                    )));
1344                                    if self.activate_on_click {
1345                                        actions.push(if node.branch {
1346                                            Action::Expand(key.clone(), !model.is_open(&key))
1347                                        } else {
1348                                            Action::Activate(key.clone())
1349                                        });
1350                                    }
1351                                }
1352                            }
1353                            if self.drag_drop && r.drag_started() && renaming.is_none() {
1354                                let keys = if selected && self.mode == Mode::Multiple {
1355                                    // In the order they are shown.
1356                                    model
1357                                        .node_rows()
1358                                        .iter()
1359                                        .filter_map(|&j| model.rows_now()[j].key())
1360                                        .filter(|k| selection.contains(k))
1361                                        .cloned()
1362                                        .collect()
1363                                } else {
1364                                    vec![key.clone()]
1365                                };
1366                                *drag = Some(Drag { keys, target: None });
1367                            }
1368                        }
1369                        Row::Loading { .. } => {
1370                            pseudo(ui, rect, x + indent, |ui| {
1371                                ui.weak(tr(ui.ctx(), &s::LOADING));
1372                            });
1373                        }
1374                        Row::Empty { .. } => {
1375                            pseudo(ui, rect, x + indent, |ui| {
1376                                ui.weak(tr(ui.ctx(), &s::EMPTY));
1377                            });
1378                        }
1379                        Row::Failed { parent, reason, .. } => {
1380                            pseudo(ui, rect, x + indent, |ui| {
1381                                ui.colored_label(
1382                                    Tokens::of(ui.ctx()).status.danger,
1383                                    tr_args(ui.ctx(), &s::FAILED, &[("reason", &reason)]),
1384                                );
1385                                if ui.small_button(tr(ui.ctx(), &strings::RETRY)).clicked() {
1386                                    actions.push(Action::Load(parent.clone()));
1387                                }
1388                            });
1389                        }
1390                    }
1391                }
1392                if let Some(d) = drag.as_mut() {
1393                    let allows = |keys: &[K], target: &K, position: Position| {
1394                        self.allows(source, keys, target, position)
1395                    };
1396                    dragging(ui, d, model, &visible, pointer, indent, row_h, &allows);
1397                }
1398            },
1399        );
1400        rows::active_row(ui, response.id, cursor_row);
1401        // The cursor's actions, after the tree in the Tab order: Tab from
1402        // the tree reaches them, Tab from the last leaves the tree.
1403        if let Some((key, row, row_state, row_actions, shown, spots)) = late {
1404            // In `ui` itself: a child `Ui` would move the ids of what
1405            // follows whenever the buttons come and go.
1406            let kit = egui_pop_core::kit::Kit::of(ui.ctx());
1407            for ((a, &k), spot) in row_actions.iter().zip(&shown).zip(&spots) {
1408                if !inner.contains_rect(*spot) {
1409                    continue;
1410                }
1411                if item::action_button(ui, &kit, item::action_id(row, k), *spot, a, row_state)
1412                    .clicked()
1413                {
1414                    clicked.push((key.clone(), a.id().to_string()));
1415                }
1416            }
1417        }
1418        // A drag ends: dropped where it points, or nowhere.
1419        if let Some(d) = drag.as_ref() {
1420            let (released, down) =
1421                ui.input(|i| (i.pointer.primary_released(), i.pointer.primary_down()));
1422            let inside = ui
1423                .input(|i| i.pointer.interact_pos())
1424                .is_some_and(|p| inner.contains(p));
1425            if released || !down {
1426                if released
1427                    && inside
1428                    && let Some((target, position)) = d.target.clone()
1429                {
1430                    actions.push(Action::Drop(d.keys.clone(), target, position));
1431                }
1432                *drag = None;
1433            } else if let Some(p) = ui.input(|i| i.pointer.interact_pos()) {
1434                // Near an edge, the view scrolls.
1435                let edge = row_h;
1436                let max = (count as f32 * row_h - inner.height()).max(0.0);
1437                if p.y < inner.top() + edge && scroll.offset > 0.0 {
1438                    scroll.to = Some((scroll.offset - row_h / 2.0).max(0.0));
1439                } else if p.y > inner.bottom() - edge && scroll.offset < max {
1440                    scroll.to = Some((scroll.offset + row_h / 2.0).min(max));
1441                }
1442                if scroll.to.is_some() {
1443                    ui.ctx().request_repaint();
1444                }
1445            }
1446        }
1447        if take_focus || focus_tree {
1448            response.request_focus();
1449        }
1450        if let Some(service) = shared {
1451            service.hover(&self.id, hovering.as_ref());
1452        }
1453        let ran = !actions.is_empty();
1454        let before = state.selection.keys().to_vec();
1455        let first = signals.len();
1456        for a in actions {
1457            self.run(state, source, a, &mut signals);
1458        }
1459        if let Some(service) = shared
1460            && let Some(Signal::Select { keys, .. }) = signals[first..]
1461                .iter()
1462                .rev()
1463                .find(|s| matches!(s, Signal::Select { .. }))
1464        {
1465            let keep_others = ui.input(|i| i.modifiers.command);
1466            shared::write(service, &self.id, &before, keys, keep_others, &|k| {
1467                source.item(k)
1468            });
1469            state.seen = Some((service.revision(), state.model.version()));
1470        }
1471        if ran {
1472            state.drain();
1473            ui.ctx().request_repaint();
1474        }
1475        for (key, action) in clicked {
1476            let outcome = steps::run(
1477                self.app,
1478                &TREE_ACTION,
1479                json!({ "tree": self.id, "key": key, "action": action }),
1480                |_| Ok(Json::Null),
1481            );
1482            match outcome {
1483                Outcome::Done(Ok(_)) => {
1484                    if let Some(act) = self.on_action.as_mut() {
1485                        act(&key, &action);
1486                    }
1487                }
1488                Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
1489                    signals.push(Signal::Vetoed {
1490                        step: TREE_ACTION,
1491                        reason,
1492                    })
1493                }
1494            }
1495            ui.ctx().request_repaint();
1496        }
1497        filter::report(ui.ctx(), &self.id, state);
1498        TreeOutput { response, signals }
1499    }
1500
1501    /// The keys of a focused tree.
1502    fn keys(&self, ui: &Ui, state: &mut TreeState<K>, row_h: f32, actions: &mut Vec<Action<K>>) {
1503        let keys = nav::read(ui);
1504        if keys.is_empty() {
1505            return;
1506        }
1507        let model = &mut state.model;
1508        model.rows();
1509        let nodes = model.node_rows().to_vec();
1510        let rows = model.rows_now();
1511        let key_at = |j: usize| rows[nodes[j]].key().cloned().expect("a node row");
1512        let cursor = state
1513            .selection
1514            .cursor()
1515            .and_then(|c| nodes.iter().position(|&i| rows[i].key() == Some(c)));
1516        let page = rows::page(&state.scroll, row_h);
1517        let now = ui.input(|i| i.time);
1518        for (k, mods) in keys {
1519            let mut go = |j: usize, mods: Modifiers, actions: &mut Vec<Action<K>>| {
1520                actions.push(Action::Select(state.selection.move_to(
1521                    self.mode,
1522                    nodes.len(),
1523                    &key_at,
1524                    j,
1525                    mods,
1526                )));
1527                state.scroll.reveal = Some(nodes[j]);
1528            };
1529            match k {
1530                Nav::Up | Nav::Down | Nav::PageUp | Nav::PageDown | Nav::Home | Nav::End => {
1531                    if let Some(j) = nav::target(&k, cursor, nodes.len(), page) {
1532                        go(j, mods, actions);
1533                    }
1534                }
1535                Nav::Left | Nav::Right => {
1536                    let Some(c) = cursor else { continue };
1537                    let key = key_at(c);
1538                    let Some(node) = model.node(&key) else {
1539                        continue;
1540                    };
1541                    let open = node.branch && model.is_open(&key);
1542                    match (k, open) {
1543                        (Nav::Left, true) => actions.push(Action::Expand(key, false)),
1544                        (Nav::Left, false) => {
1545                            if let Some(Some(p)) = model.parent(&key)
1546                                && let Some(j) =
1547                                    nodes.iter().position(|&i| rows[i].key() == Some(p))
1548                            {
1549                                go(j, Modifiers::NONE, actions);
1550                            }
1551                        }
1552                        (_, false) if node.branch => actions.push(Action::Expand(key, true)),
1553                        (_, true) => {
1554                            // The first child shown (a filter may hide some).
1555                            if let Some(j) = model.loaded(Some(&key)).and_then(|v| {
1556                                v.iter().find_map(|first| {
1557                                    nodes.iter().position(|&i| rows[i].key() == Some(first))
1558                                })
1559                            }) {
1560                                go(j, Modifiers::NONE, actions);
1561                            }
1562                        }
1563                        _ => {}
1564                    }
1565                }
1566                Nav::Space => {
1567                    if mods.command {
1568                        if let Some(p) = state.selection.toggle_cursor(self.mode) {
1569                            actions.push(Action::Select(p));
1570                        }
1571                    } else if let Some(c) = cursor {
1572                        go(c, Modifiers::NONE, actions);
1573                    }
1574                }
1575                Nav::All if self.mode == Mode::Multiple => {
1576                    actions.push(Action::Select(state.selection.all(nodes.len(), &key_at)));
1577                }
1578                Nav::Activate => {
1579                    let Some(c) = cursor else { continue };
1580                    let key = key_at(c);
1581                    match model.node(&key) {
1582                        Some(n) if n.branch => {
1583                            actions.push(Action::Expand(key.clone(), !model.is_open(&key)))
1584                        }
1585                        Some(_) => actions.push(Action::Activate(key)),
1586                        None => {}
1587                    }
1588                }
1589                Nav::Rename if self.rename => {
1590                    if let Some(c) = cursor
1591                        && let Some(n) = model.node(&key_at(c))
1592                    {
1593                        state.renaming = Some(Renaming {
1594                            key: n.key.clone(),
1595                            text: n.name().to_string(),
1596                            focus: true,
1597                        });
1598                        return;
1599                    }
1600                }
1601                Nav::Text(t) => {
1602                    let search = state.type_ahead.push(&t, now).to_string();
1603                    let label_at = |j: usize| {
1604                        model
1605                            .node(&key_at(j))
1606                            .map(|n| n.name().to_string())
1607                            .unwrap_or_default()
1608                    };
1609                    if let Some(j) = nav::find(&search, cursor, nodes.len(), &label_at) {
1610                        go(j, Modifiers::NONE, actions);
1611                    }
1612                }
1613                _ => {}
1614            }
1615        }
1616    }
1617
1618    /// Runs one action as its step.
1619    fn run(
1620        &self,
1621        state: &mut TreeState<K>,
1622        source: &dyn TreeSource<K>,
1623        action: Action<K>,
1624        signals: &mut Vec<Signal<K>>,
1625    ) {
1626        let tree = self.id.as_str();
1627        let (step, outcome, signal) = match action {
1628            Action::Load(parent) => {
1629                let ticket = state.model.begin_load(parent.as_ref());
1630                let handle = state.handle();
1631                let asked = parent.clone();
1632                let outcome = steps::run(
1633                    self.app,
1634                    &TREE_LOAD,
1635                    json!({ "tree": tree, "key": parent }),
1636                    |args| {
1637                        let parent: Option<K> = parse(&args["key"])?;
1638                        let ticket = if parent == asked {
1639                            ticket
1640                        } else {
1641                            state.model.begin_load(parent.as_ref())
1642                        };
1643                        source.load(
1644                            parent.as_ref(),
1645                            Sink {
1646                                handle,
1647                                parent: parent.clone(),
1648                                ticket,
1649                            },
1650                        );
1651                        Ok(json!("loading"))
1652                    },
1653                );
1654                if let Some(reason) = outcome.vetoed() {
1655                    state.model.fail(parent.as_ref(), reason);
1656                }
1657                (TREE_LOAD, outcome, Signal::Load { key: parent })
1658            }
1659            // While filtering, a branch opens or closes for the filter
1660            // only: the fold the tree keeps, and its step, wait.
1661            Action::Expand(key, expanded) if state.model.is_filtered() => {
1662                state.model.set_open(&key, expanded);
1663                return;
1664            }
1665            Action::Expand(key, expanded) => {
1666                let mut done = (key.clone(), expanded);
1667                let outcome = steps::run(
1668                    self.app,
1669                    &TREE_EXPAND,
1670                    json!({ "tree": tree, "key": key, "expanded": expanded }),
1671                    |args| {
1672                        let key: K = parse(&args["key"])?;
1673                        let expanded = args["expanded"].as_bool().unwrap_or(expanded);
1674                        state.model.set_expanded(&key, expanded);
1675                        done = (key, expanded);
1676                        Ok(Json::Bool(expanded))
1677                    },
1678                );
1679                (
1680                    TREE_EXPAND,
1681                    outcome,
1682                    Signal::Expand {
1683                        key: done.0,
1684                        expanded: done.1,
1685                    },
1686                )
1687            }
1688            Action::Select(p) => {
1689                // The user's selection wins over one still queued.
1690                state.pending = None;
1691                let mut done = p.clone();
1692                let selection = &mut state.selection;
1693                let outcome = steps::run(self.app, &TREE_SELECT, p.args("tree", tree), |args| {
1694                    done = p.from_args(args)?;
1695                    selection.apply(done.clone());
1696                    Ok(json!(done.keys.len()))
1697                });
1698                (
1699                    TREE_SELECT,
1700                    outcome,
1701                    Signal::Select {
1702                        keys: done.keys,
1703                        cursor: done.cursor,
1704                    },
1705                )
1706            }
1707            Action::Drop(keys, target, position) => {
1708                let mut done = (keys.clone(), target.clone(), position);
1709                let model = &mut state.model;
1710                let allows = |keys: &[K], target: &K, position: Position| {
1711                    self.allows(source, keys, target, position)
1712                };
1713                let outcome = steps::run(
1714                    self.app,
1715                    &TREE_DROP,
1716                    json!({ "tree": tree, "keys": keys, "target": target, "position": position }),
1717                    |args| {
1718                        let keys: Vec<K> = parse(&args["keys"])?;
1719                        let target: K = parse(&args["target"])?;
1720                        let position: Position = parse(&args["position"])?;
1721                        allows(&keys, &target, position)?;
1722                        drop_into(model, &keys, &target, position)?;
1723                        done = (keys, target, position);
1724                        Ok(json!(done.0.len()))
1725                    },
1726                );
1727                (
1728                    TREE_DROP,
1729                    outcome,
1730                    Signal::Drop {
1731                        keys: done.0,
1732                        target: done.1,
1733                        position: done.2,
1734                    },
1735                )
1736            }
1737            Action::Rename(key, to) => {
1738                let Some(node) = state.model.node(&key).cloned() else {
1739                    return;
1740                };
1741                let from = node.name().to_string();
1742                if to.trim().is_empty() || to == from {
1743                    return;
1744                }
1745                let mut done = to.clone();
1746                let model = &mut state.model;
1747                let outcome = steps::run(
1748                    self.app,
1749                    &TREE_RENAME,
1750                    json!({ "tree": tree, "key": key, "from": from, "to": to }),
1751                    |args| {
1752                        let to = args["to"].as_str().ok_or("`to` is not a text")?.to_string();
1753                        // A node with a name of its own keeps its label
1754                        // (decorations the application rebuilds) until
1755                        // the application updates it.
1756                        let mut renamed = node;
1757                        match &mut renamed.name {
1758                            Some(name) => *name = to.clone(),
1759                            None => renamed.label = to.clone(),
1760                        }
1761                        model.apply(Edit::Update(renamed));
1762                        done = to;
1763                        Ok(json!(done))
1764                    },
1765                );
1766                (
1767                    TREE_RENAME,
1768                    outcome,
1769                    Signal::Rename {
1770                        key,
1771                        from,
1772                        to: done,
1773                    },
1774                )
1775            }
1776            Action::Activate(key) => {
1777                let outcome = steps::run(
1778                    self.app,
1779                    &TREE_ACTIVATE,
1780                    json!({ "tree": tree, "key": key }),
1781                    |_| Ok(Json::Null),
1782                );
1783                (TREE_ACTIVATE, outcome, Signal::Activate { key })
1784            }
1785        };
1786        match outcome {
1787            Outcome::Done(Ok(_)) => signals.push(signal),
1788            Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
1789                signals.push(Signal::Vetoed { step, reason })
1790            }
1791        }
1792    }
1793}
1794
1795/// Runs `tree.context` for a right-clicked row: the row and the node
1796/// its menu is for, unless vetoed.
1797fn open_context<K: Key>(
1798    app: Option<&AppHandle>,
1799    tree: &str,
1800    key: &K,
1801    signals: &mut Vec<Signal<K>>,
1802) -> Option<(K, K)> {
1803    let mut target = key.clone();
1804    let outcome = steps::run(
1805        app,
1806        &TREE_CONTEXT,
1807        json!({ "tree": tree, "key": key }),
1808        |args| {
1809            target = parse(&args["key"])?;
1810            Ok(Json::Bool(true))
1811        },
1812    );
1813    match outcome {
1814        Outcome::Done(Ok(_)) => {
1815            signals.push(Signal::Context {
1816                key: target.clone(),
1817            });
1818            Some((key.clone(), target))
1819        }
1820        Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
1821            signals.push(Signal::Vetoed {
1822                step: TREE_CONTEXT,
1823                reason,
1824            });
1825            None
1826        }
1827    }
1828}
1829
1830fn parse<T: serde::de::DeserializeOwned>(v: &Json) -> Result<T, String> {
1831    serde_json::from_value(v.clone()).map_err(|e| e.to_string())
1832}
1833
1834/// The position of row `row` among the node rows.
1835fn node_index<K: Key>(model: &Model<K>, row: usize) -> Option<usize> {
1836    model.node_rows().binary_search(&row).ok()
1837}
1838
1839/// Moves dropped nodes in the view's model.
1840fn drop_into<K: Key>(
1841    model: &mut Model<K>,
1842    keys: &[K],
1843    target: &K,
1844    position: Position,
1845) -> Result<(), String> {
1846    if keys.iter().any(|k| model.is_within(target, k)) {
1847        return Err("a node cannot go into itself".into());
1848    }
1849    if !model.contains(target) {
1850        return Err("the target is gone".into());
1851    }
1852    model.move_many(keys, target, position);
1853    Ok(())
1854}
1855
1856/// Tracks the drop target under the pointer and marks it with the kit's
1857/// `tree-drop-marker`, `disabled` and with a "not allowed" pointer when
1858/// the source or the view refuses it.
1859#[allow(
1860    clippy::too_many_arguments,
1861    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1862)]
1863fn dragging<K: Key>(
1864    ui: &Ui,
1865    d: &mut Drag<K>,
1866    model: &Model<K>,
1867    visible: &rows::Visible<'_>,
1868    pointer: Option<egui::Pos2>,
1869    indent: f32,
1870    row_h: f32,
1871    allows: &Allows<'_, K>,
1872) {
1873    d.target = None;
1874    egui_pop_core::pointer::hold_drag_cursor(ui.ctx(), egui_pop_core::pointer::DragKind::Carry);
1875    let Some(p) = pointer else { return };
1876    let Some(i) = visible
1877        .range
1878        .clone()
1879        .find(|&i| (visible.rect_of)(i).contains(p))
1880    else {
1881        return;
1882    };
1883    let Row::Node { key, depth } = &model.rows_now()[i] else {
1884        return;
1885    };
1886    let Some(node) = model.node(key) else { return };
1887    if d.keys.iter().any(|k| model.is_within(key, k)) {
1888        return;
1889    }
1890    let rect = (visible.rect_of)(i);
1891    let f = (p.y - rect.top()) / row_h;
1892    let position = if node.branch {
1893        if f < 0.25 {
1894            Position::Before
1895        } else if f > 0.75 {
1896            Position::After
1897        } else {
1898            Position::Inside
1899        }
1900    } else if f < 0.5 {
1901        Position::Before
1902    } else {
1903        Position::After
1904    };
1905    let refused = allows(&d.keys, key, position).is_err();
1906    if refused {
1907        ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed);
1908    }
1909    let x = rect.left() + (*depth as f32 + 1.0) * indent;
1910    // Around the row, or a line (a part with no height) between rows.
1911    let at = match position {
1912        Position::Inside => rect.shrink(1.0),
1913        Position::Before => Rect::from_min_max(pos2(x, rect.top()), rect.right_top()),
1914        Position::After => Rect::from_min_max(pos2(x, rect.bottom()), rect.max),
1915    };
1916    visible.kit.tree_drop_marker.paint(
1917        &KitCx {
1918            painter: ui.painter(),
1919            ppp: ui.ctx().pixels_per_point(),
1920        },
1921        &Part {
1922            rect: at,
1923            room: at,
1924            state: State::REST.with(State::DISABLED, refused),
1925            label: None,
1926        },
1927    );
1928    d.target = Some((key.clone(), position));
1929}
1930
1931/// A row that is not a node: loading, empty, failed.
1932fn pseudo(ui: &mut Ui, rect: Rect, x: f32, add: impl FnOnce(&mut Ui)) {
1933    let mut child = ui.new_child(
1934        UiBuilder::new()
1935            .max_rect(Rect::from_min_max(pos2(x, rect.top()), rect.max))
1936            .layout(egui::Layout::left_to_right(egui::Align::Center)),
1937    );
1938    add(&mut child);
1939}