pane.rs

  1use super::{ItemViewHandle, SplitDirection};
  2use crate::Settings;
  3use gpui::{
  4    action,
  5    elements::*,
  6    geometry::{rect::RectF, vector::vec2f},
  7    keymap::Binding,
  8    platform::CursorStyle,
  9    Entity, MutableAppContext, Quad, RenderContext, View, ViewContext, ViewHandle,
 10};
 11use postage::watch;
 12use project::ProjectPath;
 13use std::cmp;
 14
 15action!(Split, SplitDirection);
 16action!(ActivateItem, usize);
 17action!(ActivatePrevItem);
 18action!(ActivateNextItem);
 19action!(CloseActiveItem);
 20action!(CloseItem, usize);
 21
 22pub fn init(cx: &mut MutableAppContext) {
 23    cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
 24        pane.activate_item(action.0, cx);
 25    });
 26    cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
 27        pane.activate_prev_item(cx);
 28    });
 29    cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
 30        pane.activate_next_item(cx);
 31    });
 32    cx.add_action(|pane: &mut Pane, _: &CloseActiveItem, cx| {
 33        pane.close_active_item(cx);
 34    });
 35    cx.add_action(|pane: &mut Pane, action: &CloseItem, cx| {
 36        pane.close_item(action.0, cx);
 37    });
 38    cx.add_action(|pane: &mut Pane, action: &Split, cx| {
 39        pane.split(action.0, cx);
 40    });
 41
 42    cx.add_bindings(vec![
 43        Binding::new("shift-cmd-{", ActivatePrevItem, Some("Pane")),
 44        Binding::new("shift-cmd-}", ActivateNextItem, Some("Pane")),
 45        Binding::new("cmd-w", CloseActiveItem, Some("Pane")),
 46        Binding::new("cmd-k up", Split(SplitDirection::Up), Some("Pane")),
 47        Binding::new("cmd-k down", Split(SplitDirection::Down), Some("Pane")),
 48        Binding::new("cmd-k left", Split(SplitDirection::Left), Some("Pane")),
 49        Binding::new("cmd-k right", Split(SplitDirection::Right), Some("Pane")),
 50    ]);
 51}
 52
 53pub enum Event {
 54    Activate,
 55    Remove,
 56    Split(SplitDirection),
 57}
 58
 59const MAX_TAB_TITLE_LEN: usize = 24;
 60
 61#[derive(Debug, Eq, PartialEq)]
 62pub struct State {
 63    pub tabs: Vec<TabState>,
 64}
 65
 66#[derive(Debug, Eq, PartialEq)]
 67pub struct TabState {
 68    pub title: String,
 69    pub active: bool,
 70}
 71
 72pub struct Pane {
 73    items: Vec<Box<dyn ItemViewHandle>>,
 74    active_item: usize,
 75    settings: watch::Receiver<Settings>,
 76}
 77
 78impl Pane {
 79    pub fn new(settings: watch::Receiver<Settings>) -> Self {
 80        Self {
 81            items: Vec::new(),
 82            active_item: 0,
 83            settings,
 84        }
 85    }
 86
 87    pub fn activate(&self, cx: &mut ViewContext<Self>) {
 88        cx.emit(Event::Activate);
 89    }
 90
 91    pub fn add_item(&mut self, item: Box<dyn ItemViewHandle>, cx: &mut ViewContext<Self>) -> usize {
 92        let item_idx = cmp::min(self.active_item + 1, self.items.len());
 93        self.items.insert(item_idx, item);
 94        cx.notify();
 95        item_idx
 96    }
 97
 98    #[cfg(test)]
 99    pub fn items(&self) -> &[Box<dyn ItemViewHandle>] {
100        &self.items
101    }
102
103    pub fn active_item(&self) -> Option<Box<dyn ItemViewHandle>> {
104        self.items.get(self.active_item).cloned()
105    }
106
107    pub fn activate_entry(
108        &mut self,
109        project_path: ProjectPath,
110        cx: &mut ViewContext<Self>,
111    ) -> bool {
112        if let Some(index) = self.items.iter().position(|item| {
113            item.project_path(cx.as_ref())
114                .map_or(false, |item_path| item_path == project_path)
115        }) {
116            self.activate_item(index, cx);
117            true
118        } else {
119            false
120        }
121    }
122
123    pub fn item_index(&self, item: &dyn ItemViewHandle) -> Option<usize> {
124        self.items.iter().position(|i| i.id() == item.id())
125    }
126
127    pub fn activate_item(&mut self, index: usize, cx: &mut ViewContext<Self>) {
128        if index < self.items.len() {
129            self.active_item = index;
130            self.focus_active_item(cx);
131            cx.notify();
132        }
133    }
134
135    pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
136        if self.active_item > 0 {
137            self.active_item -= 1;
138        } else if self.items.len() > 0 {
139            self.active_item = self.items.len() - 1;
140        }
141        self.focus_active_item(cx);
142        cx.notify();
143    }
144
145    pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
146        if self.active_item + 1 < self.items.len() {
147            self.active_item += 1;
148        } else {
149            self.active_item = 0;
150        }
151        self.focus_active_item(cx);
152        cx.notify();
153    }
154
155    pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) {
156        if !self.items.is_empty() {
157            self.close_item(self.items[self.active_item].id(), cx)
158        }
159    }
160
161    pub fn close_item(&mut self, item_id: usize, cx: &mut ViewContext<Self>) {
162        self.items.retain(|item| item.id() != item_id);
163        self.active_item = cmp::min(self.active_item, self.items.len().saturating_sub(1));
164        if self.items.is_empty() {
165            cx.emit(Event::Remove);
166        }
167        cx.notify();
168    }
169
170    fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
171        if let Some(active_item) = self.active_item() {
172            cx.focus(active_item.to_any());
173        }
174    }
175
176    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
177        cx.emit(Event::Split(direction));
178    }
179
180    fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
181        let settings = self.settings.borrow();
182        let theme = &settings.theme;
183
184        enum Tabs {}
185        let tabs = MouseEventHandler::new::<Tabs, _, _, _>(0, cx, |mouse_state, cx| {
186            let mut row = Flex::row();
187            for (ix, item) in self.items.iter().enumerate() {
188                let is_active = ix == self.active_item;
189
190                row.add_child({
191                    let mut title = item.title(cx);
192                    if title.len() > MAX_TAB_TITLE_LEN {
193                        let mut truncated_len = MAX_TAB_TITLE_LEN;
194                        while !title.is_char_boundary(truncated_len) {
195                            truncated_len -= 1;
196                        }
197                        title.truncate(truncated_len);
198                        title.push('…');
199                    }
200
201                    let mut style = if is_active {
202                        theme.workspace.active_tab.clone()
203                    } else {
204                        theme.workspace.tab.clone()
205                    };
206                    if ix == 0 {
207                        style.container.border.left = false;
208                    }
209
210                    EventHandler::new(
211                        Container::new(
212                            Flex::row()
213                                .with_child(
214                                    Align::new({
215                                        let diameter = 7.0;
216                                        let icon_color = if item.has_conflict(cx) {
217                                            Some(style.icon_conflict)
218                                        } else if item.is_dirty(cx) {
219                                            Some(style.icon_dirty)
220                                        } else {
221                                            None
222                                        };
223
224                                        ConstrainedBox::new(
225                                            Canvas::new(move |bounds, _, cx| {
226                                                if let Some(color) = icon_color {
227                                                    let square = RectF::new(
228                                                        bounds.origin(),
229                                                        vec2f(diameter, diameter),
230                                                    );
231                                                    cx.scene.push_quad(Quad {
232                                                        bounds: square,
233                                                        background: Some(color),
234                                                        border: Default::default(),
235                                                        corner_radius: diameter / 2.,
236                                                    });
237                                                }
238                                            })
239                                            .boxed(),
240                                        )
241                                        .with_width(diameter)
242                                        .with_height(diameter)
243                                        .boxed()
244                                    })
245                                    .boxed(),
246                                )
247                                .with_child(
248                                    Container::new(
249                                        Align::new(
250                                            Label::new(
251                                                title,
252                                                if is_active {
253                                                    theme.workspace.active_tab.label.clone()
254                                                } else {
255                                                    theme.workspace.tab.label.clone()
256                                                },
257                                            )
258                                            .boxed(),
259                                        )
260                                        .boxed(),
261                                    )
262                                    .with_style(ContainerStyle {
263                                        margin: Margin {
264                                            left: style.spacing,
265                                            right: style.spacing,
266                                            ..Default::default()
267                                        },
268                                        ..Default::default()
269                                    })
270                                    .boxed(),
271                                )
272                                .with_child(
273                                    Align::new(
274                                        ConstrainedBox::new(if mouse_state.hovered {
275                                            let item_id = item.id();
276                                            enum TabCloseButton {}
277                                            let icon = Svg::new("icons/x.svg");
278                                            MouseEventHandler::new::<TabCloseButton, _, _, _>(
279                                                item_id,
280                                                cx,
281                                                |mouse_state, _| {
282                                                    if mouse_state.hovered {
283                                                        icon.with_color(style.icon_close_active)
284                                                            .boxed()
285                                                    } else {
286                                                        icon.with_color(style.icon_close).boxed()
287                                                    }
288                                                },
289                                            )
290                                            .with_padding(Padding::uniform(4.))
291                                            .with_cursor_style(CursorStyle::PointingHand)
292                                            .on_click(move |cx| {
293                                                cx.dispatch_action(CloseItem(item_id))
294                                            })
295                                            .named("close-tab-icon")
296                                        } else {
297                                            Empty::new().boxed()
298                                        })
299                                        .with_width(style.icon_width)
300                                        .boxed(),
301                                    )
302                                    .boxed(),
303                                )
304                                .boxed(),
305                        )
306                        .with_style(style.container)
307                        .boxed(),
308                    )
309                    .on_mouse_down(move |cx| {
310                        cx.dispatch_action(ActivateItem(ix));
311                        true
312                    })
313                    .boxed()
314                })
315            }
316
317            row.add_child(
318                Expanded::new(
319                    0.0,
320                    Container::new(Empty::new().boxed())
321                        .with_border(theme.workspace.tab.container.border)
322                        .boxed(),
323                )
324                .named("filler"),
325            );
326
327            row.boxed()
328        });
329
330        ConstrainedBox::new(tabs.boxed())
331            .with_height(theme.workspace.tab.height)
332            .named("tabs")
333    }
334}
335
336impl Entity for Pane {
337    type Event = Event;
338}
339
340impl View for Pane {
341    fn ui_name() -> &'static str {
342        "Pane"
343    }
344
345    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
346        if let Some(active_item) = self.active_item() {
347            Flex::column()
348                .with_child(self.render_tabs(cx))
349                .with_child(Expanded::new(1.0, ChildView::new(active_item.id()).boxed()).boxed())
350                .named("pane")
351        } else {
352            Empty::new().named("pane")
353        }
354    }
355
356    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
357        self.focus_active_item(cx);
358    }
359}
360
361pub trait PaneHandle {
362    fn add_item_view(&self, item: Box<dyn ItemViewHandle>, cx: &mut MutableAppContext);
363}
364
365impl PaneHandle for ViewHandle<Pane> {
366    fn add_item_view(&self, item: Box<dyn ItemViewHandle>, cx: &mut MutableAppContext) {
367        item.set_parent_pane(self, cx);
368        self.update(cx, |pane, cx| {
369            let item_idx = pane.add_item(item, cx);
370            pane.activate_item(item_idx, cx);
371        });
372    }
373}