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