toolbar.rs

  1use crate::ItemHandle;
  2use gpui::{
  3    AnyView, Div, Entity, EntityId, EventEmitter, ParentElement as _, Render, Styled, View,
  4    ViewContext, WindowContext,
  5};
  6use ui::prelude::*;
  7use ui::{h_stack, v_stack};
  8
  9pub enum ToolbarItemEvent {
 10    ChangeLocation(ToolbarItemLocation),
 11}
 12
 13pub trait ToolbarItemView: Render + EventEmitter<ToolbarItemEvent> {
 14    fn set_active_pane_item(
 15        &mut self,
 16        active_pane_item: Option<&dyn crate::ItemHandle>,
 17        cx: &mut ViewContext<Self>,
 18    ) -> ToolbarItemLocation;
 19
 20    fn pane_focus_update(&mut self, _pane_focused: bool, _cx: &mut ViewContext<Self>) {}
 21
 22    /// Number of times toolbar's height will be repeated to get the effective height.
 23    /// Useful when multiple rows one under each other are needed.
 24    /// The rows have the same width and act as a whole when reacting to resizes and similar events.
 25    fn row_count(&self, _cx: &WindowContext) -> usize {
 26        1
 27    }
 28}
 29
 30trait ToolbarItemViewHandle: Send {
 31    fn id(&self) -> EntityId;
 32    fn to_any(&self) -> AnyView;
 33    fn set_active_pane_item(
 34        &self,
 35        active_pane_item: Option<&dyn ItemHandle>,
 36        cx: &mut WindowContext,
 37    ) -> ToolbarItemLocation;
 38    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext);
 39    fn row_count(&self, cx: &WindowContext) -> usize;
 40}
 41
 42#[derive(Copy, Clone, Debug, PartialEq)]
 43pub enum ToolbarItemLocation {
 44    Hidden,
 45    PrimaryLeft,
 46    PrimaryRight,
 47    Secondary,
 48}
 49
 50pub struct Toolbar {
 51    active_item: Option<Box<dyn ItemHandle>>,
 52    hidden: bool,
 53    can_navigate: bool,
 54    items: Vec<(Box<dyn ToolbarItemViewHandle>, ToolbarItemLocation)>,
 55}
 56
 57impl Toolbar {
 58    fn left_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 59        self.items.iter().filter_map(|(item, location)| {
 60            if *location == ToolbarItemLocation::PrimaryLeft {
 61                Some(item.as_ref())
 62            } else {
 63                None
 64            }
 65        })
 66    }
 67
 68    fn right_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 69        self.items.iter().filter_map(|(item, location)| {
 70            if *location == ToolbarItemLocation::PrimaryRight {
 71                Some(item.as_ref())
 72            } else {
 73                None
 74            }
 75        })
 76    }
 77}
 78
 79impl Render for Toolbar {
 80    type Element = Div;
 81
 82    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
 83        v_stack()
 84            .border_b()
 85            .border_color(cx.theme().colors().border_variant)
 86            .bg(cx.theme().colors().toolbar_background)
 87            .child(
 88                h_stack()
 89                    .justify_between()
 90                    .children(self.items.iter().map(|(child, _)| child.to_any())),
 91            )
 92    }
 93}
 94
 95// todo!()
 96// impl View for Toolbar {
 97//     fn ui_name() -> &'static str {
 98//         "Toolbar"
 99//     }
