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            cx.notify();
330        }
331    }
332
333    pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
334        let mut index = self.active_item_index;
335        if index > 0 {
336            index -= 1;
337        } else if self.item_views.len() > 0 {
338            index = self.item_views.len() - 1;
339        }
340        self.activate_item(index, cx);
341    }
342
343    pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
344        let mut index = self.active_item_index;
345        if index + 1 < self.item_views.len() {
346            index += 1;
347        } else {
348            index = 0;
349        }
350        self.activate_item(index, cx);
351    }
352
353    pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) {
354        if !self.item_views.is_empty() {
355            self.close_item(self.item_views[self.active_item_index].1.id(), cx)
356        }
357    }
358
359    pub fn close_item(&mut self, item_view_id: usize, cx: &mut ViewContext<Self>) {
360        let mut item_ix = 0;
361        self.item_views.retain(|(_, item_view)| {
362            if item_view.id() == item_view_id {
363                if item_ix == self.active_item_index {
364                    item_view.deactivated(cx);
365                }
366
367                let mut nav_history = self.nav_history.borrow_mut();
368                if let Some(path) = item_view.project_path(cx) {
369                    nav_history.paths_by_item.insert(item_view.id(), path);
370                } else {
371                    nav_history.paths_by_item.remove(&item_view.id());
372                }
373
374                item_ix += 1;
375                false
376            } else {
377                item_ix += 1;
378                true
379            }
380        });
381        self.activate_item(
382            cmp::min(
383                self.active_item_index,
384                self.item_views.len().saturating_sub(1),
385            ),
386            cx,
387        );
388
389        if self.item_views.is_empty() {
390            self.update_active_toolbar(cx);
391            cx.emit(Event::Remove);
392        }
393
394        cx.notify();
395    }
396
397    fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
398        if let Some(active_item) = self.active_item() {
399            cx.focus(active_item);
400        }
401    }
402
403    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
404        cx.emit(Event::Split(direction));
405    }
406
407    pub fn show_toolbar<F, V>(&mut self, cx: &mut ViewContext<Self>, build_toolbar: F)
408    where
409        F: FnOnce(&mut ViewContext<V>) -> V,
410        V: Toolbar,
411    {
412        let type_id = TypeId::of::<V>();
413        if self.active_toolbar_type != Some(type_id) {
414            self.dismiss_toolbar(cx);
415
416            let active_item = self.active_item();
417            self.toolbars
418                .entry(type_id)
419                .or_insert_with(|| Box::new(cx.add_view(build_toolbar)));
420
421            self.active_toolbar_type = Some(type_id);
422            self.active_toolbar_visible =
423                self.toolbars[&type_id].active_item_changed(active_item, cx);
424            cx.notify();
425        }
426    }
427
428    pub fn dismiss_toolbar(&mut self, cx: &mut ViewContext<Self>) {
429        if let Some(active_toolbar_type) = self.active_toolbar_type.take() {
430            self.toolbars
431                .get_mut(&active_toolbar_type)
432                .unwrap()
433                .on_dismiss(cx);
434            self.active_toolbar_visible = false;
435            self.focus_active_item(cx);
436            cx.notify();
437        }
438    }
439
440    pub fn toolbar<T: Toolbar>(&self) -> Option<ViewHandle<T>> {
441        self.toolbars
442            .get(&TypeId::of::<T>())
443            .and_then(|toolbar| toolbar.to_any().downcast())
444    }
445
446    pub fn active_toolbar(&self) -> Option<AnyViewHandle> {
447        let type_id = self.active_toolbar_type?;
448        let toolbar = self.toolbars.get(&type_id)?;
449        if self.active_toolbar_visible {
450            Some(toolbar.to_any())
451        } else {
452            None
453        }
454    }
455
456    fn update_active_toolbar(&mut self, cx: &mut ViewContext<Self>) {
457        let active_item = self.item_views.get(self.active_item_index);
458        for (toolbar_type_id, toolbar) in &self.toolbars {
459            let visible = toolbar.active_item_changed(active_item.map(|i| i.1.clone()), cx);
460            if Some(*toolbar_type_id) == self.active_toolbar_type {
461                self.active_toolbar_visible = visible;
462            }
463        }
464    }
465
466    fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
467        let settings = self.settings.borrow();
468        let theme = &settings.theme;
469
470        enum Tabs {}
471        let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
472            let mut row = Flex::row();
473            for (ix, (_, item_view)) in self.item_views.iter().enumerate() {
474                let is_active = ix == self.active_item_index;
475
476                row.add_child({
477                    let tab_style = if is_active {
478                        theme.workspace.active_tab.clone()
479                    } else {
480                        theme.workspace.tab.clone()
481                    };
482                    let title = item_view.tab_content(&tab_style, cx);
483
484                    let mut style = if is_active {
485                        theme.workspace.active_tab.clone()
486                    } else {
487                        theme.workspace.tab.clone()
488                    };
489                    if ix == 0 {
490                        style.container.border.left = false;
491                    }
492
493                    EventHandler::new(
494                        Container::new(
495                            Flex::row()
496                                .with_child(
497                                    Align::new({
498                                        let diameter = 7.0;
499                                        let icon_color = if item_view.has_conflict(cx) {
500                                            Some(style.icon_conflict)
501                                        } else if item_view.is_dirty(cx) {
502                                            Some(style.icon_dirty)
503                                        } else {
504                                            None
505                                        };
506
507                                        ConstrainedBox::new(
508                                            Canvas::new(move |bounds, _, cx| {
509                                                if let Some(color) = icon_color {
510                                                    let square = RectF::new(
511                                                        bounds.origin(),
512                                                        vec2f(diameter, diameter),
513                                                    );
514                                                    cx.scene.push_quad(Quad {
515                                                        bounds: square,
516                                                        background: Some(color),
517                                                        border: Default::default(),
518                                                        corner_radius: diameter / 2.,
519                                                    });
520                                                }
521                                            })
522                                            .boxed(),
523                                        )
524                                        .with_width(diameter)
525                                        .with_height(diameter)
526                                        .boxed()
527                                    })
528                                    .boxed(),
529                                )
530                                .with_child(
531                                    Container::new(Align::new(title).boxed())
532                                        .with_style(ContainerStyle {
533                                            margin: Margin {
534                                                left: style.spacing,
535                                                right: style.spacing,
536                                                ..Default::default()
537                                            },
538                                            ..Default::default()
539                                        })
540                                        .boxed(),
541                                )
542                                .with_child(
543                                    Align::new(
544                                        ConstrainedBox::new(if mouse_state.hovered {
545                                            let item_id = item_view.id();
546                                            enum TabCloseButton {}
547                                            let icon = Svg::new("icons/x.svg");
548                                            MouseEventHandler::new::<TabCloseButton, _, _>(
549                                                item_id,
550                                                cx,
551                                                |mouse_state, _| {
552                                                    if mouse_state.hovered {
553                                                        icon.with_color(style.icon_close_active)
554                                                            .boxed()
555                                                    } else {
556                                                        icon.with_color(style.icon_close).boxed()
557                                                    }
558                                                },
559                                            )
560                                            .with_padding(Padding::uniform(4.))
561                                            .with_cursor_style(CursorStyle::PointingHand)
562                                            .on_click(move |cx| {
563                                                cx.dispatch_action(CloseItem(item_id))
564                                            })
565                                            .named("close-tab-icon")
566                                        } else {
567                                            Empty::new().boxed()
568                                        })
569                                        .with_width(style.icon_width)
570                                        .boxed(),
571                                    )
572                                    .boxed(),
573                                )
574                                .boxed(),
575                        )
576                        .with_style(style.container)
577                        .boxed(),
578                    )
579                    .on_mouse_down(move |cx| {
580                        cx.dispatch_action(ActivateItem(ix));
581                        true
582                    })
583                    .boxed()
584                })
585            }
586
587            row.add_child(
588                Empty::new()
589                    .contained()
590                    .with_border(theme.workspace.tab.container.border)
591                    .flexible(0., true)
592                    .named("filler"),
593            );
594
595            row.boxed()
596        });
597
598        ConstrainedBox::new(tabs.boxed())
599            .with_height(theme.workspace.tab.height)
600            .named("tabs")
601    }
602}
603
604impl Entity for Pane {
605    type Event = Event;
606}
607
608impl View for Pane {
609    fn ui_name() -> &'static str {
610        "Pane"
611    }
612
613    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
614        if let Some(active_item) = self.active_item() {
615            Flex::column()
616                .with_child(self.render_tabs(cx))
617                .with_children(
618                    self.active_toolbar()
619                        .as_ref()
620                        .map(|view| ChildView::new(view).boxed()),
621                )
622                .with_child(ChildView::new(active_item).flexible(1., true).boxed())
623                .named("pane")
624        } else {
625            Empty::new().named("pane")
626        }
627    }
628
629    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
630        self.focus_active_item(cx);
631    }
632}
633
634impl<T: Toolbar> ToolbarHandle for ViewHandle<T> {
635    fn active_item_changed(
636        &self,
637        item: Option<Box<dyn ItemViewHandle>>,
638        cx: &mut MutableAppContext,
639    ) -> bool {
640        self.update(cx, |this, cx| this.active_item_changed(item, cx))
641    }
642
643    fn on_dismiss(&self, cx: &mut MutableAppContext) {
644        self.update(cx, |this, cx| this.on_dismiss(cx));
645    }
646
647    fn to_any(&self) -> AnyViewHandle {
648        self.into()
649    }
650}
651
652impl ItemNavHistory {
653    pub fn new<T: ItemView>(history: Rc<RefCell<NavHistory>>, item_view: &ViewHandle<T>) -> Self {
654        Self {
655            history,
656            item_view: Rc::new(item_view.downgrade()),
657        }
658    }
659
660    pub fn history(&self) -> Rc<RefCell<NavHistory>> {
661        self.history.clone()
662    }
663
664    pub fn push<D: 'static + Any>(&self, data: Option<D>) {
665        self.history.borrow_mut().push(data, self.item_view.clone());
666    }
667}
668
669impl NavHistory {
670    pub fn disable(&mut self) {
671        self.mode = NavigationMode::Disabled;
672    }
673
674    pub fn enable(&mut self) {
675        self.mode = NavigationMode::Normal;
676    }
677
678    pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
679        self.backward_stack.pop_back()
680    }
681
682    pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
683        self.forward_stack.pop_back()
684    }
685
686    fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
687        match mode {
688            NavigationMode::Normal | NavigationMode::Disabled => None,
689            NavigationMode::GoingBack => self.pop_backward(),
690            NavigationMode::GoingForward => self.pop_forward(),
691        }
692    }
693
694    fn set_mode(&mut self, mode: NavigationMode) {
695        self.mode = mode;
696    }
697
698    pub fn push<D: 'static + Any>(
699        &mut self,
700        data: Option<D>,
701        item_view: Rc<dyn WeakItemViewHandle>,
702    ) {
703        match self.mode {
704            NavigationMode::Disabled => {}
705            NavigationMode::Normal => {
706                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
707                    self.backward_stack.pop_front();
708                }
709                self.backward_stack.push_back(NavigationEntry {
710                    item_view,
711                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
712                });
713                self.forward_stack.clear();
714            }
715            NavigationMode::GoingBack => {
716                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
717                    self.forward_stack.pop_front();
718                }
719                self.forward_stack.push_back(NavigationEntry {
720                    item_view,
721                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
722                });
723            }
724            NavigationMode::GoingForward => {
725                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
726                    self.backward_stack.pop_front();
727                }
728                self.backward_stack.push_back(NavigationEntry {
729                    item_view,
730                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
731                });
732            }
733        }
734    }
735}