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