pane.rs

  1use super::{ItemHandle, SplitDirection};
  2use crate::{Item, Settings, WeakItemHandle, 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::{ProjectEntryId, 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    items: Vec<(Option<ProjectEntryId>, Box<dyn ItemHandle>)>,
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 ItemHandle>>,
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 ItemHandle>>,
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: Rc<dyn WeakItemHandle>,
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: Rc<dyn WeakItemHandle>,
156    pub data: Option<Box<dyn Any>>,
157}
158
159impl Pane {
160    pub fn new() -> Self {
161        Self {
162            items: 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
220                .upgrade(cx)
221                .and_then(|v| pane.index_for_item(v.as_ref()))
222            {
223                if let Some(item) = pane.active_item() {
224                    pane.nav_history.borrow_mut().set_mode(mode);
225                    item.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.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 task = task.await;
257                if let Some(pane) = pane.upgrade(&cx) {
258                    if let Some((project_entry_id, build_item)) = task.log_err() {
259                        pane.update(&mut cx, |pane, cx| {
260                            pane.nav_history.borrow_mut().set_mode(mode);
261                            let item = pane.open_item(project_entry_id, cx, build_item);
262                            pane.nav_history
263                                .borrow_mut()
264                                .set_mode(NavigationMode::Normal);
265                            if let Some(data) = entry.data {
266                                item.navigate(data, cx);
267                            }
268                        });
269                    } else {
270                        workspace
271                            .update(&mut cx, |workspace, cx| {
272                                Self::navigate_history(workspace, pane, mode, cx)
273                            })
274                            .await;
275                    }
276                }
277            })
278        } else {
279            Task::ready(())
280        }
281    }
282
283    pub fn open_item(
284        &mut self,
285        project_entry_id: ProjectEntryId,
286        cx: &mut ViewContext<Self>,
287        build_item: impl FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
288    ) -> Box<dyn ItemHandle> {
289        for (ix, (existing_entry_id, item)) in self.items.iter().enumerate() {
290            if *existing_entry_id == Some(project_entry_id) {
291                let item = item.boxed_clone();
292                self.activate_item(ix, cx);
293                return item;
294            }
295        }
296
297        let item = build_item(cx);
298        self.add_item(Some(project_entry_id), item.boxed_clone(), cx);
299        item
300    }
301
302    pub(crate) fn add_item(
303        &mut self,
304        project_entry_id: Option<ProjectEntryId>,
305        mut item: Box<dyn ItemHandle>,
306        cx: &mut ViewContext<Self>,
307    ) {
308        item.set_nav_history(self.nav_history.clone(), cx);
309        item.added_to_pane(cx);
310        let item_idx = cmp::min(self.active_item_index + 1, self.items.len());
311        self.items.insert(item_idx, (project_entry_id, item));
312        self.activate_item(item_idx, cx);
313        cx.notify();
314    }
315
316    pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
317        self.items.iter().map(|(_, view)| view)
318    }
319
320    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
321        self.items
322            .get(self.active_item_index)
323            .map(|(_, view)| view.clone())
324    }
325
326    pub fn project_entry_id_for_item(&self, item: &dyn ItemHandle) -> Option<ProjectEntryId> {
327        self.items.iter().find_map(|(entry_id, existing)| {
328            if existing.id() == item.id() {
329                *entry_id
330            } else {
331                None
332            }
333        })
334    }
335
336    pub fn item_for_entry(&self, entry_id: ProjectEntryId) -> Option<Box<dyn ItemHandle>> {
337        self.items.iter().find_map(|(id, view)| {
338            if *id == Some(entry_id) {
339                Some(view.boxed_clone())
340            } else {
341                None
342            }
343        })
344    }
345
346    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
347        self.items.iter().position(|(_, i)| i.id() == item.id())
348    }
349
350    pub fn activate_item(&mut self, index: usize, cx: &mut ViewContext<Self>) {
351        if index < self.items.len() {
352            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
353            if prev_active_item_ix != self.active_item_index
354                && prev_active_item_ix < self.items.len()
355            {
356                self.items[prev_active_item_ix].1.deactivated(cx);
357            }
358            self.update_active_toolbar(cx);
359            self.focus_active_item(cx);
360            self.activate(cx);
361            cx.notify();
362        }
363    }
364
365    pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
366        let mut index = self.active_item_index;
367        if index > 0 {
368            index -= 1;
369        } else if self.items.len() > 0 {
370            index = self.items.len() - 1;
371        }
372        self.activate_item(index, cx);
373    }
374
375    pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
376        let mut index = self.active_item_index;
377        if index + 1 < self.items.len() {
378            index += 1;
379        } else {
380            index = 0;
381        }
382        self.activate_item(index, cx);
383    }
384
385    pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) {
386        if !self.items.is_empty() {
387            self.close_item(self.items[self.active_item_index].1.id(), cx)
388        }
389    }
390
391    pub fn close_inactive_items(&mut self, cx: &mut ViewContext<Self>) {
392        if !self.items.is_empty() {
393            let active_item_id = self.items[self.active_item_index].1.id();
394            self.close_items(cx, |id| id != active_item_id);
395        }
396    }
397
398    pub fn close_item(&mut self, view_id_to_close: usize, cx: &mut ViewContext<Self>) {
399        self.close_items(cx, |view_id| view_id == view_id_to_close);
400    }
401
402    pub fn close_items(
403        &mut self,
404        cx: &mut ViewContext<Self>,
405        should_close: impl Fn(usize) -> bool,
406    ) {
407        let mut item_ix = 0;
408        let mut new_active_item_index = self.active_item_index;
409        self.items.retain(|(_, item)| {
410            if should_close(item.id()) {
411                if item_ix == self.active_item_index {
412                    item.deactivated(cx);
413                }
414
415                if item_ix < self.active_item_index {
416                    new_active_item_index -= 1;
417                }
418
419                let mut nav_history = self.nav_history.borrow_mut();
420                if let Some(path) = item.project_path(cx) {
421                    nav_history.paths_by_item.insert(item.id(), path);
422                } else {
423                    nav_history.paths_by_item.remove(&item.id());
424                }
425
426                item_ix += 1;
427                false
428            } else {
429                item_ix += 1;
430                true
431            }
432        });
433
434        if self.items.is_empty() {
435            cx.emit(Event::Remove);
436        } else {
437            self.active_item_index = cmp::min(new_active_item_index, self.items.len() - 1);
438            self.focus_active_item(cx);
439            self.activate(cx);
440        }
441        self.update_active_toolbar(cx);
442
443        cx.notify();
444    }
445
446    fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
447        if let Some(active_item) = self.active_item() {
448            cx.focus(active_item);
449        }
450    }
451
452    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
453        cx.emit(Event::Split(direction));
454    }
455
456    pub fn show_toolbar<F, V>(&mut self, cx: &mut ViewContext<Self>, build_toolbar: F)
457    where
458        F: FnOnce(&mut ViewContext<V>) -> V,
459        V: Toolbar,
460    {
461        let type_id = TypeId::of::<V>();
462        if self.active_toolbar_type != Some(type_id) {
463            self.dismiss_toolbar(cx);
464
465            let active_item = self.active_item();
466            self.toolbars
467                .entry(type_id)
468                .or_insert_with(|| Box::new(cx.add_view(build_toolbar)));
469
470            self.active_toolbar_type = Some(type_id);
471            self.active_toolbar_visible =
472                self.toolbars[&type_id].active_item_changed(active_item, cx);
473            cx.notify();
474        }
475    }
476
477    pub fn dismiss_toolbar(&mut self, cx: &mut ViewContext<Self>) {
478        if let Some(active_toolbar_type) = self.active_toolbar_type.take() {
479            self.toolbars
480                .get_mut(&active_toolbar_type)
481                .unwrap()
482                .on_dismiss(cx);
483            self.active_toolbar_visible = false;
484            self.focus_active_item(cx);
485            cx.notify();
486        }
487    }
488
489    pub fn toolbar<T: Toolbar>(&self) -> Option<ViewHandle<T>> {
490        self.toolbars
491            .get(&TypeId::of::<T>())
492            .and_then(|toolbar| toolbar.to_any().downcast())
493    }
494
495    pub fn active_toolbar(&self) -> Option<AnyViewHandle> {
496        let type_id = self.active_toolbar_type?;
497        let toolbar = self.toolbars.get(&type_id)?;
498        if self.active_toolbar_visible {
499            Some(toolbar.to_any())
500        } else {
501            None
502        }
503    }
504
505    fn update_active_toolbar(&mut self, cx: &mut ViewContext<Self>) {
506        let active_item = self.items.get(self.active_item_index);
507        for (toolbar_type_id, toolbar) in &self.toolbars {
508            let visible = toolbar.active_item_changed(active_item.map(|i| i.1.clone()), cx);
509            if Some(*toolbar_type_id) == self.active_toolbar_type {
510                self.active_toolbar_visible = visible;
511            }
512        }
513    }
514
515    fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
516        let theme = cx.global::<Settings>().theme.clone();
517
518        enum Tabs {}
519        let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
520            let mut row = Flex::row();
521            for (ix, (_, item)) in self.items.iter().enumerate() {
522                let is_active = ix == self.active_item_index;
523
524                row.add_child({
525                    let tab_style = if is_active {
526                        theme.workspace.active_tab.clone()
527                    } else {
528                        theme.workspace.tab.clone()
529                    };
530                    let title = item.tab_content(&tab_style, cx);
531
532                    let mut style = if is_active {
533                        theme.workspace.active_tab.clone()
534                    } else {
535                        theme.workspace.tab.clone()
536                    };
537                    if ix == 0 {
538                        style.container.border.left = false;
539                    }
540
541                    EventHandler::new(
542                        Container::new(
543                            Flex::row()
544                                .with_child(
545                                    Align::new({
546                                        let diameter = 7.0;
547                                        let icon_color = if item.has_conflict(cx) {
548                                            Some(style.icon_conflict)
549                                        } else if item.is_dirty(cx) {
550                                            Some(style.icon_dirty)
551                                        } else {
552                                            None
553                                        };
554
555                                        ConstrainedBox::new(
556                                            Canvas::new(move |bounds, _, cx| {
557                                                if let Some(color) = icon_color {
558                                                    let square = RectF::new(
559                                                        bounds.origin(),
560                                                        vec2f(diameter, diameter),
561                                                    );
562                                                    cx.scene.push_quad(Quad {
563                                                        bounds: square,
564                                                        background: Some(color),
565                                                        border: Default::default(),
566                                                        corner_radius: diameter / 2.,
567                                                    });
568                                                }
569                                            })
570                                            .boxed(),
571                                        )
572                                        .with_width(diameter)
573                                        .with_height(diameter)
574                                        .boxed()
575                                    })
576                                    .boxed(),
577                                )
578                                .with_child(
579                                    Container::new(Align::new(title).boxed())
580                                        .with_style(ContainerStyle {
581                                            margin: Margin {
582                                                left: style.spacing,
583                                                right: style.spacing,
584                                                ..Default::default()
585                                            },
586                                            ..Default::default()
587                                        })
588                                        .boxed(),
589                                )
590                                .with_child(
591                                    Align::new(
592                                        ConstrainedBox::new(if mouse_state.hovered {
593                                            let item_id = item.id();
594                                            enum TabCloseButton {}
595                                            let icon = Svg::new("icons/x.svg");
596                                            MouseEventHandler::new::<TabCloseButton, _, _>(
597                                                item_id,
598                                                cx,
599                                                |mouse_state, _| {
600                                                    if mouse_state.hovered {
601                                                        icon.with_color(style.icon_close_active)
602                                                            .boxed()
603                                                    } else {
604                                                        icon.with_color(style.icon_close).boxed()
605                                                    }
606                                                },
607                                            )
608                                            .with_padding(Padding::uniform(4.))
609                                            .with_cursor_style(CursorStyle::PointingHand)
610                                            .on_click(move |cx| {
611                                                cx.dispatch_action(CloseItem(item_id))
612                                            })
613                                            .named("close-tab-icon")
614                                        } else {
615                                            Empty::new().boxed()
616                                        })
617                                        .with_width(style.icon_width)
618                                        .boxed(),
619                                    )
620                                    .boxed(),
621                                )
622                                .boxed(),
623                        )
624                        .with_style(style.container)
625                        .boxed(),
626                    )
627                    .on_mouse_down(move |cx| {
628                        cx.dispatch_action(ActivateItem(ix));
629                        true
630                    })
631                    .boxed()
632                })
633            }
634
635            row.add_child(
636                Empty::new()
637                    .contained()
638                    .with_border(theme.workspace.tab.container.border)
639                    .flexible(0., true)
640                    .named("filler"),
641            );
642
643            row.boxed()
644        });
645
646        ConstrainedBox::new(tabs.boxed())
647            .with_height(theme.workspace.tab.height)
648            .named("tabs")
649    }
650}
651
652impl Entity for Pane {
653    type Event = Event;
654}
655
656impl View for Pane {
657    fn ui_name() -> &'static str {
658        "Pane"
659    }
660
661    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
662        let this = cx.handle();
663
664        EventHandler::new(if let Some(active_item) = self.active_item() {
665            Flex::column()
666                .with_child(self.render_tabs(cx))
667                .with_children(
668                    self.active_toolbar()
669                        .as_ref()
670                        .map(|view| ChildView::new(view).boxed()),
671                )
672                .with_child(ChildView::new(active_item).flexible(1., true).boxed())
673                .boxed()
674        } else {
675            Empty::new().boxed()
676        })
677        .on_navigate_mouse_down(move |direction, cx| {
678            let this = this.clone();
679            match direction {
680                NavigationDirection::Back => cx.dispatch_action(GoBack(Some(this))),
681                NavigationDirection::Forward => cx.dispatch_action(GoForward(Some(this))),
682            }
683
684            true
685        })
686        .named("pane")
687    }
688
689    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
690        self.focus_active_item(cx);
691    }
692}
693
694impl<T: Toolbar> ToolbarHandle for ViewHandle<T> {
695    fn active_item_changed(
696        &self,
697        item: Option<Box<dyn ItemHandle>>,
698        cx: &mut MutableAppContext,
699    ) -> bool {
700        self.update(cx, |this, cx| this.active_item_changed(item, cx))
701    }
702
703    fn on_dismiss(&self, cx: &mut MutableAppContext) {
704        self.update(cx, |this, cx| this.on_dismiss(cx));
705    }
706
707    fn to_any(&self) -> AnyViewHandle {
708        self.into()
709    }
710}
711
712impl ItemNavHistory {
713    pub fn new<T: Item>(history: Rc<RefCell<NavHistory>>, item: &ViewHandle<T>) -> Self {
714        Self {
715            history,
716            item: Rc::new(item.downgrade()),
717        }
718    }
719
720    pub fn history(&self) -> Rc<RefCell<NavHistory>> {
721        self.history.clone()
722    }
723
724    pub fn push<D: 'static + Any>(&self, data: Option<D>) {
725        self.history.borrow_mut().push(data, self.item.clone());
726    }
727}
728
729impl NavHistory {
730    pub fn disable(&mut self) {
731        self.mode = NavigationMode::Disabled;
732    }
733
734    pub fn enable(&mut self) {
735        self.mode = NavigationMode::Normal;
736    }
737
738    pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
739        self.backward_stack.pop_back()
740    }
741
742    pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
743        self.forward_stack.pop_back()
744    }
745
746    fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
747        match mode {
748            NavigationMode::Normal | NavigationMode::Disabled => None,
749            NavigationMode::GoingBack => self.pop_backward(),
750            NavigationMode::GoingForward => self.pop_forward(),
751        }
752    }
753
754    fn set_mode(&mut self, mode: NavigationMode) {
755        self.mode = mode;
756    }
757
758    pub fn push<D: 'static + Any>(&mut self, data: Option<D>, item: Rc<dyn WeakItemHandle>) {
759        match self.mode {
760            NavigationMode::Disabled => {}
761            NavigationMode::Normal => {
762                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
763                    self.backward_stack.pop_front();
764                }
765                self.backward_stack.push_back(NavigationEntry {
766                    item,
767                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
768                });
769                self.forward_stack.clear();
770            }
771            NavigationMode::GoingBack => {
772                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
773                    self.forward_stack.pop_front();
774                }
775                self.forward_stack.push_back(NavigationEntry {
776                    item,
777                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
778                });
779            }
780            NavigationMode::GoingForward => {
781                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
782                    self.backward_stack.pop_front();
783                }
784                self.backward_stack.push_back(NavigationEntry {
785                    item,
786                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
787                });
788            }
789        }
790    }
791}