pane.rs

  1use super::{ItemHandle, SplitDirection};
  2use crate::{toolbar::Toolbar, Item, WeakItemHandle, Workspace};
  3use anyhow::Result;
  4use collections::{HashMap, HashSet, VecDeque};
  5use futures::StreamExt;
  6use gpui::{
  7    actions,
  8    elements::*,
  9    geometry::{rect::RectF, vector::vec2f},
 10    impl_actions, impl_internal_actions,
 11    platform::{CursorStyle, NavigationDirection},
 12    AppContext, AsyncAppContext, Entity, ModelHandle, MutableAppContext, PromptLevel, Quad,
 13    RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
 14};
 15use project::{Project, ProjectEntryId, ProjectPath};
 16use serde::Deserialize;
 17use settings::Settings;
 18use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};
 19use util::ResultExt;
 20
 21actions!(
 22    pane,
 23    [
 24        ActivatePrevItem,
 25        ActivateNextItem,
 26        CloseActiveItem,
 27        CloseInactiveItems,
 28    ]
 29);
 30
 31#[derive(Clone, Deserialize)]
 32pub struct Split(pub SplitDirection);
 33
 34#[derive(Clone)]
 35pub struct CloseItem {
 36    pub item_id: usize,
 37    pub pane: WeakViewHandle<Pane>,
 38}
 39
 40#[derive(Clone, Deserialize)]
 41pub struct ActivateItem(pub usize);
 42
 43#[derive(Clone, Deserialize)]
 44pub struct GoBack {
 45    #[serde(skip_deserializing)]
 46    pub pane: Option<WeakViewHandle<Pane>>,
 47}
 48
 49#[derive(Clone, Deserialize)]
 50pub struct GoForward {
 51    #[serde(skip_deserializing)]
 52    pub pane: Option<WeakViewHandle<Pane>>,
 53}
 54
 55impl_actions!(pane, [Split, GoBack, GoForward]);
 56impl_internal_actions!(pane, [CloseItem, ActivateItem]);
 57
 58const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
 59
 60pub fn init(cx: &mut MutableAppContext) {
 61    cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
 62        pane.activate_item(action.0, true, true, cx);
 63    });
 64    cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
 65        pane.activate_prev_item(cx);
 66    });
 67    cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
 68        pane.activate_next_item(cx);
 69    });
 70    cx.add_async_action(Pane::close_active_item);
 71    cx.add_async_action(Pane::close_inactive_items);
 72    cx.add_async_action(|workspace: &mut Workspace, action: &CloseItem, cx| {
 73        let pane = action.pane.upgrade(cx)?;
 74        let task = Pane::close_item(workspace, pane, action.item_id, cx);
 75        Some(cx.foreground().spawn(async move {
 76            task.await?;
 77            Ok(())
 78        }))
 79    });
 80    cx.add_action(|pane: &mut Pane, action: &Split, cx| {
 81        pane.split(action.0, cx);
 82    });
 83    cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
 84        Pane::go_back(
 85            workspace,
 86            action
 87                .pane
 88                .as_ref()
 89                .and_then(|weak_handle| weak_handle.upgrade(cx)),
 90            cx,
 91        )
 92        .detach();
 93    });
 94    cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
 95        Pane::go_forward(
 96            workspace,
 97            action
 98                .pane
 99                .as_ref()
100                .and_then(|weak_handle| weak_handle.upgrade(cx)),
101            cx,
102        )
103        .detach();
104    });
105}
106
107pub enum Event {
108    Activate,
109    ActivateItem { local: bool },
110    Remove,
111    Split(SplitDirection),
112}
113
114pub struct Pane {
115    items: Vec<Box<dyn ItemHandle>>,
116    active_item_index: usize,
117    autoscroll: bool,
118    nav_history: Rc<RefCell<NavHistory>>,
119    toolbar: ViewHandle<Toolbar>,
120}
121
122pub struct ItemNavHistory {
123    history: Rc<RefCell<NavHistory>>,
124    item: Rc<dyn WeakItemHandle>,
125}
126
127#[derive(Default)]
128pub struct NavHistory {
129    mode: NavigationMode,
130    backward_stack: VecDeque<NavigationEntry>,
131    forward_stack: VecDeque<NavigationEntry>,
132    paths_by_item: HashMap<usize, ProjectPath>,
133}
134
135#[derive(Copy, Clone)]
136enum NavigationMode {
137    Normal,
138    GoingBack,
139    GoingForward,
140    Disabled,
141}
142
143impl Default for NavigationMode {
144    fn default() -> Self {
145        Self::Normal
146    }
147}
148
149pub struct NavigationEntry {
150    pub item: Rc<dyn WeakItemHandle>,
151    pub data: Option<Box<dyn Any>>,
152}
153
154impl Pane {
155    pub fn new(cx: &mut ViewContext<Self>) -> Self {
156        Self {
157            items: Vec::new(),
158            active_item_index: 0,
159            autoscroll: false,
160            nav_history: Default::default(),
161            toolbar: cx.add_view(|_| Toolbar::new()),
162        }
163    }
164
165    pub fn nav_history(&self) -> &Rc<RefCell<NavHistory>> {
166        &self.nav_history
167    }
168
169    pub fn activate(&self, cx: &mut ViewContext<Self>) {
170        cx.emit(Event::Activate);
171    }
172
173    pub fn go_back(
174        workspace: &mut Workspace,
175        pane: Option<ViewHandle<Pane>>,
176        cx: &mut ViewContext<Workspace>,
177    ) -> Task<()> {
178        Self::navigate_history(
179            workspace,
180            pane.unwrap_or_else(|| workspace.active_pane().clone()),
181            NavigationMode::GoingBack,
182            cx,
183        )
184    }
185
186    pub fn go_forward(
187        workspace: &mut Workspace,
188        pane: Option<ViewHandle<Pane>>,
189        cx: &mut ViewContext<Workspace>,
190    ) -> Task<()> {
191        Self::navigate_history(
192            workspace,
193            pane.unwrap_or_else(|| workspace.active_pane().clone()),
194            NavigationMode::GoingForward,
195            cx,
196        )
197    }
198
199    fn navigate_history(
200        workspace: &mut Workspace,
201        pane: ViewHandle<Pane>,
202        mode: NavigationMode,
203        cx: &mut ViewContext<Workspace>,
204    ) -> Task<()> {
205        workspace.activate_pane(pane.clone(), cx);
206
207        let to_load = pane.update(cx, |pane, cx| {
208            loop {
209                // Retrieve the weak item handle from the history.
210                let entry = pane.nav_history.borrow_mut().pop(mode)?;
211
212                // If the item is still present in this pane, then activate it.
213                if let Some(index) = entry
214                    .item
215                    .upgrade(cx)
216                    .and_then(|v| pane.index_for_item(v.as_ref()))
217                {
218                    let prev_active_item_index = pane.active_item_index;
219                    pane.nav_history.borrow_mut().set_mode(mode);
220                    pane.activate_item(index, true, true, cx);
221                    pane.nav_history
222                        .borrow_mut()
223                        .set_mode(NavigationMode::Normal);
224
225                    let mut navigated = prev_active_item_index != pane.active_item_index;
226                    if let Some(data) = entry.data {
227                        navigated |= pane.active_item()?.navigate(data, cx);
228                    }
229
230                    if navigated {
231                        break None;
232                    }
233                }
234                // If the item is no longer present in this pane, then retrieve its
235                // project path in order to reopen it.
236                else {
237                    break pane
238                        .nav_history
239                        .borrow_mut()
240                        .paths_by_item
241                        .get(&entry.item.id())
242                        .cloned()
243                        .map(|project_path| (project_path, entry));
244                }
245            }
246        });
247
248        if let Some((project_path, entry)) = to_load {
249            // If the item was no longer present, then load it again from its previous path.
250            let pane = pane.downgrade();
251            let task = workspace.load_path(project_path, cx);
252            cx.spawn(|workspace, mut cx| async move {
253                let task = task.await;
254                if let Some(pane) = pane.upgrade(&cx) {
255                    if let Some((project_entry_id, build_item)) = task.log_err() {
256                        pane.update(&mut cx, |pane, _| {
257                            pane.nav_history.borrow_mut().set_mode(mode);
258                        });
259                        let item = workspace.update(&mut cx, |workspace, cx| {
260                            Self::open_item(
261                                workspace,
262                                pane.clone(),
263                                project_entry_id,
264                                true,
265                                cx,
266                                build_item,
267                            )
268                        });
269                        pane.update(&mut cx, |pane, cx| {
270                            pane.nav_history
271                                .borrow_mut()
272                                .set_mode(NavigationMode::Normal);
273                            if let Some(data) = entry.data {
274                                item.navigate(data, cx);
275                            }
276                        });
277                    } else {
278                        workspace
279                            .update(&mut cx, |workspace, cx| {
280                                Self::navigate_history(workspace, pane, mode, cx)
281                            })
282                            .await;
283                    }
284                }
285            })
286        } else {
287            Task::ready(())
288        }
289    }
290
291    pub(crate) fn open_item(
292        workspace: &mut Workspace,
293        pane: ViewHandle<Pane>,
294        project_entry_id: ProjectEntryId,
295        focus_item: bool,
296        cx: &mut ViewContext<Workspace>,
297        build_item: impl FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
298    ) -> Box<dyn ItemHandle> {
299        let existing_item = pane.update(cx, |pane, cx| {
300            for (ix, item) in pane.items.iter().enumerate() {
301                if item.project_entry_ids(cx).as_slice() == &[project_entry_id] {
302                    let item = item.boxed_clone();
303                    pane.activate_item(ix, true, focus_item, cx);
304                    return Some(item);
305                }
306            }
307            None
308        });
309        if let Some(existing_item) = existing_item {
310            existing_item
311        } else {
312            let item = build_item(cx);
313            Self::add_item(workspace, pane, item.boxed_clone(), true, focus_item, cx);
314            item
315        }
316    }
317
318    pub(crate) fn add_item(
319        workspace: &mut Workspace,
320        pane: ViewHandle<Pane>,
321        item: Box<dyn ItemHandle>,
322        activate_pane: bool,
323        focus_item: bool,
324        cx: &mut ViewContext<Workspace>,
325    ) {
326        // Prevent adding the same item to the pane more than once.
327        if let Some(item_ix) = pane.read(cx).items.iter().position(|i| i.id() == item.id()) {
328            pane.update(cx, |pane, cx| {
329                pane.activate_item(item_ix, activate_pane, focus_item, cx)
330            });
331            return;
332        }
333
334        item.set_nav_history(pane.read(cx).nav_history.clone(), cx);
335        item.added_to_pane(workspace, pane.clone(), cx);
336        pane.update(cx, |pane, cx| {
337            let item_idx = cmp::min(pane.active_item_index + 1, pane.items.len());
338            pane.items.insert(item_idx, item);
339            pane.activate_item(item_idx, activate_pane, focus_item, cx);
340            cx.notify();
341        });
342    }
343
344    pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
345        self.items.iter()
346    }
347
348    pub fn items_of_type<'a, T: View>(&'a self) -> impl 'a + Iterator<Item = ViewHandle<T>> {
349        self.items
350            .iter()
351            .filter_map(|item| item.to_any().downcast())
352    }
353
354    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
355        self.items.get(self.active_item_index).cloned()
356    }
357
358    pub fn item_for_entry(
359        &self,
360        entry_id: ProjectEntryId,
361        cx: &AppContext,
362    ) -> Option<Box<dyn ItemHandle>> {
363        self.items.iter().find_map(|item| {
364            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == &[entry_id] {
365                Some(item.boxed_clone())
366            } else {
367                None
368            }
369        })
370    }
371
372    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
373        self.items.iter().position(|i| i.id() == item.id())
374    }
375
376    pub fn activate_item(
377        &mut self,
378        index: usize,
379        activate_pane: bool,
380        focus_item: bool,
381        cx: &mut ViewContext<Self>,
382    ) {
383        use NavigationMode::{GoingBack, GoingForward};
384        if index < self.items.len() {
385            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
386            if matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
387                || (prev_active_item_ix != self.active_item_index
388                    && prev_active_item_ix < self.items.len())
389            {
390                self.items[prev_active_item_ix].deactivated(cx);
391                cx.emit(Event::ActivateItem {
392                    local: activate_pane,
393                });
394            }
395            self.update_toolbar(cx);
396            if focus_item {
397                self.focus_active_item(cx);
398            }
399            if activate_pane {
400                self.activate(cx);
401            }
402            self.autoscroll = true;
403            cx.notify();
404        }
405    }
406
407    pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
408        let mut index = self.active_item_index;
409        if index > 0 {
410            index -= 1;
411        } else if self.items.len() > 0 {
412            index = self.items.len() - 1;
413        }
414        self.activate_item(index, true, true, cx);
415    }
416
417    pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
418        let mut index = self.active_item_index;
419        if index + 1 < self.items.len() {
420            index += 1;
421        } else {
422            index = 0;
423        }
424        self.activate_item(index, true, true, cx);
425    }
426
427    fn close_active_item(
428        workspace: &mut Workspace,
429        _: &CloseActiveItem,
430        cx: &mut ViewContext<Workspace>,
431    ) -> Option<Task<Result<()>>> {
432        let pane_handle = workspace.active_pane().clone();
433        let pane = pane_handle.read(cx);
434        if pane.items.is_empty() {
435            None
436        } else {
437            let item_id_to_close = pane.items[pane.active_item_index].id();
438            let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
439                item_id == item_id_to_close
440            });
441            Some(cx.foreground().spawn(async move {
442                task.await?;
443                Ok(())
444            }))
445        }
446    }
447
448    pub fn close_inactive_items(
449        workspace: &mut Workspace,
450        _: &CloseInactiveItems,
451        cx: &mut ViewContext<Workspace>,
452    ) -> Option<Task<Result<()>>> {
453        let pane_handle = workspace.active_pane().clone();
454        let pane = pane_handle.read(cx);
455        if pane.items.is_empty() {
456            None
457        } else {
458            let active_item_id = pane.items[pane.active_item_index].id();
459            let task =
460                Self::close_items(workspace, pane_handle, cx, move |id| id != active_item_id);
461            Some(cx.foreground().spawn(async move {
462                task.await?;
463                Ok(())
464            }))
465        }
466    }
467
468    pub fn close_item(
469        workspace: &mut Workspace,
470        pane: ViewHandle<Pane>,
471        item_id_to_close: usize,
472        cx: &mut ViewContext<Workspace>,
473    ) -> Task<Result<bool>> {
474        Self::close_items(workspace, pane, cx, move |view_id| {
475            view_id == item_id_to_close
476        })
477    }
478
479    pub fn close_items(
480        workspace: &mut Workspace,
481        pane: ViewHandle<Pane>,
482        cx: &mut ViewContext<Workspace>,
483        should_close: impl 'static + Fn(usize) -> bool,
484    ) -> Task<Result<bool>> {
485        let project = workspace.project().clone();
486
487        // Find the items to close.
488        let mut items_to_close = Vec::new();
489        for item in &pane.read(cx).items {
490            if should_close(item.id()) {
491                items_to_close.push(item.boxed_clone());
492            }
493        }
494        items_to_close.sort_by_key(|item| !item.is_singleton(cx));
495
496        cx.spawn(|workspace, mut cx| async move {
497            let mut saved_project_entry_ids = HashSet::default();
498            for item in items_to_close.clone() {
499                // Find the item's current index and its set of project entries. Avoid
500                // storing these in advance, in case they have changed since this task
501                // was started.
502                let (item_ix, mut project_entry_ids) = pane.read_with(&cx, |pane, cx| {
503                    (pane.index_for_item(&*item), item.project_entry_ids(cx))
504                });
505                let item_ix = if let Some(ix) = item_ix {
506                    ix
507                } else {
508                    continue;
509                };
510
511                let should_save = if project_entry_ids.is_empty() {
512                    true
513                } else {
514                    // Find the project entries that aren't open anywhere else in the workspace.
515                    workspace.read_with(&cx, |workspace, cx| {
516                        for item in workspace.items(cx) {
517                            if !items_to_close
518                                .iter()
519                                .any(|item_to_close| item_to_close.id() == item.id())
520                            {
521                                let other_project_entry_ids = item.project_entry_ids(cx);
522                                project_entry_ids
523                                    .retain(|id| !other_project_entry_ids.contains(&id));
524                            }
525                        }
526                    });
527                    project_entry_ids
528                        .iter()
529                        .any(|id| saved_project_entry_ids.insert(*id))
530                };
531
532                // If any of these project entries have not already been saved by an earlier item,
533                // then this item must be saved.
534                if should_save {
535                    if !Self::save_item(project.clone(), &pane, item_ix, &item, true, &mut cx)
536                        .await?
537                    {
538                        break;
539                    }
540                }
541
542                // Remove the item from the pane.
543                pane.update(&mut cx, |pane, cx| {
544                    if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
545                        if item_ix == pane.active_item_index {
546                            if item_ix + 1 < pane.items.len() {
547                                pane.activate_next_item(cx);
548                            } else if item_ix > 0 {
549                                pane.activate_prev_item(cx);
550                            }
551                        }
552
553                        let item = pane.items.remove(item_ix);
554                        if pane.items.is_empty() {
555                            item.deactivated(cx);
556                            pane.update_toolbar(cx);
557                            cx.emit(Event::Remove);
558                        }
559
560                        if item_ix < pane.active_item_index {
561                            pane.active_item_index -= 1;
562                        }
563
564                        let mut nav_history = pane.nav_history.borrow_mut();
565                        if let Some(path) = item.project_path(cx) {
566                            nav_history.paths_by_item.insert(item.id(), path);
567                        } else {
568                            nav_history.paths_by_item.remove(&item.id());
569                        }
570                    }
571                });
572            }
573
574            pane.update(&mut cx, |_, cx| cx.notify());
575            Ok(true)
576        })
577    }
578
579    pub async fn save_item(
580        project: ModelHandle<Project>,
581        pane: &ViewHandle<Pane>,
582        item_ix: usize,
583        item: &Box<dyn ItemHandle>,
584        should_prompt_for_save: bool,
585        cx: &mut AsyncAppContext,
586    ) -> Result<bool> {
587        const CONFLICT_MESSAGE: &'static str =
588            "This file has changed on disk since you started editing it. Do you want to overwrite it?";
589        const DIRTY_MESSAGE: &'static str =
590            "This file contains unsaved edits. Do you want to save it?";
591
592        let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
593            (
594                item.has_conflict(cx),
595                item.is_dirty(cx),
596                item.can_save(cx),
597                item.is_singleton(cx),
598            )
599        });
600
601        if has_conflict && can_save {
602            let mut answer = pane.update(cx, |pane, cx| {
603                pane.activate_item(item_ix, true, true, cx);
604                cx.prompt(
605                    PromptLevel::Warning,
606                    CONFLICT_MESSAGE,
607                    &["Overwrite", "Discard", "Cancel"],
608                )
609            });
610            match answer.next().await {
611                Some(0) => cx.update(|cx| item.save(project, cx)).await?,
612                Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
613                _ => return Ok(false),
614            }
615        } else if is_dirty && (can_save || is_singleton) {
616            let should_save = if should_prompt_for_save {
617                let mut answer = pane.update(cx, |pane, cx| {
618                    pane.activate_item(item_ix, true, true, cx);
619                    cx.prompt(
620                        PromptLevel::Warning,
621                        DIRTY_MESSAGE,
622                        &["Save", "Don't Save", "Cancel"],
623                    )
624                });
625                match answer.next().await {
626                    Some(0) => true,
627                    Some(1) => false,
628                    _ => return Ok(false),
629                }
630            } else {
631                true
632            };
633
634            if should_save {
635                if can_save {
636                    cx.update(|cx| item.save(project, cx)).await?;
637                } else if is_singleton {
638                    let start_abs_path = project
639                        .read_with(cx, |project, cx| {
640                            let worktree = project.visible_worktrees(cx).next()?;
641                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
642                        })
643                        .unwrap_or(Path::new("").into());
644
645                    let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
646                    if let Some(abs_path) = abs_path.next().await.flatten() {
647                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
648                    } else {
649                        return Ok(false);
650                    }
651                }
652            }
653        }
654        Ok(true)
655    }
656
657    pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
658        if let Some(active_item) = self.active_item() {
659            cx.focus(active_item);
660        }
661    }
662
663    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
664        cx.emit(Event::Split(direction));
665    }
666
667    pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
668        &self.toolbar
669    }
670
671    fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
672        let active_item = self
673            .items
674            .get(self.active_item_index)
675            .map(|item| item.as_ref());
676        self.toolbar.update(cx, |toolbar, cx| {
677            toolbar.set_active_pane_item(active_item, cx);
678        });
679    }
680
681    fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
682        let theme = cx.global::<Settings>().theme.clone();
683
684        enum Tabs {}
685        let pane = cx.handle();
686        let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
687            let autoscroll = if mem::take(&mut self.autoscroll) {
688                Some(self.active_item_index)
689            } else {
690                None
691            };
692            let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
693            for (ix, item) in self.items.iter().enumerate() {
694                let is_active = ix == self.active_item_index;
695
696                row.add_child({
697                    let tab_style = if is_active {
698                        theme.workspace.active_tab.clone()
699                    } else {
700                        theme.workspace.tab.clone()
701                    };
702                    let title = item.tab_content(&tab_style, cx);
703
704                    let mut style = if is_active {
705                        theme.workspace.active_tab.clone()
706                    } else {
707                        theme.workspace.tab.clone()
708                    };
709                    if ix == 0 {
710                        style.container.border.left = false;
711                    }
712
713                    EventHandler::new(
714                        Container::new(
715                            Flex::row()
716                                .with_child(
717                                    Align::new({
718                                        let diameter = 7.0;
719                                        let icon_color = if item.has_conflict(cx) {
720                                            Some(style.icon_conflict)
721                                        } else if item.is_dirty(cx) {
722                                            Some(style.icon_dirty)
723                                        } else {
724                                            None
725                                        };
726
727                                        ConstrainedBox::new(
728                                            Canvas::new(move |bounds, _, cx| {
729                                                if let Some(color) = icon_color {
730                                                    let square = RectF::new(
731                                                        bounds.origin(),
732                                                        vec2f(diameter, diameter),
733                                                    );
734                                                    cx.scene.push_quad(Quad {
735                                                        bounds: square,
736                                                        background: Some(color),
737                                                        border: Default::default(),
738                                                        corner_radius: diameter / 2.,
739                                                    });
740                                                }
741                                            })
742                                            .boxed(),
743                                        )
744                                        .with_width(diameter)
745                                        .with_height(diameter)
746                                        .boxed()
747                                    })
748                                    .boxed(),
749                                )
750                                .with_child(
751                                    Container::new(Align::new(title).boxed())
752                                        .with_style(ContainerStyle {
753                                            margin: Margin {
754                                                left: style.spacing,
755                                                right: style.spacing,
756                                                ..Default::default()
757                                            },
758                                            ..Default::default()
759                                        })
760                                        .boxed(),
761                                )
762                                .with_child(
763                                    Align::new(
764                                        ConstrainedBox::new(if mouse_state.hovered {
765                                            let item_id = item.id();
766                                            enum TabCloseButton {}
767                                            let icon = Svg::new("icons/x.svg");
768                                            MouseEventHandler::new::<TabCloseButton, _, _>(
769                                                item_id,
770                                                cx,
771                                                |mouse_state, _| {
772                                                    if mouse_state.hovered {
773                                                        icon.with_color(style.icon_close_active)
774                                                            .boxed()
775                                                    } else {
776                                                        icon.with_color(style.icon_close).boxed()
777                                                    }
778                                                },
779                                            )
780                                            .with_padding(Padding::uniform(4.))
781                                            .with_cursor_style(CursorStyle::PointingHand)
782                                            .on_click({
783                                                let pane = pane.clone();
784                                                move |_, cx| {
785                                                    cx.dispatch_action(CloseItem {
786                                                        item_id,
787                                                        pane: pane.clone(),
788                                                    })
789                                                }
790                                            })
791                                            .named("close-tab-icon")
792                                        } else {
793                                            Empty::new().boxed()
794                                        })
795                                        .with_width(style.icon_width)
796                                        .boxed(),
797                                    )
798                                    .boxed(),
799                                )
800                                .boxed(),
801                        )
802                        .with_style(style.container)
803                        .boxed(),
804                    )
805                    .on_mouse_down(move |cx| {
806                        cx.dispatch_action(ActivateItem(ix));
807                        true
808                    })
809                    .boxed()
810                })
811            }
812
813            row.add_child(
814                Empty::new()
815                    .contained()
816                    .with_border(theme.workspace.tab.container.border)
817                    .flex(0., true)
818                    .named("filler"),
819            );
820
821            row.boxed()
822        });
823
824        ConstrainedBox::new(tabs.boxed())
825            .with_height(theme.workspace.tab.height)
826            .named("tabs")
827    }
828}
829
830impl Entity for Pane {
831    type Event = Event;
832}
833
834impl View for Pane {
835    fn ui_name() -> &'static str {
836        "Pane"
837    }
838
839    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
840        let this = cx.handle();
841
842        EventHandler::new(if let Some(active_item) = self.active_item() {
843            Flex::column()
844                .with_child(self.render_tabs(cx))
845                .with_child(ChildView::new(&self.toolbar).boxed())
846                .with_child(ChildView::new(active_item).flex(1., true).boxed())
847                .boxed()
848        } else {
849            Empty::new().boxed()
850        })
851        .on_navigate_mouse_down(move |direction, cx| {
852            let this = this.clone();
853            match direction {
854                NavigationDirection::Back => cx.dispatch_action(GoBack { pane: Some(this) }),
855                NavigationDirection::Forward => cx.dispatch_action(GoForward { pane: Some(this) }),
856            }
857
858            true
859        })
860        .named("pane")
861    }
862
863    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
864        self.focus_active_item(cx);
865    }
866}
867
868impl ItemNavHistory {
869    pub fn new<T: Item>(history: Rc<RefCell<NavHistory>>, item: &ViewHandle<T>) -> Self {
870        Self {
871            history,
872            item: Rc::new(item.downgrade()),
873        }
874    }
875
876    pub fn history(&self) -> Rc<RefCell<NavHistory>> {
877        self.history.clone()
878    }
879
880    pub fn push<D: 'static + Any>(&self, data: Option<D>) {
881        self.history.borrow_mut().push(data, self.item.clone());
882    }
883}
884
885impl NavHistory {
886    pub fn disable(&mut self) {
887        self.mode = NavigationMode::Disabled;
888    }
889
890    pub fn enable(&mut self) {
891        self.mode = NavigationMode::Normal;
892    }
893
894    pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
895        self.backward_stack.pop_back()
896    }
897
898    pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
899        self.forward_stack.pop_back()
900    }
901
902    fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
903        match mode {
904            NavigationMode::Normal | NavigationMode::Disabled => None,
905            NavigationMode::GoingBack => self.pop_backward(),
906            NavigationMode::GoingForward => self.pop_forward(),
907        }
908    }
909
910    fn set_mode(&mut self, mode: NavigationMode) {
911        self.mode = mode;
912    }
913
914    pub fn push<D: 'static + Any>(&mut self, data: Option<D>, item: Rc<dyn WeakItemHandle>) {
915        match self.mode {
916            NavigationMode::Disabled => {}
917            NavigationMode::Normal => {
918                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
919                    self.backward_stack.pop_front();
920                }
921                self.backward_stack.push_back(NavigationEntry {
922                    item,
923                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
924                });
925                self.forward_stack.clear();
926            }
927            NavigationMode::GoingBack => {
928                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
929                    self.forward_stack.pop_front();
930                }
931                self.forward_stack.push_back(NavigationEntry {
932                    item,
933                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
934                });
935            }
936            NavigationMode::GoingForward => {
937                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
938                    self.backward_stack.pop_front();
939                }
940                self.backward_stack.push_back(NavigationEntry {
941                    item,
942                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
943                });
944            }
945        }
946    }
947}