terminal_panel.rs

  1use std::sync::Arc;
  2
  3use crate::TerminalView;
  4use db::kvp::KEY_VALUE_STORE;
  5use gpui::{
  6    actions, anyhow::Result, elements::*, serde_json, Action, AppContext, AsyncAppContext, Entity,
  7    Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
  8};
  9use project::Fs;
 10use serde::{Deserialize, Serialize};
 11use settings::SettingsStore;
 12use terminal::{TerminalDockPosition, TerminalSettings};
 13use util::{ResultExt, TryFutureExt};
 14use workspace::{
 15    dock::{DockPosition, Panel},
 16    item::Item,
 17    pane, DraggedItem, Pane, Workspace,
 18};
 19
 20const TERMINAL_PANEL_KEY: &'static str = "TerminalPanel";
 21
 22actions!(terminal_panel, [ToggleFocus]);
 23
 24pub fn init(cx: &mut AppContext) {
 25    cx.add_action(TerminalPanel::add_terminal);
 26}
 27
 28pub enum Event {
 29    Close,
 30    DockPositionChanged,
 31    ZoomIn,
 32    ZoomOut,
 33    Focus,
 34}
 35
 36pub struct TerminalPanel {
 37    pane: ViewHandle<Pane>,
 38    fs: Arc<dyn Fs>,
 39    workspace: WeakViewHandle<Workspace>,
 40    width: Option<f32>,
 41    height: Option<f32>,
 42    pending_serialization: Task<Option<()>>,
 43    _subscriptions: Vec<Subscription>,
 44}
 45
 46impl TerminalPanel {
 47    fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
 48        let weak_self = cx.weak_handle();
 49        let pane = cx.add_view(|cx| {
 50            let window_id = cx.window_id();
 51            let mut pane = Pane::new(
 52                workspace.weak_handle(),
 53                workspace.app_state().background_actions,
 54                Default::default(),
 55                cx,
 56            );
 57            pane.set_can_split(false, cx);
 58            pane.set_can_navigate(false, cx);
 59            pane.on_can_drop(move |drag_and_drop, cx| {
 60                drag_and_drop
 61                    .currently_dragged::<DraggedItem>(window_id)
 62                    .map_or(false, |(_, item)| {
 63                        item.handle.act_as::<TerminalView>(cx).is_some()
 64                    })
 65            });
 66            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 67                let this = weak_self.clone();
 68                Flex::row()
 69                    .with_child(Pane::render_tab_bar_button(
 70                        0,
 71                        "icons/plus_12.svg",
 72                        Some((
 73                            "New Terminal".into(),
 74                            Some(Box::new(workspace::NewTerminal)),
 75                        )),
 76                        cx,
 77                        move |_, cx| {
 78                            let this = this.clone();
 79                            cx.window_context().defer(move |cx| {
 80                                if let Some(this) = this.upgrade(cx) {
 81                                    this.update(cx, |this, cx| {
 82                                        this.add_terminal(&Default::default(), cx);
 83                                    });
 84                                }
 85                            })
 86                        },
 87                        None,
 88                    ))
 89                    .with_child(Pane::render_tab_bar_button(
 90                        1,
 91                        if pane.is_zoomed() {
 92                            "icons/minimize_8.svg"
 93                        } else {
 94                            "icons/maximize_8.svg"
 95                        },
 96                        Some(("Toggle Zoom".into(), Some(Box::new(workspace::ToggleZoom)))),
 97                        cx,
 98                        move |pane, cx| pane.toggle_zoom(&Default::default(), cx),
 99                        None,
100                    ))
101                    .into_any()
102            });
103            let buffer_search_bar = cx.add_view(search::BufferSearchBar::new);
104            pane.toolbar()
105                .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
106            pane
107        });
108        let subscriptions = vec![
109            cx.observe(&pane, |_, _, cx| cx.notify()),
110            cx.subscribe(&pane, Self::handle_pane_event),
111        ];
112        let this = Self {
113            pane,
114            fs: workspace.app_state().fs.clone(),
115            workspace: workspace.weak_handle(),
116            pending_serialization: Task::ready(None),
117            width: None,
118            height: None,
119            _subscriptions: subscriptions,
120        };
121        let mut old_dock_position = this.position(cx);
122        cx.observe_global::<SettingsStore, _>(move |this, cx| {
123            let new_dock_position = this.position(cx);
124            if new_dock_position != old_dock_position {
125                old_dock_position = new_dock_position;
126                cx.emit(Event::DockPositionChanged);
127            }
128        })
129        .detach();
130        this
131    }
132
133    pub fn load(
134        workspace: WeakViewHandle<Workspace>,
135        cx: AsyncAppContext,
136    ) -> Task<Result<ViewHandle<Self>>> {
137        cx.spawn(|mut cx| async move {
138            let serialized_panel = if let Some(panel) = cx
139                .background()
140                .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
141                .await
142                .log_err()
143                .flatten()
144            {
145                Some(serde_json::from_str::<SerializedTerminalPanel>(&panel)?)
146            } else {
147                None
148            };
149            let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
150                let panel = cx.add_view(|cx| TerminalPanel::new(workspace, cx));
151                let items = if let Some(serialized_panel) = serialized_panel.as_ref() {
152                    panel.update(cx, |panel, cx| {
153                        cx.notify();
154                        panel.height = serialized_panel.height;
155                        panel.width = serialized_panel.width;
156                        panel.pane.update(cx, |_, cx| {
157                            serialized_panel
158                                .items
159                                .iter()
160                                .map(|item_id| {
161                                    TerminalView::deserialize(
162                                        workspace.project().clone(),
163                                        workspace.weak_handle(),
164                                        workspace.database_id(),
165                                        *item_id,
166                                        cx,
167                                    )
168                                })
169                                .collect::<Vec<_>>()
170                        })
171                    })
172                } else {
173                    Default::default()
174                };
175                let pane = panel.read(cx).pane.clone();
176                (panel, pane, items)
177            })?;
178
179            let items = futures::future::join_all(items).await;
180            workspace.update(&mut cx, |workspace, cx| {
181                let active_item_id = serialized_panel
182                    .as_ref()
183                    .and_then(|panel| panel.active_item_id);
184                let mut active_ix = None;
185                for item in items {
186                    if let Some(item) = item.log_err() {
187                        let item_id = item.id();
188                        Pane::add_item(workspace, &pane, Box::new(item), false, false, None, cx);
189                        if Some(item_id) == active_item_id {
190                            active_ix = Some(pane.read(cx).items_len() - 1);
191                        }
192                    }
193                }
194
195                if let Some(active_ix) = active_ix {
196                    pane.update(cx, |pane, cx| {
197                        pane.activate_item(active_ix, false, false, cx)
198                    });
199                }
200            })?;
201
202            Ok(panel)
203        })
204    }
205
206    fn handle_pane_event(
207        &mut self,
208        _pane: ViewHandle<Pane>,
209        event: &pane::Event,
210        cx: &mut ViewContext<Self>,
211    ) {
212        match event {
213            pane::Event::ActivateItem { .. } => self.serialize(cx),
214            pane::Event::RemoveItem { .. } => self.serialize(cx),
215            pane::Event::Remove => cx.emit(Event::Close),
216            pane::Event::ZoomIn => cx.emit(Event::ZoomIn),
217            pane::Event::ZoomOut => cx.emit(Event::ZoomOut),
218            pane::Event::Focus => cx.emit(Event::Focus),
219            _ => {}
220        }
221    }
222
223    fn add_terminal(&mut self, _: &workspace::NewTerminal, cx: &mut ViewContext<Self>) {
224        let workspace = self.workspace.clone();
225        cx.spawn(|this, mut cx| async move {
226            let pane = this.read_with(&cx, |this, _| this.pane.clone())?;
227            workspace.update(&mut cx, |workspace, cx| {
228                let working_directory_strategy = settings::get::<TerminalSettings>(cx)
229                    .working_directory
230                    .clone();
231                let working_directory =
232                    crate::get_working_directory(workspace, cx, working_directory_strategy);
233                let window_id = cx.window_id();
234                if let Some(terminal) = workspace.project().update(cx, |project, cx| {
235                    project
236                        .create_terminal(working_directory, window_id, cx)
237                        .log_err()
238                }) {
239                    let terminal =
240                        Box::new(cx.add_view(|cx| {
241                            TerminalView::new(terminal, workspace.database_id(), cx)
242                        }));
243                    let focus = pane.read(cx).has_focus();
244                    Pane::add_item(workspace, &pane, terminal, true, focus, None, cx);
245                }
246            })?;
247            this.update(&mut cx, |this, cx| this.serialize(cx))?;
248            anyhow::Ok(())
249        })
250        .detach_and_log_err(cx);
251    }
252
253    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
254        let items = self
255            .pane
256            .read(cx)
257            .items()
258            .map(|item| item.id())
259            .collect::<Vec<_>>();
260        let active_item_id = self.pane.read(cx).active_item().map(|item| item.id());
261        let height = self.height;
262        let width = self.width;
263        self.pending_serialization = cx.background().spawn(
264            async move {
265                KEY_VALUE_STORE
266                    .write_kvp(
267                        TERMINAL_PANEL_KEY.into(),
268                        serde_json::to_string(&SerializedTerminalPanel {
269                            items,
270                            active_item_id,
271                            height,
272                            width,
273                        })?,
274                    )
275                    .await?;
276                anyhow::Ok(())
277            }
278            .log_err(),
279        );
280    }
281}
282
283impl Entity for TerminalPanel {
284    type Event = Event;
285}
286
287impl View for TerminalPanel {
288    fn ui_name() -> &'static str {
289        "TerminalPanel"
290    }
291
292    fn render(&mut self, cx: &mut ViewContext<Self>) -> gpui::AnyElement<Self> {
293        ChildView::new(&self.pane, cx).into_any()
294    }
295
296    fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {
297        if cx.is_self_focused() {
298            cx.focus(&self.pane);
299        }
300    }
301}
302
303impl Panel for TerminalPanel {
304    fn position(&self, cx: &WindowContext) -> DockPosition {
305        match settings::get::<TerminalSettings>(cx).dock {
306            TerminalDockPosition::Left => DockPosition::Left,
307            TerminalDockPosition::Bottom => DockPosition::Bottom,
308            TerminalDockPosition::Right => DockPosition::Right,
309        }
310    }
311
312    fn position_is_valid(&self, _: DockPosition) -> bool {
313        true
314    }
315
316    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
317        settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
318            let dock = match position {
319                DockPosition::Left => TerminalDockPosition::Left,
320                DockPosition::Bottom => TerminalDockPosition::Bottom,
321                DockPosition::Right => TerminalDockPosition::Right,
322            };
323            settings.dock = Some(dock);
324        });
325    }
326
327    fn size(&self, cx: &WindowContext) -> f32 {
328        let settings = settings::get::<TerminalSettings>(cx);
329        match self.position(cx) {
330            DockPosition::Left | DockPosition::Right => {
331                self.width.unwrap_or_else(|| settings.default_width)
332            }
333            DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
334        }
335    }
336
337    fn set_size(&mut self, size: f32, cx: &mut ViewContext<Self>) {
338        match self.position(cx) {
339            DockPosition::Left | DockPosition::Right => self.width = Some(size),
340            DockPosition::Bottom => self.height = Some(size),
341        }
342        self.serialize(cx);
343        cx.notify();
344    }
345
346    fn should_zoom_in_on_event(event: &Event) -> bool {
347        matches!(event, Event::ZoomIn)
348    }
349
350    fn should_zoom_out_on_event(event: &Event) -> bool {
351        matches!(event, Event::ZoomOut)
352    }
353
354    fn is_zoomed(&self, cx: &WindowContext) -> bool {
355        self.pane.read(cx).is_zoomed()
356    }
357
358    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
359        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
360    }
361
362    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
363        if active && self.pane.read(cx).items_len() == 0 {
364            self.add_terminal(&Default::default(), cx)
365        }
366    }
367
368    fn icon_path(&self) -> &'static str {
369        "icons/terminal_12.svg"
370    }
371
372    fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
373        ("Terminal Panel".into(), Some(Box::new(ToggleFocus)))
374    }
375
376    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
377        let count = self.pane.read(cx).items_len();
378        if count == 0 {
379            None
380        } else {
381            Some(count.to_string())
382        }
383    }
384
385    fn should_change_position_on_event(event: &Self::Event) -> bool {
386        matches!(event, Event::DockPositionChanged)
387    }
388
389    fn should_activate_on_event(_: &Self::Event) -> bool {
390        false
391    }
392
393    fn should_close_on_event(event: &Event) -> bool {
394        matches!(event, Event::Close)
395    }
396
397    fn has_focus(&self, cx: &WindowContext) -> bool {
398        self.pane.read(cx).has_focus()
399    }
400
401    fn is_focus_event(event: &Self::Event) -> bool {
402        matches!(event, Event::Focus)
403    }
404}
405
406#[derive(Serialize, Deserialize)]
407struct SerializedTerminalPanel {
408    items: Vec<usize>,
409    active_item_id: Option<usize>,
410    width: Option<f32>,
411    height: Option<f32>,
412}