terminal_panel.rs

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