mktree 0.6.1

An egui tree to display entities of tree structure, e.g. CG assets, staffs, etc.
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
//! A tree structure and display with [`egui::SelectableLabel`] at every leaves.

use crate::*;

use crossbeam_channel::Sender;
use egui::{collapsing_header::CollapsingState, RichText};
use std::collections::HashSet;

// ----------------------------------------------------------------------------
#[derive(Clone, Debug, Default)]
pub struct Node<T: Entity> {
    /// This name will be used to represent the node in the tree.
    name: String,
    /// Inner content of the node.
    content: T,
    /// Collapse state of the `CollapsingHeader`.
    open: bool,
}

impl<T: Entity> Node<T> {
    fn empty() -> Self {
        Self {
            content: T::empty(),
            open: true,
            ..Default::default()
        }
    }

    fn name(mut self, name: &str) -> Self {
        self.name = name.to_owned();
        self
    }

    fn match_by(&self, pattern: &str) -> bool {
        self.name.to_lowercase().contains(pattern)
    }
}

#[derive(Clone, Debug)]
/// Used for display tree data with [`Node`].
/// We're distinguishing the type of the nodes in order to perform further actions
/// depending on the selected node type.
pub enum TreeNode<T: Entity> {
    Root(Node<T>),
    SubTreeRoot(Node<T>),
    Leaf(Node<T>),
}

impl<T: Entity> Default for TreeNode<T> {
    /// Makes a leaf.
    fn default() -> Self {
        TreeNode::Leaf(Node::default())
    }
}

impl<T: Entity> TreeNode<T> {
    fn node_name(&self) -> &String {
        match self {
            Self::Root(inner) | Self::SubTreeRoot(inner) | Self::Leaf(inner) => &inner.name,
        }
    }

    fn open(&self) -> bool {
        match self {
            Self::Root(inner) | Self::SubTreeRoot(inner) | Self::Leaf(inner) => inner.open,
        }
    }

    fn open_mut(&mut self, open: bool) {
        match self {
            Self::Root(inner) | Self::SubTreeRoot(inner) | Self::Leaf(inner) => {
                inner.open = open;
            }
        }
    }

    fn toggle_collapse_state(&mut self) {
        match self {
            Self::Root(inner) | Self::SubTreeRoot(inner) | Self::Leaf(inner) => {
                inner.open = !inner.open;
            }
        }
    }

    fn selected(&self, selection: &HashSet<T>) -> bool {
        match self {
            // TODO: `SubTreeRoot`s won't be shown as selected for now.
            Self::Root(_) | Self::SubTreeRoot(_) => false,
            Self::Leaf(inner) => match inner.content.name() {
                // TODO: this makes assets with the same name all show as selected
                Some(name) => selection
                    .iter()
                    .filter_map(|a| a.name())
                    .collect::<HashSet<&String>>()
                    .contains(name),
                None => false,
            },
        }
    }

    fn leaf(entity: T) -> TreeNode<T> {
        TreeNode::Leaf(Node {
            name: match entity.name() {
                Some(name) => name.to_owned(),
                None => EMPTY_NODE_NAME.to_owned(),
            },
            content: entity,
            open: false,
        })
    }

    fn subtree_root(group: &str, typ: &ProjectSource) -> TreeNode<T> {
        TreeNode::SubTreeRoot(Node {
            name: group.to_owned(),
            content: T::as_group(group, typ),
            open: true,
        })
    }
}

// ----------------------------------------------------------------------------
#[derive(Clone, Debug, Default)]
/// Recursive tree struct.
pub struct MkTree<T: Entity>(pub TreeNode<T>, pub Vec<MkTree<T>>);

impl<T: Entity> MkTree<T> {
    /// Can be used to sort trees after construction.
    /// Must clone to get around the borrow checker.
    pub fn node_name(&self) -> String {
        self.0.node_name().clone()
    }

    fn open(&self) -> bool {
        self.0.open()
    }

    fn toggle_collapse_state(&mut self) {
        self.0.toggle_collapse_state()
    }

    fn node_content(&self) -> &T {
        match &self.0 {
            TreeNode::Root(inner) | TreeNode::SubTreeRoot(inner) | TreeNode::Leaf(inner) => {
                &inner.content
            }
        }
    }