100
101//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
102//         let theme = &theme::current(cx).workspace.toolbar;
103
104//         let mut primary_left_items = Vec::new();
105//         let mut primary_right_items = Vec::new();
106//         let mut secondary_item = None;
107//         let spacing = theme.item_spacing;
108//         let mut primary_items_row_count = 1;
109
110//         for (item, position) in &self.items {
111//             match *position {
112//                 ToolbarItemLocation::Hidden => {}
113
114//                 ToolbarItemLocation::PrimaryLeft { flex } => {
115//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
116//                     let left_item = ChildView::new(item.as_any(), cx).aligned();
117//                     if let Some((flex, expanded)) = flex {
118//                         primary_left_items.push(left_item.flex(flex, expanded).into_any());
119//                     } else {
120//                         primary_left_items.push(left_item.into_any());
121//                     }
122//                 }
123
124//                 ToolbarItemLocation::PrimaryRight { flex } => {
125//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
126//                     let right_item = ChildView::new(item.as_any(), cx).aligned().flex_float();
127//                     if let Some((flex, expanded)) = flex {
128//                         primary_right_items.push(right_item.flex(flex, expanded).into_any());
129//                     } else {
130//                         primary_right_items.push(right_item.into_any());
131//                     }
132//                 }
133
134//                 ToolbarItemLocation::Secondary => {
135//                     secondary_item = Some(
136//                         ChildView::new(item.as_any(), cx)
137//                             .constrained()
138//                             .with_height(theme.height * item.row_count(cx) as f32)
139//                             .into_any(),
140//                     );
141//                 }
142//             }
143//         }
144
145//         let container_style = theme.container;
146//         let height = theme.height * primary_items_row_count as f32;
147
148//         let mut primary_items = Flex::row().with_spacing(spacing);
149//         primary_items.extend(primary_left_items);
150//         primary_items.extend(primary_right_items);
151
152//         let mut toolbar = Flex::column();
153//         if !primary_items.is_empty() {
154//             toolbar.add_child(primary_items.constrained().with_height(height));
155//         }
156//         if let Some(secondary_item) = secondary_item {
157//             toolbar.add_child(secondary_item);
158//         }
159
160//         if toolbar.is_empty() {
161//             toolbar.into_any_named("toolbar")
162//         } else {
163//             toolbar
164//                 .contained()
165//                 .with_style(container_style)
166//                 .into_any_named("toolbar")
167//         }
168//     }
169// }
170
171impl Toolbar {
172    pub fn new() -> Self {
173        Self {
174            active_item: None,
175            items: Default::default(),
176            hidden: false,
177            can_navigate: true,
178        }
179    }
180
181    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
182        self.can_navigate = can_navigate;
183        cx.notify();
184    }
185
186    pub fn add_item<T>(&mut self, item: View<T>, cx: &mut ViewContext<Self>)
187    where
188        T: 'static + ToolbarItemView,
189    {
190        let location = item.set_active_pane_item(self.active_item.as_deref(), cx);
191        cx.subscribe(&item, |this, item, event, cx| {
192            if let Some((_, current_location)) =
193                this.items.iter_mut().find(|(i, _)| i.id() == item.id())
194            {
195                match event {
196                    ToolbarItemEvent::ChangeLocation(new_location) => {
197                        if new_location != current_location {
198                            *current_location = *new_location;
199                            cx.notify();
200                        }
201                    }
202                }
203            }
204        })
205        .detach();
206        self.items.push((Box::new(item), location));
207        cx.notify();
208    }
209
210    pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
211        self.active_item = item.map(|item| item.boxed_clone());
212        self.hidden = self
213            .active_item
214            .as_ref()
215            .map(|item| !item.show_toolbar(cx))
216            .unwrap_or(false);
217
218        for (toolbar_item, current_location) in self.items.iter_mut() {
219            let new_location = toolbar_item.set_active_pane_item(item, cx);
220            if new_location != *current_location {
221                *current_location = new_location;
222                cx.notify();
223            }
224        }
225    }
226
227    pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext<Self>) {
228        for (toolbar_item, _) in self.items.iter_mut() {
229            toolbar_item.focus_changed(focused, cx);
230        }
231    }
232
233    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<View<T>> {
234        self.items
235            .iter()
236            .find_map(|(item, _)| item.to_any().downcast().ok())
237    }
238
239    pub fn hidden(&self) -> bool {
240        self.hidden
241    }
242}
243
244impl<T: ToolbarItemView> ToolbarItemViewHandle for View<T> {
245    fn id(&self) -> EntityId {
246        self.entity_id()
247    }
248
249    fn to_any(&self) -> AnyView {
250        self.clone().into()
251    }
252
253    fn set_active_pane_item(
254        &self,
255        active_pane_item: Option<&dyn ItemHandle>,
256        cx: &mut WindowContext,
257    ) -> ToolbarItemLocation {
258        self.update(cx, |this, cx| {
259            this.set_active_pane_item(active_pane_item, cx)
260        })
261    }
262
263    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) {
264        self.update(cx, |this, cx| {
265            this.pane_focus_update(pane_focused, cx);
266            cx.notify();
267        });
268    }
269
270    fn row_count(&self, cx: &WindowContext) -> usize {
271        self.read(cx).row_count(cx)
272    }
273}
274
275// todo!()
276// impl From<&dyn ToolbarItemViewHandle> for AnyViewHandle {
277//     fn from(val: &dyn ToolbarItemViewHandle) -> Self {
278//         val.as_any().clone()
279//     }
280// }