egui_ltreeview 0.7.0

A tree view widget for egui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
#![warn(missing_docs)]
//! # `egui_ltreeview` is a tree view widget for [egui](https://github.com/emilk/egui)
//!
//! This tree view widget implements all the common features of a tree view to get you
//! up and running as fast as possible.
//!
//! # Features:
//! * Directory and leaf nodes
//! * Node selection
//! * Select multiple nodes
//! * Keyboard navigation using arrow keys
//! * Frontend for Drag and Drop support
//! * Agnostic to the implementation of your data.
//! * Performant (100k nodes in ~3 ms)
//!
//! # Crate feature flags
//! * `persistence` Adds serde to [`NodeId`] and enabled the `persistence` feature of egui.
//! * `doc` Adds additional documentation.
//!
//! # Quick start
//! ```
//! # use egui_ltreeview::*;
//! # use egui::*;
//! # fn ui(ui: &mut egui::Ui){
//! TreeView::new(Id::new("tree view")).show(ui, |builder| {
//!     builder.dir(0, "Root");
//!     builder.leaf(1, "Ava");
//!     builder.leaf(2, "Benjamin");
//!     builder.leaf(3, "Charlotte");
//!     builder.close_dir();
//! });
//! # }
//! ```
//! Create a new [`TreeView`] with its unique id and show it for the current ui.
//! Use the [`builder`](TreeViewBuilder) in the callback to add directories and leaves
//! to the tree. The nodes of the tree must have a unique id which implements the [`NodeId`] trait.
//!
//! # Further information
#![cfg_attr(feature = "doc",
    doc = "Visit the [`doc`] module documentation for further information about these topics:",
    doc = "",
    doc = make_table_of_contents::make_table_of_contents!("src/doc/doc.md", "doc/index.html")
)]
#![cfg_attr(
    not(feature = "doc"),
    doc = "Enable the `doc` feature for further information"
)]

#[cfg(feature = "doc")]
pub mod doc;

mod builder;
mod node;
mod state;

use egui::{
    self, layers::ShapeIdx, vec2, Align, EventFilter, Id, Key, LayerId, Layout, Modifiers, NumExt,
    Order, PointerButton, Popup, PopupAnchor, PopupKind, Pos2, Rangef, Rect, Response, Sense,
    Shape, Ui, UiBuilder, Vec2,
};
use std::{collections::HashSet, hash::Hash};

pub use builder::*;
pub use node::*;
pub use state::*;

/// Identifies a node in the tree.
///
/// This is just a trait alias for the collection of necessary traits that a node id
/// must implement.
#[cfg(not(feature = "persistence"))]
pub trait NodeId: Clone + PartialEq + Eq + Hash {}
#[cfg(not(feature = "persistence"))]
impl<T> NodeId for T where T: Clone + PartialEq + Eq + Hash {}

#[cfg(feature = "persistence")]
/// A node in the tree is identified by an id that must implement this trait.
///
/// This is just a trait alias for the collection of necessary traits that a node id
/// must implement.
pub trait NodeId:
    Clone + PartialEq + Eq + Hash + serde::de::DeserializeOwned + serde::Serialize
{
}
#[cfg(feature = "persistence")]
impl<T> NodeId for T where
    T: Clone + PartialEq + Eq + Hash + serde::de::DeserializeOwned + serde::Serialize
{
}

/// A tree view widget.
pub struct TreeView<'context_menu, NodeIdType> {
    id: Id,
    settings: TreeViewSettings,
    #[allow(clippy::type_complexity)]
    fallback_context_menu: Option<Box<dyn FnOnce(&mut Ui, &Vec<NodeIdType>) + 'context_menu>>,
}

impl<'context_menu, NodeIdType: NodeId> TreeView<'context_menu, NodeIdType> {
    /// Create a tree view from an unique id.
    pub fn new(id: Id) -> Self {
        Self {
            id,
            settings: TreeViewSettings::default(),
            fallback_context_menu: None,
        }
    }