    /// Recursively determines if the node should be visible, given the filter string.
    fn match_by(&self, pattern: &str) -> bool {
        match &self.0 {
            TreeNode::Leaf(inner) => inner.match_by(pattern),
            TreeNode::SubTreeRoot(_) => self
                .1
                .iter()
                .filter(|n| n.match_by(pattern))
                .next()
                .is_some(),
            TreeNode::Root(_) => true,
        }
    }

    /// The given `T` will be used to make a leaf -- a tip of the tree -- all by itself,
    /// i.e. containing empty list of trees.
    fn single_leaf(entity: T) -> Self {
        Self(TreeNode::leaf(entity), vec![])
    }

    /// The given group name will be made into a `SubTreeRoot` directly containing the given leaves.
    pub fn leaf_group(group: &str, leaves: Vec<T>, typ: &ProjectSource) -> Self {
        Self(
            TreeNode::subtree_root(group, typ),
            leaves
                .into_iter()
                .map(|leaf| Self::single_leaf(leaf))
                .collect(),
        )
    }

    pub fn subtree_group(group: &str, subtrees: Vec<MkTree<T>>, typ: &ProjectSource) -> Self {
        Self(TreeNode::subtree_root(group, typ), subtrees)
    }

    /// A root and all other leaves at the same level.
    pub fn from_node_n_leaves(entity: T, leaves: Vec<T>) -> Self {
        Self(
            TreeNode::leaf(entity),
            leaves.into_iter().map(|c| Self::single_leaf(c)).collect(),
        )
    }

    pub fn from_node_n_subtrees(entity: T, subtrees: Vec<MkTree<T>>) -> Self {
        Self(TreeNode::leaf(entity), subtrees)
    }

    fn listen(
        &mut self,
        ui: &mut egui::Ui,
        response: egui::Response,
        selection: &mut HashSet<T>,
        sender: &Sender<TreeNodeSignal>,
    ) {
        if response.clicked() {
            if !ui.ctx().input(|i| i.modifiers).any() {
                selection.clear();
            };
            match &self.0 {
                TreeNode::Leaf(_) => {
                    // Only signal selection change in this case.
                    sender
                        .send(TreeNodeSignal::LeafClicked)
                        .expect("Channel of MkTree's selected node response has been disconnected");
                    // Saves selected `impl Entity` in `TreeContainer::selected_nodes`
                    selection.insert(self.node_content().clone());
                }
                // don't do anything when `TreeNode::SubTreeRoot` or `TreeNode::Root` gets clicked
                _ => {}
            };
            // log::info!("Selected node: {:?}", &selection);
        };
    }

    /// Recursively makes the tree UI, while collects the user selection of the leaf nodes, and sends message.
    pub fn ui(
        &mut self,
        ui: &mut egui::Ui,
        node_name: &str,
        depth: usize,
        filter: &str,
        selection: &mut HashSet<T>,
        sender: &Sender<TreeNodeSignal>,
    ) {
        let mut state = CollapsingState::load_with_default_open(
            ui.ctx(),
            ui.make_persistent_id(node_name),
            true,
        );

        state.set_open(self.open());

        let response = state
            .show_header(ui, |ui| {
                // NOTE: no semicolon, as we're returning the inner response!
                ui.selectable_label(self.0.selected(selection), node_name)
                // the `egui::Response` is returned from this `CollapsingState::show_header` method,
                // and passed to `Self::listen` to be sent via channel
                //
            })
            // then recursively draws the children content
            .body(|ui| self.children_ui(ui, &node_name, depth, filter, selection, sender));

        // toggles collapse state
        if response.0.clicked() {
            self.toggle_collapse_state();
        };

        // checks for clicks on the header UI -- selectable label
        self.listen(ui, response.1.inner, selection, sender);
    }

