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