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