    fn children_ui(
        &mut self,
        ui: &mut egui::Ui,
        // this isn't used in this function body but in previous call it's used for the header
        _node_name: &str,
        depth: usize,
        filter: &str,
        selection: &mut HashSet<T>,
        sender: &Sender<TreeNodeSignal>,
    ) {
        let mut tree = std::mem::take(self);
        // modifies the children
        tree.1 = tree
            .1
            .into_iter()
            .map(|mut child| {
                let node_name = child.node_name();
                if filter.is_empty() || child.match_by(filter) {
                    child.ui(ui, &node_name, depth + 1, filter, selection, sender);
                };
                child
            })
            .collect();
        *self = tree
    }

    /// Recursively counts (by accumulation) the number of leaves.
    fn leaf_len(&self, count: &mut usize) -> usize {
        if let TreeNode::Leaf(_) = self.0 {
            *count += 1;
        };
        self.1.iter().for_each(|t| {
            t.leaf_len(count);
        });
        *count
    }

    fn collapse_all(&mut self, open: bool) {
        match self.0 {
            TreeNode::Root(_) => {
                // do not expand nor close
            }
            _ => {
                self.0.open_mut(open);
            }
        }
        self.1.iter_mut().for_each(|t| t.collapse_all(open));
    }
}

#[derive(Debug, Clone, Default)]
/// Container for the asset tree, where first field holds the currently selected asset (via primary mouse click).
pub struct TreeContainer<T: Entity> {
    /// The final tree with `tree.0` of `TreeNode::Root` type.
    tree: MkTree<T>,

    root_nice_name: String,

    total_leaves: usize,

    filter: String,

    /// This contains only non-empty ProductionAsset, but such item might not have `asset_name`, i.e.
    /// having only `category.main_type` value.
    selected_nodes: HashSet<T>,

    /// Whether next toggle action should expand or collapse the tree recursively.
    batch_collapse: bool,
}

impl<T: Entity> TreeContainer<T> {
    pub fn uninitialized_root() -> Self {
        Self {
            tree: MkTree(
                TreeNode::Root(Node::empty().name(TREE_ROOT_UNINITIALIZED_NAME)),
                vec![],
            ),
            ..Default::default()
        }
    }

    pub fn subtrees_mut(&mut self, subtrees: Vec<MkTree<T>>, root_name: &str, show_count: bool) {
        self.tree = MkTree(TreeNode::Root(Node::empty().name(root_name)), subtrees);
        self.count_leaves();
        self.make_root_nice_name(root_name, show_count);
    }

    pub fn selected_nodes(&self) -> &HashSet<T> {
        &self.selected_nodes
    }

    pub fn selected_nodes_mut(&mut self, selected_nodes: HashSet<T>) {
        self.selected_nodes = selected_nodes;
    }

    // TODO: provide select all leaves?
    pub fn clear_selection(&mut self) {
        self.selected_nodes = HashSet::new();
    }

    pub fn filter_ui(&mut self, width: f32, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.label("Filter by Name:");
            ui.add(egui::TextEdit::singleline(&mut self.filter).desired_width(width));
            // forces lowercase conversion
            self.filter = self.filter.to_lowercase();
            if ui.button("").clicked() {
                self.filter.clear();
            }
        });
    }

    pub fn batch_collapse_ui(&mut self, ui: &mut egui::Ui) {
        let text = RichText::new(if self.batch_collapse {
            "⏷ Expand Tree"
        } else {
            "➖ Collapse Tree"
        });
        if ui.button(text).clicked() {
            self.tree.collapse_all(self.batch_collapse);
            self.batch_collapse = !self.batch_collapse;
        };
    }

    pub fn tree_ui(&mut self, ui: &mut egui::Ui, sender: &Sender<TreeNodeSignal>) {
        self.tree.ui(
            ui,
            &self.root_nice_name,
            0,
            &self.filter,
            &mut self.selected_nodes,
            sender,
        )
    }

    /// Counts all the leaves.
    fn count_leaves(&mut self) {
        // must reset the count first
        self.total_leaves = 0;
        self.tree.leaf_len(&mut self.total_leaves);
    }

    /// Appends after the root name of the tree the count of leaves.
    fn make_root_nice_name(&mut self, root_name: &str, show_count: bool) {
        if show_count {
            self.root_nice_name = format!("{}: total {}", root_name, self.total_leaves);
        } else {
            self.root_nice_name = root_name.to_owned();
        }
    }
}