    /// Construct the tree view using the [`TreeViewBuilder`] by adding [nodes](`NodeBuilder`) to the tree.
    ///
    /// [`NodeId`] has to be thread safe for this to load the [`TreeViewState`] from egui data.
    /// If your [`NodeId`] is not threadsafe consider creating a [`TreeViewState`] directly and displaying
    /// the the tree with [`TreeView::show_state`]
    ///
    pub fn show(
        self,
        ui: &mut Ui,
        build_tree_view: impl FnOnce(&mut TreeViewBuilder<'_, NodeIdType>),
    ) -> (Response, Vec<Action<NodeIdType>>)
    where
        NodeIdType: NodeId + Send + Sync + 'static,
    {
        let id = self.id;
        let mut state = TreeViewState::load(ui, id).unwrap_or_default();
        let res = self.show_state(ui, &mut state, build_tree_view);
        state.store(ui, id);
        res
    }

    /// Start displaying the tree view with a [`TreeViewState`].
    ///
    /// Construct the tree view using the [`TreeViewBuilder`] by adding
    /// directories or leaves to the tree.
    pub fn show_state(
        self,
        ui: &mut Ui,
        state: &mut TreeViewState<NodeIdType>,
        build_tree_view: impl FnOnce(&mut TreeViewBuilder<'_, NodeIdType>),
    ) -> (Response, Vec<Action<NodeIdType>>)
    where
        NodeIdType: NodeId,
    {
        let TreeView {
            id,
            settings,
            mut fallback_context_menu,
        } = self;

        // Set the focus filter to get correct keyboard navigation while focused.
        ui.memory_mut(|m| {
            m.set_focus_lock_filter(
                id,
                EventFilter {
                    tab: false,
                    escape: false,
                    horizontal_arrows: true,
                    vertical_arrows: true,
                },
            )
        });

        let (builder_response, tree_view_rect) = draw_foreground(
            ui,
            id,
            &settings,
            state,
            build_tree_view,
            &mut fallback_context_menu,
        );

        if !settings.allow_multi_select {
            state.prune_selection_to_single_id();
        }
        // Remember the size of the tree for next frame.
        //state.size = response.rect.size();

        //draw_background(ui, &ui_data);

        if ui.memory(|m| m.has_focus(id)) {
            // If the widget is focused but no node is selected we want to select any node
            // to allow navigating throught the tree.
            // In case we gain focus from a drag action we select the dragged node directly.
            if state.selected().is_empty() {
                let fallback_selection = state.get_dragged().and_then(|v| v.first());
                if let Some(fallback_selection) = fallback_selection {
                    state.set_one_selected(fallback_selection.clone());
                }
            }
        }
        if builder_response.interaction.clicked() || builder_response.interaction.drag_started() {
            ui.memory_mut(|m| m.request_focus(id));
        }

        let mut actions = Vec::new();
        // Create a drag or move action.
        if builder_response.interaction.dragged() {
            if let Some((drop_id, position)) = &builder_response.drop_target {
                actions.push(Action::Drag(DragAndDrop {
                    source: state.get_simplified_dragged().cloned().unwrap_or_default(),
                    target: drop_id.clone(),
                    position: position.clone(),
                    drop_marker_idx: builder_response.drop_marker_idx,
                }))
            } else if !builder_response.drop_on_self {
                if let Some(position) = ui.ctx().pointer_latest_pos() {
                    actions.push(Action::DragExternal(DragAndDropExternal {
                        position,
                        source: state.get_simplified_dragged().cloned().unwrap_or_default(),
                    }));
                }
            }
        }
        if builder_response.interaction.drag_stopped() {
            if let Some((drop_id, position)) = builder_response.drop_target {
                actions.push(Action::Move(DragAndDrop {
                    source: state.get_simplified_dragged().cloned().unwrap_or_default(),
                    target: drop_id,
                    position,
                    drop_marker_idx: builder_response.drop_marker_idx,
                }))
            } else if !builder_response.drop_on_self {
                if let Some(position) = ui.ctx().pointer_latest_pos() {
                    actions.push(Action::MoveExternal(DragAndDropExternal {
                        position,
                        source: state.get_simplified_dragged().cloned().unwrap_or_default(),
                    }));
                }
            }
        }

        if builder_response.selected {
            actions.push(Action::SetSelected(state.selected().clone()));
        }

        if let Some(nodes_to_activate) = builder_response.activate {
            actions.push(Action::Activate(Activate {
                selected: nodes_to_activate.clone(),
                modifiers: ui.ctx().input(|i| i.modifiers),
            }));
        }

        if builder_response.interaction.drag_stopped() {
            state.reset_dragged();
        }

        (
            builder_response.interaction.with_new_rect(tree_view_rect),
            actions,
        )
    }
}
///
/// # Customizing the look and feel of the tree view.
///
/// To change the basic settings of the tree view you can use the [`TreeViewSettings`] to customize the tree view
/// or use the convenience methods on [`TreeView`] directly.
/// Check out [`TreeViewSettings`] for all settings possible on the tree view.
/// ```
/// # use egui_ltreeview::*;
/// # fn ui(ui: &mut egui::Ui, id: egui::Id){
/// TreeView::new(id)
///     .with_settings(TreeViewSettings{
///         override_indent: Some(15.0),
///         ..Default::default()
///     })
///     .min_height(200.0)
///     .show(ui, |builder| {
///         # builder.leaf(0, "");
///         // build your tree here
/// });
/// # }
/// ```
///
impl<'context_menu, NodeIdType: NodeId> TreeView<'context_menu, NodeIdType> {
    /// Set the settings for this tree view with the [`TreeViewSettings`] struct.
    ///
    /// This is maybe more convienient to you than setting each setting individually.
    pub fn with_settings(mut self, settings: TreeViewSettings) -> Self {
        self.settings = settings;
        self
    }

    /// Override the indent value for this tree view.
    ///
    /// By default, this value is 'None' which means that the indent value from the
    /// current ui is used. If this value is set, this value will be used as the indent
    /// value without affecting the ui's indent value.
    pub fn override_indent(mut self, indent: Option<f32>) -> Self {
        self.settings.override_indent = indent;
        self
    }

    /// Override whether or not the background of the nodes should striped.
    ///
    /// By default, this value is 'None' which means that the striped setting from the
    /// current UI style is used. If this value is set, it will be used without
    /// affecting the ui's value.
    pub fn override_striped(mut self, striped: Option<bool>) -> Self {
        self.settings.override_striped = striped;
        self
    }

    /// Set the style of the indent hint to show the indentation level.
    pub fn indent_hint_style(mut self, style: IndentHintStyle) -> Self {
        self.settings.indent_hint_style = style;
        self
    }

    /// Set the row layout for this tree.
    pub fn row_layout(mut self, layout: RowLayout) -> Self {
        self.settings.row_layout = layout;
        self
    }

    /// Set if the tree view is allowed to select multiple nodes at once.
    pub fn allow_multi_selection(mut self, allow_multi_select: bool) -> Self {
        self.settings.allow_multi_select = allow_multi_select;
        self
    }

    /// Set the modifier that the user is required to press to initiate a range based selection.
    pub fn range_selection_modifier(mut self, modifiers: Modifiers) -> Self {
        self.settings.range_selection_modifier = modifiers;
        self
    }

    /// Set the modifier that the user is required to press to initiate a set based selection.
    pub fn set_selection_modifier(mut self, modifiers: Modifiers) -> Self {
        self.settings.set_selection_modifier = modifiers;
        self
    }

    /// Set if nodes in the tree are allowed to be dragged and dropped.
    pub fn allow_drag_and_drop(mut self, allow_drag_and_drop: bool) -> Self {
        self.settings.allow_drag_and_drop = allow_drag_and_drop;
        self
    }

    /// Set the default node height for this tree.
    pub fn default_node_height(mut self, default_node_height: Option<f32>) -> Self {
        self.settings.default_node_height = default_node_height;
        self
    }

    /// Add a fallback context menu to the tree.
    ///
    /// If the node did not configure a context menu, either through [`NodeBuilder`](`NodeBuilder::context_menu`) or [`NodeConfig`](`NodeConfig::has_context_menu`),
    /// or if multiple nodes were selected and right-clicked, then this fallback context menu will be opened.
    ///
    /// A context menu in egui gets its size the first time it becomes visible.
    /// Since all nodes in the tree view share the same context menu you must set
    /// the size of the context menu manually for each node if you want to have differently
    /// sized context menus.
    pub fn fallback_context_menu(
        mut self,
        context_menu: impl FnOnce(&mut Ui, &Vec<NodeIdType>) + 'context_menu,
    ) -> Self {
        self.fallback_context_menu = Some(Box::new(context_menu));
        self
    }

    /// Set the minimum width the tree can have.
    pub fn min_width(mut self, width: f32) -> Self {
        self.settings.min_width = width;
        self
    }

    /// Set the minimum height the tree can have.
    pub fn min_height(mut self, height: f32) -> Self {
        self.settings.min_height = height;
        self
    }
}

#[allow(clippy::type_complexity)]
fn draw_foreground<'context_menu, NodeIdType: NodeId>(
    ui: &mut Ui,
    id: Id,
    settings: &TreeViewSettings,
    state: &mut TreeViewState<NodeIdType>,
    build_tree_view: impl FnOnce(&mut TreeViewBuilder<'_, NodeIdType>),
    fall_back_context_menu: &mut Option<Box<dyn FnOnce(&mut Ui, &Vec<NodeIdType>) + 'context_menu>>,
) -> (TreeViewBuilderResponse<NodeIdType>, Rect) {
    // Calculate the desired size of the tree view widget.
    let interaction_rect = Rect::from_min_size(
        ui.cursor().min,
        ui.available_size()
            .at_least(vec2(settings.min_width, settings.min_height))
            .at_least(vec2(state.min_width, state.last_height)),
    );
    let interaction = interact_no_expansion(ui, interaction_rect, id, Sense::click_and_drag());
    let input = get_input::<NodeIdType>(ui, &interaction, id, settings);
    let ui_data = UiData {
        interaction,
        drag_layer: LayerId::new(Order::Tooltip, ui.make_persistent_id("ltreeviw drag layer")),
        drag_layer_offset: ui
            .input(|i| i.pointer.press_origin())
            .zip(ui.input(|i| i.pointer.latest_pos()))
            .zip(state.get_drag_overlay_offset())
            .map(|((origin, latest), drag_overlay_offset)| (latest - origin) + drag_overlay_offset)
            .unwrap_or_default(),
        has_focus: ui.memory(|m| m.has_focus(id)),
        drop_marker_idx: ui.painter().add(Shape::Noop),
    };
    // Run the build tree view closure

    let mut builder_ui = ui.new_child(
        UiBuilder::new()
            .layout(Layout::top_down(egui::Align::Min))
            .max_rect(interaction_rect),
    );
    let mut builder_response = TreeViewBuilder::run(
        &mut builder_ui,
        state,
        settings,
        ui_data,
        input,
        build_tree_view,
    );

    let tree_view_rect = builder_response.space_used.union(interaction_rect);
    ui.allocate_rect(tree_view_rect, Sense::hover());

    // Remember width of the tree view for next frame
    state.min_width = state
        .min_width
        .at_least(builder_response.space_used.width());
    state.last_height = builder_response.space_used.height();

    let mut open_fallback_context_menu = false;
    match builder_response.output {
        BuilderActions::OpenFallbackContextmenu { for_selection } => {
            open_fallback_context_menu = true;
            state.show_fallback_context_menu_for_selection = for_selection;
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::SetDragged(dragged) => {
            state.set_dragged(dragged);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::SetSecondaryClicked(id) => {
            state.secondary_selection = Some(id);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::ActivateSelection(selection) => {
            builder_response.activate = Some(selection);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::ActivateThis(id) => {
            builder_response.activate = Some(vec![id]);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::SelectOneNode(id, scroll_to_rect) => {
            builder_response.selected = true;
            state.set_one_selected(id.clone());
            state.set_cursor(None);
            if let Some(scroll_to_rect) = scroll_to_rect {
                ui.scroll_to_rect(scroll_to_rect, None);
            }
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::ToggleSelection(id, scroll_to_rect) => {
            builder_response.selected = true;
            state.toggle_selected(&id);
            state.set_pivot(Some(id));
            if let Some(scroll_to_rect) = scroll_to_rect {
                ui.scroll_to_rect(scroll_to_rect, None);
            }
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::ShiftSelect(ids) => {
            builder_response.selected = true;
            state.set_selected_dont_change_pivot(ids);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::Select {
            selection,
            pivot,
            cursor,
            scroll_to_rect,
        } => {
            builder_response.selected = true;
            state.set_selected(selection);
            state.set_pivot(Some(pivot));
            state.set_cursor(Some(cursor));
            ui.scroll_to_rect(scroll_to_rect, None);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::SetCursor(id, scroll_to_rect) => {
            state.set_cursor(Some(id));
            ui.scroll_to_rect(scroll_to_rect, None);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::SetOpenness(id, is_open) => {
            state.set_openness(id, is_open);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::SetLastclicked(id) => {
            state.set_last_clicked(&id);
            builder_response.output = BuilderActions::None;
        }
        BuilderActions::ClearSelection => {
            state.set_selected(vec![]);
            builder_response.selected = true;
        }
        BuilderActions::None => (),
    }

    // Do context menu
    if let Some(fallback_context_menu) = fall_back_context_menu.take() {
        Popup::new(
            Id::new(&id).with("egui_ltreeview_context_menu"),
            ui.ctx().clone(),
            PopupAnchor::PointerFixed,
            ui.layer_id(),
        )
        .kind(PopupKind::Menu)
        .layout(Layout::top_down_justified(Align::Min))
        .style(egui::containers::menu::menu_style)
        .gap(0.0)
        .open_memory(open_fallback_context_menu.then_some(egui::SetOpenCommand::Bool(true)))
        .show(|ui| {
            if state.show_fallback_context_menu_for_selection {
                fallback_context_menu(ui, state.selected());
            } else {
                fallback_context_menu(ui, &Vec::new());
            }
        });
    }

    (builder_response, tree_view_rect)
}

/// A position inside a directory node.
///
/// When a source node is dragged this enum describes the position
/// where the node should be dropped inside a directory node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirPosition<NodeIdType> {
    /// The source node should be inserted in the first position of the directory
    First,
    /// The source node should be inserted in the last position of the directory.
    Last,
    /// The source node should be inserted after the node with this node id.
    After(NodeIdType),
    /// The source node should be inserted before the node with this node id.
    Before(NodeIdType),
}

/// The global settings the tree view will use.
#[derive(Clone, Debug)]
pub struct TreeViewSettings {
    /// Override the indent value for the tree view.
    ///
    /// By default, this value is 'None' which means that the indent value from the
    /// current UI is used. If this value is set, this value will be used as the indent
    /// value without affecting the ui's indent value.
    pub override_indent: Option<f32>,
    /// Override whether or not the background of the nodes should striped.
    ///
    /// By default, this value is 'None' which means that the striped setting from the
    /// current UI style is used. If this value is set, it will be used without
    /// affecting the ui's value.
    pub override_striped: Option<bool>,
    /// The style of the indent hint to show the indentation level.
    pub indent_hint_style: IndentHintStyle,
    /// The row layout for this tree.
    pub row_layout: RowLayout,
    /// The minimum width the tree can have.
    pub min_width: f32,
    /// The minimum height the tree can have.
    pub min_height: f32,
    /// If the tree view is allowed to select multiple nodes at once.
    /// Default is true.
    pub allow_multi_select: bool,
    /// Specifies the modifier that the user is require to press for a range based multi selection.
    /// A range based selection selects all nodes between the selected node and a previously selected pivot node.
    /// Default is `egui::Modifiers::SHIFT`
    pub range_selection_modifier: Modifiers,
    /// Specified the modifier that the user is required to press for a set based multi selection.
    /// A set based selection adds/removes the selected node to/from the multi selection.
    /// Default is `egui::Modifiers::COMMAND`
    pub set_selection_modifier: Modifiers,
    /// If the nodes in the tree view are allowed to be dragged and dropped.
    /// Default is true.
    pub allow_drag_and_drop: bool,
    /// The default height of a node.
    /// If none is set the default height will be `interact_size.y` from `egui::style::Spacing`.
    pub default_node_height: Option<f32>,
}

impl Default for TreeViewSettings {
    fn default() -> Self {
        Self {
            override_indent: None,
            override_striped: None,
            indent_hint_style: Default::default(),
            row_layout: Default::default(),
            min_width: 0.0,
            min_height: 0.0,
            allow_multi_select: true,
            range_selection_modifier: Modifiers::SHIFT,
            set_selection_modifier: Modifiers::COMMAND,
            allow_drag_and_drop: true,
            default_node_height: None,
        }
    }
}

/// Style of the vertical line to show the indentation level.
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub enum IndentHintStyle {
    /// No indent hint is shown.
    None,
    /// A single vertical line is show for the full height of the directory.
    /// ```text
    /// v Foo
    /// │  Alice
    /// │  v Bar
    /// │  │ Bob
    /// │  │  v Baz
    /// │  │  │ Clair
    /// │  │  │ Denis
    /// │  Emil
    /// ```
    Line,
    /// A vertical line is show with horizontal hooks to the child nodes of the directory.
    /// ```text
    /// v Foo
    /// ├─ Alice
    /// ├─ v Bar
    /// │  ├─ Bob
    /// │  └─ v Baz
    /// │     ├─ Clair
    /// │     └─ Denis
    /// └─ Emil
    /// ```
    #[default]
    Hook,
}

/// How rows in the tree are laid out.
///
/// Each row in the tree is made up of three elements. A closer,
/// an icon and a label. The layout of these elements is controlled
/// by this value.
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub enum RowLayout {
    /// No icons are displayed.
    /// Directories only show the closer and the label.
    /// Leaves only show the label and allocate no additional space for a closer.
    /// Labels between leaves and directories do not align.
    Compact,
    /// The labels of leaves and directories are aligned.
    /// Icons are displayed for leaves only.
    CompactAlignedLabels,
    /// The icons of leaves and directories are aligned.
    /// If a leaf or directory does not show an icon, the label will fill the
    /// space. Labels between leaves and directories can be misaligned.
    #[default]
    AlignedIcons,
    /// The labels of leaves and directories are aligned.
    /// If a leaf or directory does not show an icon, the label will not fill
    /// the space.
    AlignedIconsAndLabels,
}

/// An action the tree view would like to take as a result
/// of some user input like drag and drop.
#[derive(Clone, Debug)]
pub enum Action<NodeIdType> {
    /// Set the selected node to be this.
    SetSelected(Vec<NodeIdType>),
    /// Move set of nodes from one place to another.
    Move(DragAndDrop<NodeIdType>),
    /// An in-process drag and drop action where the node
    /// is currently dragged but not yet dropped.
    Drag(DragAndDrop<NodeIdType>),
    /// Activate a set of nodes.
    ///
    /// When pressing enter or double clicking on a selection, the tree
    /// view will create this action.
    /// Can be used to open a file for example.
    Activate(Activate<NodeIdType>),
    /// Indicates that nodes are being dragged outside the TreeView
    /// (but not yet dropped).
    DragExternal(DragAndDropExternal<NodeIdType>),
    /// Triggered when dragged nodes are released outside the TreeView.
    /// Indicates that the nodes should be moved to an
    /// external target (e.g., another panel).
    MoveExternal(DragAndDropExternal<NodeIdType>),
}

/// Represents a drag-and-drop interaction where nodes are dragged outside the TreeView.
/// Used to handle external drops (e.g., onto another UI component or the workspace).
#[derive(Clone, Debug)]
pub struct DragAndDropExternal<NodeIdType> {
    /// The nodes that are being dragged
    pub source: Vec<NodeIdType>,
    /// The position where the dragged nodes are dropped outside of the TreeView.
    pub position: egui::Pos2,
}

/// Information about drag and drop action that is currently
/// happening on the tree.
#[derive(Clone, Debug)]
pub struct DragAndDrop<NodeIdType> {
    /// The nodes that are being dragged
    pub source: Vec<NodeIdType>,
    /// The node where the dragged nodes are dropped.
    pub target: NodeIdType,
    /// The position where the dragged nodes are dropped inside the target node.
    pub position: DirPosition<NodeIdType>,
    /// The shape index of the drop marker.
    drop_marker_idx: ShapeIdx,
}
impl<NodeIdType> DragAndDrop<NodeIdType> {
    /// Remove the drop marker from the tree view.
    ///
    /// Use this to remove the drop marker if a proposed drag and drop action
    /// is disallowed.
    pub fn remove_drop_marker(&self, ui: &mut Ui) {
        ui.painter().set(self.drop_marker_idx, Shape::Noop);
    }
}

/// Information about the `Activate` action in the tree.
#[derive(Clone, Debug)]
pub struct Activate<NodeIdType> {
    /// The nodes that are being activated.
    pub selected: Vec<NodeIdType>,
    /// The modifiers that were active when this action was generated.
    pub modifiers: Modifiers,
}

/// Interact with the ui without egui adding any extra space.
fn interact_no_expansion(ui: &mut Ui, rect: Rect, id: Id, sense: Sense) -> Response {
    let spacing_before = ui.spacing().clone();
    ui.spacing_mut().item_spacing = Vec2::ZERO;
    let res = ui.interact(rect, id, sense);
    *ui.spacing_mut() = spacing_before;
    res
}

enum DropQuarter {
    Top,
    MiddleTop,
    MiddleBottom,
    Bottom,
}

impl DropQuarter {
    fn new(range: Rangef, cursor_pos: f32) -> Option<DropQuarter> {
        pub const DROP_LINE_HOVER_HEIGHT: f32 = 5.0;

        let h0 = range.min;
        let h1 = range.min + DROP_LINE_HOVER_HEIGHT;
        let h2 = range.center();
        let h3 = range.max - DROP_LINE_HOVER_HEIGHT;
        let h4 = range.max;

        match cursor_pos {
            y if y >= h0 && y < h1 => Some(Self::Top),
            y if y >= h1 && y < h2 => Some(Self::MiddleTop),
            y if y >= h2 && y < h3 => Some(Self::MiddleBottom),
            y if y >= h3 && y < h4 => Some(Self::Bottom),
            _ => None,
        }
    }
}

struct UiData {
    interaction: Response,
    drag_layer: LayerId,
    drag_layer_offset: Vec2,
    has_focus: bool,
    drop_marker_idx: ShapeIdx,
}

/// When you ast a rectangle if it contains a point it does so inclusive the upper bound.
/// like this: min <= p <= max
/// Visually the rectangle is displayed exclusive the upper bound.
/// like this: min <= p < max
///
/// This means that two rectangles can not overlap visually but overlap when aksing if a point
/// is contained in them.
/// This check if a point is contained exclusive the upper bound.
fn rect_contains_visually(rect: &Rect, pos: &Pos2) -> bool {
    rect.min.x <= pos.x && pos.x < rect.max.x && rect.min.y <= pos.y && pos.y < rect.max.y
}

enum Input<NodeIdType> {
    DragStarted {
        pos: Pos2,
        selected_node_dragged: bool,
        visited_selected_nodes: HashSet<NodeIdType>,
        simplified_dragged: Vec<NodeIdType>,
    },
    Dragged(Pos2),
    SecondaryClick(Pos2),
    Click {
        pos: Pos2,
        double: bool,
        modifiers: Modifiers,
        activatable_nodes: Vec<NodeIdType>,
        shift_click_nodes: Option<Vec<NodeIdType>>,
    },
    KeyLeft,
    KeyRight {
        select_next: bool,
    },
    KeyUp {
        previous_node: Option<(NodeIdType, Rect)>,
    },
    KeyUpAndCommand {
        previous_node: Option<(NodeIdType, Rect)>,
    },
    KeyUpAndShift {
        previous_node: Option<(NodeIdType, Rect)>,
        nodes_to_select: Option<Vec<NodeIdType>>,
        next_cursor: Option<(NodeIdType, Rect)>,
    },
    KeyDown(bool),
    KeyDownAndCommand {
        is_next: bool,
    },
    KeyDownAndShift {
        nodes_to_select: Option<Vec<NodeIdType>>,
        next_cursor: Option<(NodeIdType, Rect)>,
        is_next: bool,
    },
    KeySpace,
    CollectActivatableNodes {
        activatable_nodes: Vec<NodeIdType>,
    },
    None,
}

fn get_input<NodeIdType>(
    ui: &Ui,
    interaction: &Response,
    id: Id,
    settings: &TreeViewSettings,
) -> Input<NodeIdType> {
    let press_origin = ui.input(|i| i.pointer.press_origin());
    let pointer_pos = ui.input(|i| i.pointer.interact_pos());
    let modifiers = ui.input(|i| i.modifiers);

    if interaction.context_menu_opened() {
        if interaction.secondary_clicked() {
            return Input::SecondaryClick(
                pointer_pos.expect("If the tree view was clicked it must have a pointer position"),
            );
        }
        return Input::None;
    }

    if interaction.drag_started_by(PointerButton::Primary) && settings.allow_drag_and_drop {
        return Input::DragStarted {
            pos: press_origin
                .expect("If a drag has started it must have a position where the press started"),
            selected_node_dragged: false,
            visited_selected_nodes: HashSet::new(),
            simplified_dragged: Vec::new(),
        };
    }
    if (interaction.dragged_by(PointerButton::Primary)
        || interaction.drag_stopped_by(PointerButton::Primary))
        && settings.allow_drag_and_drop
    {
        return Input::Dragged(
            pointer_pos.expect("If the tree view is dragged it must have a pointer position"),
        );
    }
    if interaction.secondary_clicked() {
        return Input::SecondaryClick(
            pointer_pos.expect("If the tree view was clicked it must have a pointer position"),
        );
    }
    if interaction.clicked_by(PointerButton::Primary)
        || interaction.drag_started_by(PointerButton::Primary) && !settings.allow_drag_and_drop
    {
        return Input::Click {
            pos: pointer_pos.expect("If the tree view was clicked it must have a pointer position"),
            double: interaction.double_clicked(),
            modifiers,
            activatable_nodes: Vec::new(),
            shift_click_nodes: None,
        };
    }
    if !ui.memory(|m| m.has_focus(id)) {
        return Input::None;
    }
    if ui.input(|i| i.key_pressed(Key::ArrowLeft)) {
        return Input::KeyLeft;
    }
    if ui.input(|i| i.key_pressed(Key::ArrowRight)) {
        return Input::KeyRight { select_next: false };
    }
    if ui.input(|i| i.key_pressed(Key::ArrowUp)) {
        if modifiers.matches_exact(settings.range_selection_modifier) {
            return Input::KeyUpAndShift {
                previous_node: None,
                nodes_to_select: None,
                next_cursor: None,
            };
        }
        if modifiers.matches_exact(settings.set_selection_modifier) {
            return Input::KeyUpAndCommand {
                previous_node: None,
            };
        }
        return Input::KeyUp {
            previous_node: None,
        };
    }
    if ui.input(|i| i.key_pressed(Key::ArrowDown)) {
        if modifiers.matches_exact(settings.range_selection_modifier) {
            return Input::KeyDownAndShift {
                nodes_to_select: None,
                next_cursor: None,
                is_next: false,
            };
        }
        if modifiers.matches_exact(settings.set_selection_modifier) {
            return Input::KeyDownAndCommand { is_next: false };
        }
        return Input::KeyDown(false);
    }
    if ui.input(|i| i.key_pressed(Key::Space)) {
        return Input::KeySpace;
    }
    if ui.input(|i| i.key_pressed(Key::Enter)) {
        return Input::CollectActivatableNodes {
            activatable_nodes: Vec::new(),
        };
    }
    Input::None
}