pane.rs

  1use super::{ItemViewHandle, SplitDirection};
  2use crate::{ItemHandle, ItemView, Settings, WeakItemViewHandle, Workspace};
  3use collections::{HashMap, VecDeque};
  4use gpui::{
  5    action,
  6    elements::*,
  7    geometry::{rect::RectF, vector::vec2f},
  8    keymap::Binding,
  9    platform::{CursorStyle, NavigationDirection},
 10    AnyViewHandle, Entity, MutableAppContext, Quad, RenderContext, Task, View, ViewContext,
 11    ViewHandle, WeakViewHandle,
 12};
 13use project::ProjectPath;
 14use std::{
 15    any::{Any, TypeId},
 16    cell::RefCell,
 17    cmp, mem,
 18    rc::Rc,
 19};
 20use util::ResultExt;
 21
 22action!(Split, SplitDirection);
 23action!(ActivateItem, usize);
 24action!(ActivatePrevItem);
 25action!(ActivateNextItem);
 26action!(CloseActiveItem);
 27action!(CloseInactiveItems);
 28action!(CloseItem, usize);
 29action!(GoBack, Option<WeakViewHandle<Pane>>);
 30action!(GoForward, Option<WeakViewHandle<Pane>>);
 31
 32const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
 33
 34pub fn init(cx: &mut MutableAppContext) {
 35    cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
 36        pane.activate_item(action.0, cx);
 37    });
 38    cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
 39        pane.activate_prev_item(cx);
 40    });
 41    cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
 42        pane.activate_next_item(cx);
 43    });
 44    cx.add_action(|pane: &mut Pane, _: &CloseActiveItem, cx| {
 45        pane.close_active_item(cx);
 46    });
 47    cx.add_action(|pane: &mut Pane, _: &CloseInactiveItems, cx| {
 48        pane.close_inactive_items(cx);
 49    });
 50    cx.add_action(|pane: &mut Pane, action: &CloseItem, cx| {
 51        pane.close_item(action.0, cx);
 52    });
 53    cx.add_action(|pane: &mut Pane, action: &Split, cx| {
 54        pane.split(action.0, cx);
 55    });
 56    cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
 57        Pane::go_back(
 58            workspace,
 59            action
 60                .0
 61                .as_ref()
 62                .and_then(|weak_handle| weak_handle.upgrade(cx)),
 63            cx,
 64        )
 65        .detach();
 66    });
 67    cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
 68        Pane::go_forward(
 69            workspace,
 70            action
 71                .0
 72                .as_ref()
 73                .and_then(|weak_handle| weak_handle.upgrade(cx)),
 74            cx,
 75        )
 76        .detach();
 77    });
 78
 79    cx.add_bindings(vec![
 80        Binding::new("shift-cmd-{", ActivatePrevItem, Some("Pane")),
 81        Binding::new("shift-cmd-}", ActivateNextItem, Some("Pane")),
 82        Binding::new("cmd-w", CloseActiveItem, Some("Pane")),
 83        Binding::new("alt-cmd-w", CloseInactiveItems, Some("Pane")),
 84        Binding::new("cmd-k up", Split(SplitDirection::Up), Some("Pane")),
 85        Binding::new("cmd-k down", Split(SplitDirection::Down), Some("Pane")),
 86        Binding::new("cmd-k left", Split(SplitDirection::Left), Some("Pane")),
 87        Binding::new("cmd-k right", Split(SplitDirection::Right), Some("Pane")),
 88        Binding::new("ctrl--", GoBack(None), Some("Pane")),
 89        Binding::new("shift-ctrl-_", GoForward(None), Some("Pane")),
 90    ]);
 91}
 92
 93pub enum Event {
 94    Activate,
 95    Remove,
 96    Split(SplitDirection),
 97}
 98
 99pub struct Pane {
100    item_views: Vec<(usize, Box<dyn ItemViewHandle>)>,
101    active_item_index: usize,
102    nav_history: Rc<RefCell<NavHistory>>,
103    toolbars: HashMap<TypeId, Box<dyn ToolbarHandle>>,
104    active_toolbar_type: Option<TypeId>,
105    active_toolbar_visible: bool,
106}
107
108pub trait Toolbar: View {
109    fn active_item_changed(
110        &mut self,
111        item: Option<Box<dyn ItemViewHandle>>,
112        cx: &mut ViewContext<Self>,
113    ) -> bool;
114    fn on_dismiss(&mut self, cx: &mut ViewContext<Self>);
115}
116
117trait ToolbarHandle {
118    fn active_item_changed(
119        &self,
120        item: Option<Box<dyn ItemViewHandle>>,
121        cx: &mut MutableAppContext,
122    ) -> bool;
123    fn on_dismiss(&self, cx: &mut MutableAppContext);
124    fn to_any(&self) -> AnyViewHandle;
125}
126
127pub struct ItemNavHistory {
128    history: Rc<RefCell<NavHistory>>,
129    item_view: Rc<dyn WeakItemViewHandle>,
130}
131
132#[derive(Default)]
133pub struct NavHistory {
134    mode: NavigationMode,
135    backward_stack: VecDeque<NavigationEntry>,
136    forward_stack: VecDeque<NavigationEntry>,
137    paths_by_item: HashMap<usize, ProjectPath>,
138}
139
140#[derive(Copy, Clone)]
141enum NavigationMode {
142    Normal,
143    GoingBack,
144    GoingForward,
145    Disabled,
146}
147
148impl Default for NavigationMode {
149    fn default() -> Self {
150        Self::Normal
151    }
152}
153
154pub struct NavigationEntry {
155    pub item_view: Rc<dyn WeakItemViewHandle>,
156    pub data: Option<Box<dyn Any>>,
157}
158
159impl Pane {
160    pub fn new() -> Self {
161        Self {
162            item_views: Vec::new(),
163            active_item_index: 0,
164            nav_history: Default::default(),
165            toolbars: Default::default(),
166            active_toolbar_type: Default::default(),
167            active_toolbar_visible: false,
168        }
169    }
170
171    pub fn nav_history(&self) -> &Rc<RefCell<NavHistory>> {
172        &self.nav_history
173    }
174
175    pub fn activate(&self, cx: &mut ViewContext<Self>) {
176        cx.emit(Event::Activate);
177    }
178
179    pub fn go_back(
180        workspace: &mut Workspace,
181        pane: Option<ViewHandle<Pane>>,
182        cx: &mut ViewContext<Workspace>,
183    ) -> Task<()> {
184        Self::navigate_history(
185            workspace,
186            pane.unwrap_or_else(|| workspace.active_pane().clone()),
187            NavigationMode::GoingBack,
188            cx,
189        )
190    }
191
192    pub fn go_forward(
193        workspace: &mut Workspace,
194        pane: Option<ViewHandle<Pane>>,
195        cx: &mut ViewContext<Workspace>,
196    ) -> Task<()> {
197        Self::navigate_history(
198            workspace,
199            pane.unwrap_or_else(|| workspace.active_pane().clone()),
200            NavigationMode::GoingForward,
201            cx,
202        )
203    }
204
205    fn navigate_history(
206        workspace: &mut Workspace,
207        pane: ViewHandle<Pane>,
208        mode: NavigationMode,
209        cx: &mut ViewContext<Workspace>,
210    ) -> Task<()> {
211        workspace.activate_pane(pane.clone(), cx);
212
213        let to_load = pane.update(cx, |pane, cx| {
214            // Retrieve the weak item handle from the history.
215            let entry = pane.nav_history.borrow_mut().pop(mode)?;
216
217            // If the item is still present in this pane, then activate it.
218            if let Some(index) = entry
219                .item_view
220                .upgrade(cx)
221                .and_then(|v| pane.index_for_item_view(v.as_ref()))
222            {
223                if let Some(item_view) = pane.active_item() {
224                    pane.nav_history.borrow_mut().set_mode(mode);
225                    item_view.deactivated(cx);
226                    pane.nav_history
227                        .borrow_mut()
228                        .set_mode(NavigationMode::Normal);
229                }
230
231                pane.active_item_index = index;
232                pane.focus_active_item(cx);
233                if let Some(data) = entry.data {
234                    pane.active_item()?.navigate(data, cx);
235                }
236                cx.notify();
237                None
238            }
239            // If the item is no longer present in this pane, then retrieve its
240            // project path in order to reopen it.
241            else {
242                pane.nav_history
243                    .borrow_mut()
244                    .paths_by_item
245                    .get(&entry.item_view.id())
246                    .cloned()
247                    .map(|project_path| (project_path, entry))
248            }
249        });
250
251        if let Some((project_path, entry)) = to_load {
252            // If the item was no longer present, then load it again from its previous path.
253            let pane = pane.downgrade();
254            let task = workspace.load_path(project_path, cx);
255            cx.spawn(|workspace, mut cx| async move {
256                let item = task.await;
257                if let Some(pane) = pane.upgrade(&cx) {
258                    if let Some(item) = item.log_err() {
259                        workspace.update(&mut cx, |workspace, cx| {
260                            pane.update(cx, |p, _| p.nav_history.borrow_mut().set_mode(mode));
261                            let item_view = workspace.open_item_in_pane(item, &pane, cx);
262                            pane.update(cx, |p, _| {
263                                p.nav_history.borrow_mut().set_mode(NavigationMode::Normal)
264                            });
265
266                            if let Some(data) = entry.data {
267                                item_view.navigate(data, cx);
268                            }
269                        });
270                    } else {
271                        workspace
272                            .update(&mut cx, |workspace, cx| {
273                                Self::navigate_history(workspace, pane, mode, cx)
274                            })
275                            .await;
276                    }
277                }
278            })
279        } else {
280            Task::ready(())
281        }
282    }
283
284    pub fn open_item<T>(
285        &mut self,
286        item_handle: T,
287        workspace: &Workspace,
288        cx: &mut ViewContext<Self>,
289    ) -> Box<dyn ItemViewHandle>
290    where
291        T: 'static + ItemHandle,
292    {
293        for (ix, (item_id, item_view)) in self.item_views.iter().enumerate() {
294            if *item_id == item_handle.id() {
295                let item_view = item_view.boxed_clone();
296                self.activate_item(ix, cx);
297                return item_view;
298            }
299        }
300
301        let item_view =
302            item_handle.add_view(cx.window_id(), workspace, self.nav_history.clone(), cx);
303        self.add_item_view(item_view.boxed_clone(), cx);
304        item_view
305    }
306
307    pub fn add_item_view(
308        &mut self,
309        mut item_view: Box<dyn ItemViewHandle>,
310        cx: &mut ViewContext<Self>,
311    ) {
312        item_view.added_to_pane(cx);
313        let item_idx = cmp::min(self.active_item_index + 1, self.item_views.len());
314        self.item_views
315            .insert(item_idx, (item_view.item(cx).id(), item_view));
316        self.activate_item(item_idx, cx);
317        cx.notify();
318    }
319
320    pub fn contains_item(&self, item: &dyn ItemHandle) -> bool {
321        let item_id = item.id();
322        self.item_views
323            .iter()
324            .any(|(existing_item_id, _)| *existing_item_id == item_id)
325    }
326
327    pub fn item_views(&self) -> impl Iterator<Item = &Box<dyn ItemViewHandle>> {
328        self.item_views.iter().map(|(_, view)| view)
329    }
330
331    pub fn active_item(&self) -> Option<Box<dyn ItemViewHandle>> {
332        self.item_views
333            .get(self.active_item_index)
334            .map(|(_, view)| view.clone())
335    }
336
337    pub fn index_for_item_view(&self, item_view: &dyn ItemViewHandle) -> Option<usize> {
338        self.item_views
339            .iter()
340            .position(|(_, i)| i.id() == item_view.id())
341    }
342
343    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
344        self.item_views.iter().position(|(id, _)| *id == item.id())
345    }
346
347    pub fn activate_item(&mut self, index: usize, cx: &mut ViewContext<Self>) {
348        if index < self.item_views.len() {
349            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
350            if prev_active_item_ix != self.active_item_index
351                && prev_active_item_ix < self.item_views.len()
352            {
353                self.item_views[prev_active_item_ix].1.deactivated(cx);
354            }
355            self.update_active_toolbar(cx);
356            self.focus_active_item(cx);
357            self.activate(cx);
358            cx.notify();
359        }
360    }
361
362    pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
363        let mut index = self.active_item_index;
364        if index > 0 {
365            index -= 1;
366        } else if self.item_views.len() > 0 {
367            index = self.item_views.len() - 1;
368        }
369        self.activate_item(index, cx);
370    }
371
372    pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
373        let mut index = self.active_item_index;
374        if index + 1 < self.item_views.len() {
375            index += 1;
376        } else {
377            index = 0;
378        }
379        self.activate_item(index, cx);
380    }
381
382    pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) {
383        if !self.item_views.is_empty() {
384            self.close_item(self.item_views[self.active_item_index].1.id(), cx)
385        }
386    }
387
388    pub fn close_inactive_items(&mut self, cx: &mut ViewContext<Self>) {
389        if !self.item_views.is_empty() {
390            let active_item_id = self.item_views[self.active_item_index].1.id();
391            self.close_items(cx, |id| id != active_item_id);
392        }
393    }
394
395    pub fn close_item(&mut self, view_id_to_close: usize, cx: &mut ViewContext<Self>) {
396        self.close_items(cx, |view_id| view_id == view_id_to_close);
397    }
398
399    pub fn close_items(
400        &mut self,
401        cx: &mut ViewContext<Self>,
402        should_close: impl Fn(usize) -> bool,
403    ) {
404        let mut item_ix = 0;
405        let mut new_active_item_index = self.active_item_index;
406        self.item_views.retain(|(_, item_view)| {
407            if should_close(item_view.id()) {
408                if item_ix == self.active_item_index {
409                    item_view.deactivated(cx);
410                }
411
412                if item_ix < self.active_item_index {
413                    new_active_item_index -= 1;
414                }
415
416                let mut nav_history = self.nav_history.borrow_mut();
417                if let Some(path) = item_view.project_path(cx) {
418                    nav_history.paths_by_item.insert(item_view.id(), path);
419                } else {
420                    nav_history.paths_by_item.remove(&item_view.id());
421                }
422
423                item_ix += 1;
424                false
425            } else {
426                item_ix += 1;
427                true
428            }
429        });
430
431        if self.item_views.is_empty() {
432            cx.emit(Event::Remove);
433        } else {
434            self.active_item_index = cmp::min(new_active_item_index, self.item_views.len() - 1);
435            self.focus_active_item(cx);
436            self.activate(cx);
437        }
438        self.update_active_toolbar(cx);
439
440        cx.notify();
441    }
442
443    fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
444        if let Some(active_item) = self.active_item() {
445            cx.focus(active_item);
446        }
447    }
448
449    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
450        cx.emit(Event::Split(direction));
451    }
452
453    pub fn show_toolbar<F, V>(&mut self, cx: &mut ViewContext<Self>, build_toolbar: F)
454    where
455        F: FnOnce(&mut ViewContext<V>) -> V,
456        V: Toolbar,
457    {
458        let type_id = TypeId::of::<V>();
459        if self.active_toolbar_type != Some(type_id) {
460            self.dismiss_toolbar(cx);
461
462            let active_item = self.active_item();
463            self.toolbars
464                .entry(type_id)
465                .or_insert_with(|| Box::new(cx.add_view(build_toolbar)));
466
467            self.active_toolbar_type = Some(type_id);
468            self.active_toolbar_visible =
469                self.toolbars[&type_id].active_item_changed(active_item, cx);
470            cx.notify();
471        }
472    }
473
474    pub fn dismiss_toolbar(&mut self, cx: &mut ViewContext<Self>) {
475        if let Some(active_toolbar_type) = self.active_toolbar_type.take() {
476            self.toolbars
477                .get_mut(&active_toolbar_type)
478                .unwrap()
479                .on_dismiss(cx);
480            self.active_toolbar_visible = false;
481            self.focus_active_item(cx);
482            cx.notify();
483        }
484    }
485
486    pub fn toolbar<T: Toolbar>(&self) -> Option<ViewHandle<T>> {
487        self.toolbars
488            .get(&TypeId::of::<T>())
489            .and_then(|toolbar| toolbar.to_any().downcast())
490    }
491
492    pub fn active_toolbar(&self) -> Option<AnyViewHandle> {
493        let type_id = self.active_toolbar_type?;
494        let toolbar = self.toolbars.get(&type_id)?;
495        if self.active_toolbar_visible {
496            Some(toolbar.to_any())
497        } else {
498            None
499        }
500    }
501
502    fn update_active_toolbar(&mut self, cx: &mut ViewContext<Self>) {
503        let active_item = self.item_views.get(self.active_item_index);
504        for (toolbar_type_id, toolbar) in &self.toolbars {
505            let visible = toolbar.active_item_changed(active_item.map(|i| i.1.clone()), cx);
506            if Some(*toolbar_type_id) == self.active_toolbar_type {
507                self.active_toolbar_visible = visible;
508            }
509        }
510    }
511
512    fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
513        let theme = cx.app_state::<Settings>().theme.clone();
514
515        enum Tabs {}
516        let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
517            let mut row = Flex::row();
518            for (ix, (_, item_view)) in self.item_views.iter().enumerate() {
519                let is_active = ix == self.active_item_index;
520
521                row.add_child({
522                    let tab_style = if is_active {
523                        theme.workspace.active_tab.clone()
524                    } else {
525                        theme.workspace.tab.clone()
526                    };
527                    let title = item_view.tab_content(&tab_style, cx);
528
529                    let mut style = if is_active {
530                        theme.workspace.active_tab.clone()
531                    } else {
532                        theme.workspace.tab.clone()
533                    };
534                    if ix == 0 {
535                        style.container.border.left = false;
536                    }
537
538                    EventHandler::new(
539                        Container::new(
540                            Flex::row()
541                                .with_child(
542                                    Align::new({
543                                        let diameter = 7.0;
544                                        let icon_color = if item_view.has_conflict(cx) {
545                                            Some(style.icon_conflict)
546                                        } else if item_view.is_dirty(cx) {
547                                            Some(style.icon_dirty)
548                                        } else {
549                                            None
550                                        };
551
552                                        ConstrainedBox::new(
553                                            Canvas::new(move |bounds, _, cx| {
554                                                if let Some(color) = icon_color {
555                                                    let square = RectF::new(
556                                                        bounds.origin(),
557                                                        vec2f(diameter, diameter),
558                                                    );
559                                                    cx.scene.push_quad(Quad {
560                                                        bounds: square,
561                                                        background: Some(color),
562                                                        border: Default::default(),
563                                                        corner_radius: diameter / 2.,
564                                                    });
565                                                }
566                                            })
567                                            .boxed(),
568                                        )
569                                        .with_width(diameter)
570                                        .with_height(diameter)
571                                        .boxed()
572                                    })
573                                    .boxed(),
574                                )
575                                .with_child(
576                                    Container::new(Align::new(title).boxed())
577                                        .with_style(ContainerStyle {
578                                            margin: Margin {
579                                                left: style.spacing,
580                                                right: style.spacing,
581                                                ..Default::default()
582                                            },
583                                            ..Default::default()
584                                        })
585                                        .boxed(),
586                                )
587                                .with_child(
588                                    Align::new(
589                                        ConstrainedBox::new(if mouse_state.hovered {
590                                            let item_id = item_view.id();
591                                            enum TabCloseButton {}
592                                            let icon = Svg::new("icons/x.svg");
593                                            MouseEventHandler::new::<TabCloseButton, _, _>(
594                                                item_id,
595                                                cx,
596                                                |mouse_state, _| {
597                                                    if mouse_state.hovered {
598                                                        icon.with_color(style.icon_close_active)
599                                                            .boxed()
600                                                    } else {
601                                                        icon.with_color(style.icon_close).boxed()
602                                                    }
603                                                },
604                                            )
605                                            .with_padding(Padding::uniform(4.))
606                                            .with_cursor_style(CursorStyle::PointingHand)
607                                            .on_click(move |cx| {
608                                                cx.dispatch_action(CloseItem(item_id))
609                                            })
610                                            .named("close-tab-icon")
611                                        } else {
612                                            Empty::new().boxed()
613                                        })
614                                        .with_width(style.icon_width)
615                                        .boxed(),
616                                    )
617                                    .boxed(),
618                                )
619                                .boxed(),
620                        )
621                        .with_style(style.container)
622                        .boxed(),
623                    )
624                    .on_mouse_down(move |cx| {
625                        cx.dispatch_action(ActivateItem(ix));
626                        true
627                    })
628                    .boxed()
629                })
630            }
631
632            row.add_child(
633                Empty::new()
634                    .contained()
635                    .with_border(theme.workspace.tab.container.border)
636                    .flexible(0., true)
637                    .named("filler"),
638            );
639
640            row.boxed()
641        });
642
643        ConstrainedBox::new(tabs.boxed())
644            .with_height(theme.workspace.tab.height)
645            .named("tabs")
646    }
647}
648
649impl Entity for Pane {
650    type Event = Event;
651}
652
653impl View for Pane {
654    fn ui_name() -> &'static str {
655        "Pane"
656    }
657
658    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
659        let this = cx.handle();
660
661        EventHandler::new(if let Some(active_item) = self.active_item() {
662            Flex::column()
663                .with_child(self.render_tabs(cx))
664                .with_children(
665                    self.active_toolbar()
666                        .as_ref()
667                        .map(|view| ChildView::new(view).boxed()),
668                )
669                .with_child(ChildView::new(active_item).flexible(1., true).boxed())
670                .boxed()
671        } else {
672            Empty::new().boxed()
673        })
674        .on_navigate_mouse_down(move |direction, cx| {
675            let this = this.clone();
676            match direction {
677                NavigationDirection::Back => cx.dispatch_action(GoBack(Some(this))),
678                NavigationDirection::Forward => cx.dispatch_action(GoForward(Some(this))),
679            }
680
681            true
682        })
683        .named("pane")
684    }
685
686    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
687        self.focus_active_item(cx);
688    }
689}
690
691impl<T: Toolbar> ToolbarHandle for ViewHandle<T> {
692    fn active_item_changed(
693        &self,
694        item: Option<Box<dyn ItemViewHandle>>,
695        cx: &mut MutableAppContext,
696    ) -> bool {
697        self.update(cx, |this, cx| this.active_item_changed(item, cx))
698    }
699
700    fn on_dismiss(&self, cx: &mut MutableAppContext) {
701        self.update(cx, |this, cx| this.on_dismiss(cx));
702    }
703
704    fn to_any(&self) -> AnyViewHandle {
705        self.into()
706    }
707}
708
709impl ItemNavHistory {
710    pub fn new<T: ItemView>(history: Rc<RefCell<NavHistory>>, item_view: &ViewHandle<T>) -> Self {
711        Self {
712            history,
713            item_view: Rc::new(item_view.downgrade()),
714        }
715    }
716
717    pub fn history(&self) -> Rc<RefCell<NavHistory>> {
718        self.history.clone()
719    }
720
721    pub fn push<D: 'static + Any>(&self, data: Option<D>) {
722        self.history.borrow_mut().push(data, self.item_view.clone());
723    }
724}
725
726impl NavHistory {
727    pub fn disable(&mut self) {
728        self.mode = NavigationMode::Disabled;
729    }
730
731    pub fn enable(&mut self) {
732        self.mode = NavigationMode::Normal;
733    }
734
735    pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
736        self.backward_stack.pop_back()
737    }
738
739    pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
740        self.forward_stack.pop_back()
741    }
742
743    fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
744        match mode {
745            NavigationMode::Normal | NavigationMode::Disabled => None,
746            NavigationMode::GoingBack => self.pop_backward(),
747            NavigationMode::GoingForward => self.pop_forward(),
748        }
749    }
750
751    fn set_mode(&mut self, mode: NavigationMode) {
752        self.mode = mode;
753    }
754
755    pub fn push<D: 'static + Any>(
756        &mut self,
757        data: Option<D>,
758        item_view: Rc<dyn WeakItemViewHandle>,
759    ) {
760        match self.mode {
761            NavigationMode::Disabled => {}
762            NavigationMode::Normal => {
763                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
764                    self.backward_stack.pop_front();
765                }
766                self.backward_stack.push_back(NavigationEntry {
767                    item_view,
768                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
769                });
770                self.forward_stack.clear();
771            }
772            NavigationMode::GoingBack => {
773                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
774                    self.forward_stack.pop_front();
775                }
776                self.forward_stack.push_back(NavigationEntry {
777                    item_view,
778                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
779                });
780            }
781            NavigationMode::GoingForward => {
782                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
783                    self.backward_stack.pop_front();
784                }
785                self.backward_stack.push_back(NavigationEntry {
786                    item_view,
787                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
788                });
789            }
790        }
791    }
792}