terminal_panel.rs

  1use std::{path::PathBuf, sync::Arc};
  2
  3use crate::TerminalView;
  4use db::kvp::KEY_VALUE_STORE;
  5use gpui::{
  6    actions, div, serde_json, AppContext, AsyncWindowContext, Entity, EventEmitter, ExternalPaths,
  7    FocusHandle, FocusableView, IntoElement, ParentElement, Pixels, Render, Styled, Subscription,
  8    Task, View, ViewContext, VisualContext, WeakView, WindowContext,
  9};
 10use project::Fs;
 11use serde::{Deserialize, Serialize};
 12use settings::{Settings, SettingsStore};
 13use terminal::terminal_settings::{TerminalDockPosition, TerminalSettings};
 14use ui::{h_stack, ButtonCommon, Clickable, IconButton, IconSize, Selectable, Tooltip};
 15use util::{ResultExt, TryFutureExt};
 16use workspace::{
 17    dock::{DockPosition, Panel, PanelEvent},
 18    item::Item,
 19    pane,
 20    ui::Icon,
 21    Pane, Workspace,
 22};
 23
 24use anyhow::Result;
 25
 26const TERMINAL_PANEL_KEY: &'static str = "TerminalPanel";
 27
 28actions!(terminal_panel, [ToggleFocus]);
 29
 30pub fn init(cx: &mut AppContext) {
 31    cx.observe_new_views(
 32        |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
 33            workspace.register_action(TerminalPanel::new_terminal);
 34            workspace.register_action(TerminalPanel::open_terminal);
 35            workspace.register_action(|workspace, _: &ToggleFocus, cx| {
 36                workspace.toggle_panel_focus::<TerminalPanel>(cx);
 37            });
 38        },
 39    )
 40    .detach();
 41}
 42
 43pub struct TerminalPanel {
 44    pane: View<Pane>,
 45    fs: Arc<dyn Fs>,
 46    workspace: WeakView<Workspace>,
 47    width: Option<Pixels>,
 48    height: Option<Pixels>,
 49    pending_serialization: Task<Option<()>>,
 50    _subscriptions: Vec<Subscription>,
 51}
 52
 53impl TerminalPanel {
 54    fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
 55        let terminal_panel = cx.view().clone();
 56        let pane = cx.new_view(|cx| {
 57            let mut pane = Pane::new(
 58                workspace.weak_handle(),
 59                workspace.project().clone(),
 60                Default::default(),
 61                Some(Arc::new(|a, cx| {
 62                    if let Some(tab) = a.downcast_ref::<workspace::pane::DraggedTab>() {
 63                        if let Some(item) = tab.pane.read(cx).item_for_index(tab.ix) {
 64                            return item.downcast::<TerminalView>().is_some();
 65                        }
 66                    }
 67                    if a.downcast_ref::<ExternalPaths>().is_some() {
 68                        return true;
 69                    }
 70
 71                    false
 72                })),
 73                cx,
 74            );
 75            pane.set_can_split(false, cx);
 76            pane.set_can_navigate(false, cx);
 77            pane.display_nav_history_buttons(false);
 78            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 79                h_stack()
 80                    .gap_2()
 81                    .child(
 82                        IconButton::new("plus", Icon::Plus)
 83                            .icon_size(IconSize::Small)
 84                            .on_click(cx.listener_for(&terminal_panel, |terminal_panel, _, cx| {
 85                                terminal_panel.add_terminal(None, cx);
 86                            }))
 87                            .tooltip(|cx| Tooltip::text("New Terminal", cx)),
 88                    )
 89                    .child({
 90                        let zoomed = pane.is_zoomed();
 91                        IconButton::new("toggle_zoom", Icon::Maximize)
 92                            .icon_size(IconSize::Small)
 93                            .selected(zoomed)
 94                            .selected_icon(Icon::Minimize)
 95                            .on_click(cx.listener(|pane, _, cx| {
 96                                pane.toggle_zoom(&workspace::ToggleZoom, cx);
 97                            }))
 98                            .tooltip(move |cx| {
 99                                Tooltip::text(if zoomed { "Zoom Out" } else { "Zoom In" }, cx)
100                            })
101                    })
102                    .into_any_element()
103            });
104            // let buffer_search_bar = cx.build_view(search::BufferSearchBar::new);
105            // pane.toolbar()
106            //     .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
107            pane
108        });
109        let subscriptions = vec![
110            cx.observe(&pane, |_, _, cx| cx.notify()),
111            cx.subscribe(&pane, Self::handle_pane_event),
112        ];
113        let this = Self {
114            pane,
115            fs: workspace.app_state().fs.clone(),
116            workspace: workspace.weak_handle(),
117            pending_serialization: Task::ready(None),
118            width: None,
119            height: None,
120            _subscriptions: subscriptions,
121        };
122        let mut old_dock_position = this.position(cx);
123        cx.observe_global::<SettingsStore>(move |this, cx| {
124            let new_dock_position = this.position(cx);
125            if new_dock_position != old_dock_position {
126                old_dock_position = new_dock_position;
127                cx.emit(PanelEvent::ChangePosition);
128            }
129        })
130        .detach();
131        this
132    }
133
134    pub async fn load(
135        workspace: WeakView<Workspace>,
136        mut cx: AsyncWindowContext,
137    ) -> Result<View<Self>> {
138        let serialized_panel = cx
139            .background_executor()
140            .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
141            .await
142            .log_err()
143            .flatten()
144            .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
145            .transpose()
146            .log_err()
147            .flatten();
148
149        let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
150            let panel = cx.new_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 pane = pane.downgrade();
180        let items = futures::future::join_all(items).await;
181        pane.update(&mut cx, |pane, cx| {
182            let active_item_id = serialized_panel
183                .as_ref()
184                .and_then(|panel| panel.active_item_id);
185            let mut active_ix = None;
186            for item in items {
187                if let Some(item) = item.log_err() {
188                    let item_id = item.entity_id().as_u64();
189                    pane.add_item(Box::new(item), false, false, None, cx);
190                    if Some(item_id) == active_item_id {
191                        active_ix = Some(pane.items_len() - 1);
192                    }
193                }
194            }
195
196            if let Some(active_ix) = active_ix {
197                pane.activate_item(active_ix, false, false, cx)
198            }
199        })?;
200
201        Ok(panel)
202    }
203
204    fn handle_pane_event(
205        &mut self,
206        _pane: View<Pane>,
207        event: &pane::Event,
208        cx: &mut ViewContext<Self>,
209    ) {
210        match event {
211            pane::Event::ActivateItem { .. } => self.serialize(cx),
212            pane::Event::RemoveItem { .. } => self.serialize(cx),
213            pane::Event::Remove => cx.emit(PanelEvent::Close),
214            pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
215            pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
216            pane::Event::Focus => cx.emit(PanelEvent::Focus),
217
218            pane::Event::AddItem { item } => {
219                if let Some(workspace) = self.workspace.upgrade() {
220                    let pane = self.pane.clone();
221                    workspace.update(cx, |workspace, cx| item.added_to_pane(workspace, pane, cx))
222                }
223            }
224
225            _ => {}
226        }
227    }
228
229    pub fn open_terminal(
230        workspace: &mut Workspace,
231        action: &workspace::OpenTerminal,
232        cx: &mut ViewContext<Workspace>,
233    ) {
234        let Some(this) = workspace.focus_panel::<Self>(cx) else {
235            return;
236        };
237
238        this.update(cx, |this, cx| {
239            this.add_terminal(Some(action.working_directory.clone()), cx)
240        })
241    }
242
243    ///Create a new Terminal in the current working directory or the user's home directory
244    fn new_terminal(
245        workspace: &mut Workspace,
246        _: &workspace::NewTerminal,
247        cx: &mut ViewContext<Workspace>,
248    ) {
249        let Some(this) = workspace.focus_panel::<Self>(cx) else {
250            return;
251        };
252
253        this.update(cx, |this, cx| this.add_terminal(None, cx))
254    }
255
256    fn add_terminal(&mut self, working_directory: Option<PathBuf>, cx: &mut ViewContext<Self>) {
257        let workspace = self.workspace.clone();
258        cx.spawn(|this, mut cx| async move {
259            let pane = this.update(&mut cx, |this, _| this.pane.clone())?;
260            workspace.update(&mut cx, |workspace, cx| {
261                let working_directory = if let Some(working_directory) = working_directory {
262                    Some(working_directory)
263                } else {
264                    let working_directory_strategy =
265                        TerminalSettings::get_global(cx).working_directory.clone();
266                    crate::get_working_directory(workspace, cx, working_directory_strategy)
267                };
268
269                let window = cx.window_handle();
270                if let Some(terminal) = workspace.project().update(cx, |project, cx| {
271                    project
272                        .create_terminal(working_directory, window, cx)
273                        .log_err()
274                }) {
275                    let terminal = Box::new(cx.new_view(|cx| {
276                        TerminalView::new(
277                            terminal,
278                            workspace.weak_handle(),
279                            workspace.database_id(),
280                            cx,
281                        )
282                    }));
283                    pane.update(cx, |pane, cx| {
284                        let focus = pane.has_focus(cx);
285                        pane.add_item(terminal, true, focus, None, cx);
286                    });
287                }
288            })?;
289            this.update(&mut cx, |this, cx| this.serialize(cx))?;
290            anyhow::Ok(())
291        })
292        .detach_and_log_err(cx);
293    }
294
295    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
296        let items = self
297            .pane
298            .read(cx)
299            .items()
300            .map(|item| item.item_id().as_u64())
301            .collect::<Vec<_>>();
302        let active_item_id = self
303            .pane
304            .read(cx)
305            .active_item()
306            .map(|item| item.item_id().as_u64());
307        let height = self.height;
308        let width = self.width;
309        self.pending_serialization = cx.background_executor().spawn(
310            async move {
311                KEY_VALUE_STORE
312                    .write_kvp(
313                        TERMINAL_PANEL_KEY.into(),
314                        serde_json::to_string(&SerializedTerminalPanel {
315                            items,
316                            active_item_id,
317                            height,
318                            width,
319                        })?,
320                    )
321                    .await?;
322                anyhow::Ok(())
323            }
324            .log_err(),
325        );
326    }
327}
328
329impl EventEmitter<PanelEvent> for TerminalPanel {}
330
331impl Render for TerminalPanel {
332    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
333        div().size_full().child(self.pane.clone())
334    }
335}
336
337impl FocusableView for TerminalPanel {
338    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
339        self.pane.focus_handle(cx)
340    }
341}
342
343impl Panel for TerminalPanel {
344    fn position(&self, cx: &WindowContext) -> DockPosition {
345        match TerminalSettings::get_global(cx).dock {
346            TerminalDockPosition::Left => DockPosition::Left,
347            TerminalDockPosition::Bottom => DockPosition::Bottom,
348            TerminalDockPosition::Right => DockPosition::Right,
349        }
350    }
351
352    fn position_is_valid(&self, _: DockPosition) -> bool {
353        true
354    }
355
356    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
357        settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
358            let dock = match position {
359                DockPosition::Left => TerminalDockPosition::Left,
360                DockPosition::Bottom => TerminalDockPosition::Bottom,
361                DockPosition::Right => TerminalDockPosition::Right,
362            };
363            settings.dock = Some(dock);
364        });
365    }
366
367    fn size(&self, cx: &WindowContext) -> Pixels {
368        let settings = TerminalSettings::get_global(cx);
369        match self.position(cx) {
370            DockPosition::Left | DockPosition::Right => {
371                self.width.unwrap_or_else(|| settings.default_width)
372            }
373            DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
374        }
375    }
376
377    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
378        match self.position(cx) {
379            DockPosition::Left | DockPosition::Right => self.width = size,
380            DockPosition::Bottom => self.height = size,
381        }
382        self.serialize(cx);
383        cx.notify();
384    }
385
386    fn is_zoomed(&self, cx: &WindowContext) -> bool {
387        self.pane.read(cx).is_zoomed()
388    }
389
390    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
391        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
392    }
393
394    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
395        if active && self.pane.read(cx).items_len() == 0 {
396            self.add_terminal(None, cx)
397        }
398    }
399
400    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
401        let count = self.pane.read(cx).items_len();
402        if count == 0 {
403            None
404        } else {
405            Some(count.to_string())
406        }
407    }
408
409    fn persistent_name() -> &'static str {
410        "TerminalPanel"
411    }
412
413    // todo!()
414    // fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
415    //     ("Terminal Panel".into(), Some(Box::new(ToggleFocus)))
416    // }
417
418    fn icon(&self, _cx: &WindowContext) -> Option<Icon> {
419        Some(Icon::Terminal)
420    }
421
422    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
423        Some("Terminal Panel")
424    }
425
426    fn toggle_action(&self) -> Box<dyn gpui::Action> {
427        Box::new(ToggleFocus)
428    }
429}
430
431#[derive(Serialize, Deserialize)]
432struct SerializedTerminalPanel {
433    items: Vec<u64>,
434    active_item_id: Option<u64>,
435    width: Option<Pixels>,
436    height: Option<Pixels>,
437}