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