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