terminal_panel.rs

  1use std::{ops::ControlFlow, path::PathBuf, sync::Arc};
  2
  3use crate::TerminalView;
  4use collections::{HashMap, HashSet};
  5use db::kvp::KEY_VALUE_STORE;
  6use futures::future::join_all;
  7use gpui::{
  8    actions, Action, AppContext, AsyncWindowContext, DismissEvent, Entity, EventEmitter,
  9    ExternalPaths, FocusHandle, FocusableView, IntoElement, Model, ParentElement, Pixels, Render,
 10    Styled, Subscription, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
 11};
 12use itertools::Itertools;
 13use project::{Fs, ProjectEntryId};
 14use search::{buffer_search::DivRegistrar, BufferSearchBar};
 15use serde::{Deserialize, Serialize};
 16use settings::Settings;
 17use task::{RevealStrategy, SpawnInTerminal, TaskId, TerminalWorkDir};
 18use terminal::{
 19    terminal_settings::{Shell, TerminalDockPosition, TerminalSettings},
 20    Terminal,
 21};
 22use ui::{
 23    h_flex, ButtonCommon, Clickable, ContextMenu, FluentBuilder, IconButton, IconSize, Selectable,
 24    Tooltip,
 25};
 26use util::{ResultExt, TryFutureExt};
 27use workspace::{
 28    dock::{DockPosition, Panel, PanelEvent},
 29    item::Item,
 30    pane,
 31    ui::IconName,
 32    DraggedTab, NewTerminal, Pane, ToggleZoom, Workspace,
 33};
 34
 35use anyhow::Result;
 36
 37const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
 38
 39actions!(terminal_panel, [ToggleFocus]);
 40
 41pub fn init(cx: &mut AppContext) {
 42    cx.observe_new_views(
 43        |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
 44            workspace.register_action(TerminalPanel::new_terminal);
 45            workspace.register_action(TerminalPanel::open_terminal);
 46            workspace.register_action(|workspace, _: &ToggleFocus, cx| {
 47                if workspace
 48                    .panel::<TerminalPanel>(cx)
 49                    .as_ref()
 50                    .is_some_and(|panel| panel.read(cx).enabled)
 51                {
 52                    workspace.toggle_panel_focus::<TerminalPanel>(cx);
 53                }
 54            });
 55        },
 56    )
 57    .detach();
 58}
 59
 60pub struct TerminalPanel {
 61    pane: View<Pane>,
 62    fs: Arc<dyn Fs>,
 63    workspace: WeakView<Workspace>,
 64    width: Option<Pixels>,
 65    height: Option<Pixels>,
 66    pending_serialization: Task<Option<()>>,
 67    pending_terminals_to_add: usize,
 68    _subscriptions: Vec<Subscription>,
 69    deferred_tasks: HashMap<TaskId, Task<()>>,
 70    enabled: bool,
 71}
 72
 73impl TerminalPanel {
 74    fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
 75        let pane = cx.new_view(|cx| {
 76            let mut pane = Pane::new(
 77                workspace.weak_handle(),
 78                workspace.project().clone(),
 79                Default::default(),
 80                None,
 81                NewTerminal.boxed_clone(),
 82                cx,
 83            );
 84            pane.set_can_split(false, cx);
 85            pane.set_can_navigate(false, cx);
 86            pane.display_nav_history_buttons(None);
 87            pane.set_should_display_tab_bar(|_| true);
 88            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 89                h_flex()
 90                    .gap_2()
 91                    .child(
 92                        IconButton::new("plus", IconName::Plus)
 93                            .icon_size(IconSize::Small)
 94                            .on_click(cx.listener(|pane, _, cx| {
 95                                let focus_handle = pane.focus_handle(cx);
 96                                let menu = ContextMenu::build(cx, |menu, _| {
 97                                    menu.action(
 98                                        "New Terminal",
 99                                        workspace::NewTerminal.boxed_clone(),
100                                    )
101                                    .entry(
102                                        "Spawn task",
103                                        Some(tasks_ui::Spawn::modal().boxed_clone()),
104                                        move |cx| {
105                                            // We want the focus to go back to terminal panel once task modal is dismissed,
106                                            // hence we focus that first. Otherwise, we'd end up without a focused element, as
107                                            // context menu will be gone the moment we spawn the modal.
108                                            cx.focus(&focus_handle);
109                                            cx.dispatch_action(
110                                                tasks_ui::Spawn::modal().boxed_clone(),
111                                            );
112                                        },
113                                    )
114                                });
115                                cx.subscribe(&menu, |pane, _, _: &DismissEvent, _| {
116                                    pane.new_item_menu = None;
117                                })
118                                .detach();
119                                pane.new_item_menu = Some(menu);
120                            }))
121                            .tooltip(|cx| Tooltip::text("New...", cx)),
122                    )
123                    .when_some(pane.new_item_menu.as_ref(), |el, new_item_menu| {
124                        el.child(Pane::render_menu_overlay(new_item_menu))
125                    })
126                    .child({
127                        let zoomed = pane.is_zoomed();
128                        IconButton::new("toggle_zoom", IconName::Maximize)
129                            .icon_size(IconSize::Small)
130                            .selected(zoomed)
131                            .selected_icon(IconName::Minimize)
132                            .on_click(cx.listener(|pane, _, cx| {
133                                pane.toggle_zoom(&workspace::ToggleZoom, cx);
134                            }))
135                            .tooltip(move |cx| {
136                                Tooltip::for_action(
137                                    if zoomed { "Zoom Out" } else { "Zoom In" },
138                                    &ToggleZoom,
139                                    cx,
140                                )
141                            })
142                    })
143                    .into_any_element()
144            });
145
146            let workspace = workspace.weak_handle();
147            pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
148                if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
149                    let item = if &tab.pane == cx.view() {
150                        pane.item_for_index(tab.ix)
151                    } else {
152                        tab.pane.read(cx).item_for_index(tab.ix)
153                    };
154                    if let Some(item) = item {
155                        if item.downcast::<TerminalView>().is_some() {
156                            return ControlFlow::Continue(());
157                        } else if let Some(project_path) = item.project_path(cx) {
158                            if let Some(entry_path) = workspace
159                                .update(cx, |workspace, cx| {
160                                    workspace
161                                        .project()
162                                        .read(cx)
163                                        .absolute_path(&project_path, cx)
164                                })
165                                .log_err()
166                                .flatten()
167                            {
168                                add_paths_to_terminal(pane, &[entry_path], cx);
169                            }
170                        }
171                    }
172                } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
173                    if let Some(entry_path) = workspace
174                        .update(cx, |workspace, cx| {
175                            let project = workspace.project().read(cx);
176                            project
177                                .path_for_entry(entry_id, cx)
178                                .and_then(|project_path| project.absolute_path(&project_path, cx))
179                        })
180                        .log_err()
181                        .flatten()
182                    {
183                        add_paths_to_terminal(pane, &[entry_path], cx);
184                    }
185                } else if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
186                    add_paths_to_terminal(pane, paths.paths(), cx);
187                }
188
189                ControlFlow::Break(())
190            });
191            let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
192            pane.toolbar()
193                .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
194            pane
195        });
196        let subscriptions = vec![
197            cx.observe(&pane, |_, _, cx| cx.notify()),
198            cx.subscribe(&pane, Self::handle_pane_event),
199        ];
200        let project = workspace.project().read(cx);
201        let enabled = project.is_local() || project.supports_remote_terminal(cx);
202        let this = Self {
203            pane,
204            fs: workspace.app_state().fs.clone(),
205            workspace: workspace.weak_handle(),
206            pending_serialization: Task::ready(None),
207            width: None,
208            height: None,
209            pending_terminals_to_add: 0,
210            deferred_tasks: HashMap::default(),
211            _subscriptions: subscriptions,
212            enabled,
213        };
214        this
215    }
216
217    pub async fn load(
218        workspace: WeakView<Workspace>,
219        mut cx: AsyncWindowContext,
220    ) -> Result<View<Self>> {
221        let serialized_panel = cx
222            .background_executor()
223            .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
224            .await
225            .log_err()
226            .flatten()
227            .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
228            .transpose()
229            .log_err()
230            .flatten();
231
232        let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
233            let panel = cx.new_view(|cx| TerminalPanel::new(workspace, cx));
234            let items = if let Some((serialized_panel, database_id)) =
235                serialized_panel.as_ref().zip(workspace.database_id())
236            {
237                panel.update(cx, |panel, cx| {
238                    cx.notify();
239                    panel.height = serialized_panel.height.map(|h| h.round());
240                    panel.width = serialized_panel.width.map(|w| w.round());
241                    panel.pane.update(cx, |_, cx| {
242                        serialized_panel
243                            .items
244                            .iter()
245                            .map(|item_id| {
246                                TerminalView::deserialize(
247                                    workspace.project().clone(),
248                                    workspace.weak_handle(),
249                                    database_id,
250                                    *item_id,
251                                    cx,
252                                )
253                            })
254                            .collect::<Vec<_>>()
255                    })
256                })
257            } else {
258                Vec::new()
259            };
260            let pane = panel.read(cx).pane.clone();
261            (panel, pane, items)
262        })?;
263
264        if let Some(workspace) = workspace.upgrade() {
265            panel
266                .update(&mut cx, |panel, cx| {
267                    panel._subscriptions.push(cx.subscribe(
268                        &workspace,
269                        |terminal_panel, _, e, cx| {
270                            if let workspace::Event::SpawnTask(spawn_in_terminal) = e {
271                                terminal_panel.spawn_task(spawn_in_terminal, cx);
272                            };
273                        },
274                    ))
275                })
276                .ok();
277        }
278
279        let pane = pane.downgrade();
280        let items = futures::future::join_all(items).await;
281        pane.update(&mut cx, |pane, cx| {
282            let active_item_id = serialized_panel
283                .as_ref()
284                .and_then(|panel| panel.active_item_id);
285            let mut active_ix = None;
286            for item in items {
287                if let Some(item) = item.log_err() {
288                    let item_id = item.entity_id().as_u64();
289                    pane.add_item(Box::new(item), false, false, None, cx);
290                    if Some(item_id) == active_item_id {
291                        active_ix = Some(pane.items_len() - 1);
292                    }
293                }
294            }
295
296            if let Some(active_ix) = active_ix {
297                pane.activate_item(active_ix, false, false, cx)
298            }
299        })?;
300
301        Ok(panel)
302    }
303
304    fn handle_pane_event(
305        &mut self,
306        _pane: View<Pane>,
307        event: &pane::Event,
308        cx: &mut ViewContext<Self>,
309    ) {
310        match event {
311            pane::Event::ActivateItem { .. } => self.serialize(cx),
312            pane::Event::RemoveItem { .. } => self.serialize(cx),
313            pane::Event::Remove => cx.emit(PanelEvent::Close),
314            pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
315            pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
316
317            pane::Event::AddItem { item } => {
318                if let Some(workspace) = self.workspace.upgrade() {
319                    let pane = self.pane.clone();
320                    workspace.update(cx, |workspace, cx| item.added_to_pane(workspace, pane, cx))
321                }
322            }
323
324            _ => {}
325        }
326    }
327
328    pub fn open_terminal(
329        workspace: &mut Workspace,
330        action: &workspace::OpenTerminal,
331        cx: &mut ViewContext<Workspace>,
332    ) {
333        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
334            return;
335        };
336
337        let terminal_work_dir = workspace
338            .project()
339            .read(cx)
340            .terminal_work_dir_for(Some(&action.working_directory), cx);
341
342        terminal_panel
343            .update(cx, |panel, cx| {
344                panel.add_terminal(terminal_work_dir, None, RevealStrategy::Always, cx)
345            })
346            .detach_and_log_err(cx);
347    }
348
349    fn spawn_task(&mut self, spawn_in_terminal: &SpawnInTerminal, cx: &mut ViewContext<Self>) {
350        let mut spawn_task = spawn_in_terminal.clone();
351        // Set up shell args unconditionally, as tasks are always spawned inside of a shell.
352        let Some((shell, mut user_args)) = (match TerminalSettings::get_global(cx).shell.clone() {
353            Shell::System => std::env::var("SHELL").ok().map(|shell| (shell, Vec::new())),
354            Shell::Program(shell) => Some((shell, Vec::new())),
355            Shell::WithArguments { program, args } => Some((program, args)),
356        }) else {
357            return;
358        };
359
360        spawn_task.command_label = format!("{shell} -i -c `{}`", spawn_task.command_label);
361        let task_command = std::mem::replace(&mut spawn_task.command, shell);
362        let task_args = std::mem::take(&mut spawn_task.args);
363        let combined_command = task_args
364            .into_iter()
365            .fold(task_command, |mut command, arg| {
366                command.push(' ');
367                command.push_str(&arg);
368                command
369            });
370        user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command]);
371        spawn_task.args = user_args;
372        let spawn_task = spawn_task;
373
374        let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
375        let use_new_terminal = spawn_in_terminal.use_new_terminal;
376
377        if allow_concurrent_runs && use_new_terminal {
378            self.spawn_in_new_terminal(spawn_task, cx)
379                .detach_and_log_err(cx);
380            return;
381        }
382
383        let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.full_label, cx);
384        if terminals_for_task.is_empty() {
385            self.spawn_in_new_terminal(spawn_task, cx)
386                .detach_and_log_err(cx);
387            return;
388        }
389        let (existing_item_index, existing_terminal) = terminals_for_task
390            .last()
391            .expect("covered no terminals case above")
392            .clone();
393        if allow_concurrent_runs {
394            debug_assert!(
395                !use_new_terminal,
396                "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
397            );
398            self.replace_terminal(spawn_task, existing_item_index, existing_terminal, cx);
399        } else {
400            self.deferred_tasks.insert(
401                spawn_in_terminal.id.clone(),
402                cx.spawn(|terminal_panel, mut cx| async move {
403                    wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
404                    terminal_panel
405                        .update(&mut cx, |terminal_panel, cx| {
406                            if use_new_terminal {
407                                terminal_panel
408                                    .spawn_in_new_terminal(spawn_task, cx)
409                                    .detach_and_log_err(cx);
410                            } else {
411                                terminal_panel.replace_terminal(
412                                    spawn_task,
413                                    existing_item_index,
414                                    existing_terminal,
415                                    cx,
416                                );
417                            }
418                        })
419                        .ok();
420                }),
421            );
422        }
423    }
424
425    pub fn spawn_in_new_terminal(
426        &mut self,
427        spawn_task: SpawnInTerminal,
428        cx: &mut ViewContext<Self>,
429    ) -> Task<Result<Model<Terminal>>> {
430        let reveal = spawn_task.reveal;
431        self.add_terminal(spawn_task.cwd.clone(), Some(spawn_task), reveal, cx)
432    }
433
434    /// Create a new Terminal in the current working directory or the user's home directory
435    fn new_terminal(
436        workspace: &mut Workspace,
437        _: &workspace::NewTerminal,
438        cx: &mut ViewContext<Workspace>,
439    ) {
440        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
441            return;
442        };
443
444        terminal_panel
445            .update(cx, |this, cx| {
446                this.add_terminal(None, None, RevealStrategy::Always, cx)
447            })
448            .detach_and_log_err(cx);
449    }
450
451    fn terminals_for_task(
452        &self,
453        label: &str,
454        cx: &mut AppContext,
455    ) -> Vec<(usize, View<TerminalView>)> {
456        self.pane
457            .read(cx)
458            .items()
459            .enumerate()
460            .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
461            .filter_map(|(index, terminal_view)| {
462                let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
463                if &task_state.full_label == label {
464                    Some((index, terminal_view))
465                } else {
466                    None
467                }
468            })
469            .collect()
470    }
471
472    fn activate_terminal_view(&self, item_index: usize, cx: &mut WindowContext) {
473        self.pane.update(cx, |pane, cx| {
474            pane.activate_item(item_index, true, true, cx)
475        })
476    }
477
478    fn add_terminal(
479        &mut self,
480        working_directory: Option<TerminalWorkDir>,
481        spawn_task: Option<SpawnInTerminal>,
482        reveal_strategy: RevealStrategy,
483        cx: &mut ViewContext<Self>,
484    ) -> Task<Result<Model<Terminal>>> {
485        if !self.enabled {
486            if spawn_task.is_none()
487                || !matches!(
488                    spawn_task.as_ref().unwrap().cwd,
489                    Some(TerminalWorkDir::Ssh { .. })
490                )
491            {
492                return Task::ready(Err(anyhow::anyhow!(
493                    "terminal not yet supported for remote projects"
494                )));
495            }
496        }
497
498        let workspace = self.workspace.clone();
499        self.pending_terminals_to_add += 1;
500
501        cx.spawn(|terminal_panel, mut cx| async move {
502            let pane = terminal_panel.update(&mut cx, |this, _| this.pane.clone())?;
503            let result = workspace.update(&mut cx, |workspace, cx| {
504                let working_directory = if let Some(working_directory) = working_directory {
505                    Some(working_directory)
506                } else {
507                    let working_directory_strategy =
508                        TerminalSettings::get_global(cx).working_directory.clone();
509                    crate::get_working_directory(workspace, cx, working_directory_strategy)
510                };
511
512                let window = cx.window_handle();
513                let terminal = workspace.project().update(cx, |project, cx| {
514                    project.create_terminal(working_directory, spawn_task, window, cx)
515                })?;
516                let terminal_view = Box::new(cx.new_view(|cx| {
517                    TerminalView::new(
518                        terminal.clone(),
519                        workspace.weak_handle(),
520                        workspace.database_id(),
521                        cx,
522                    )
523                }));
524                pane.update(cx, |pane, cx| {
525                    let focus = pane.has_focus(cx);
526                    pane.add_item(terminal_view, true, focus, None, cx);
527                });
528
529                if reveal_strategy == RevealStrategy::Always {
530                    workspace.focus_panel::<Self>(cx);
531                }
532                Ok(terminal)
533            })?;
534            terminal_panel.update(&mut cx, |this, cx| {
535                this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
536                this.serialize(cx)
537            })?;
538            result
539        })
540    }
541
542    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
543        let mut items_to_serialize = HashSet::default();
544        let items = self
545            .pane
546            .read(cx)
547            .items()
548            .filter_map(|item| {
549                let terminal_view = item.act_as::<TerminalView>(cx)?;
550                if terminal_view.read(cx).terminal().read(cx).task().is_some() {
551                    None
552                } else {
553                    let id = item.item_id().as_u64();
554                    items_to_serialize.insert(id);
555                    Some(id)
556                }
557            })
558            .collect::<Vec<_>>();
559        let active_item_id = self
560            .pane
561            .read(cx)
562            .active_item()
563            .map(|item| item.item_id().as_u64())
564            .filter(|active_id| items_to_serialize.contains(active_id));
565        let height = self.height;
566        let width = self.width;
567        self.pending_serialization = cx.background_executor().spawn(
568            async move {
569                KEY_VALUE_STORE
570                    .write_kvp(
571                        TERMINAL_PANEL_KEY.into(),
572                        serde_json::to_string(&SerializedTerminalPanel {
573                            items,
574                            active_item_id,
575                            height,
576                            width,
577                        })?,
578                    )
579                    .await?;
580                anyhow::Ok(())
581            }
582            .log_err(),
583        );
584    }
585
586    fn replace_terminal(
587        &self,
588        spawn_task: SpawnInTerminal,
589        terminal_item_index: usize,
590        terminal_to_replace: View<TerminalView>,
591        cx: &mut ViewContext<'_, Self>,
592    ) -> Option<()> {
593        let project = self
594            .workspace
595            .update(cx, |workspace, _| workspace.project().clone())
596            .ok()?;
597
598        let reveal = spawn_task.reveal;
599        let window = cx.window_handle();
600        let new_terminal = project.update(cx, |project, cx| {
601            project
602                .create_terminal(spawn_task.cwd.clone(), Some(spawn_task), window, cx)
603                .log_err()
604        })?;
605        terminal_to_replace.update(cx, |terminal_to_replace, cx| {
606            terminal_to_replace.set_terminal(new_terminal, cx);
607        });
608
609        match reveal {
610            RevealStrategy::Always => {
611                self.activate_terminal_view(terminal_item_index, cx);
612                let task_workspace = self.workspace.clone();
613                cx.spawn(|_, mut cx| async move {
614                    task_workspace
615                        .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
616                        .ok()
617                })
618                .detach();
619            }
620            RevealStrategy::Never => {}
621        }
622
623        Some(())
624    }
625
626    pub fn pane(&self) -> &View<Pane> {
627        &self.pane
628    }
629
630    fn has_no_terminals(&self, cx: &WindowContext) -> bool {
631        self.pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
632    }
633}
634
635async fn wait_for_terminals_tasks(
636    terminals_for_task: Vec<(usize, View<TerminalView>)>,
637    cx: &mut AsyncWindowContext,
638) {
639    let pending_tasks = terminals_for_task.iter().filter_map(|(_, terminal)| {
640        terminal
641            .update(cx, |terminal_view, cx| {
642                terminal_view
643                    .terminal()
644                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
645            })
646            .ok()
647    });
648    let _: Vec<()> = join_all(pending_tasks).await;
649}
650
651fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
652    if let Some(terminal_view) = pane
653        .active_item()
654        .and_then(|item| item.downcast::<TerminalView>())
655    {
656        cx.focus_view(&terminal_view);
657        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
658        new_text.push(' ');
659        terminal_view.update(cx, |terminal_view, cx| {
660            terminal_view.terminal().update(cx, |terminal, _| {
661                terminal.paste(&new_text);
662            });
663        });
664    }
665}
666
667impl EventEmitter<PanelEvent> for TerminalPanel {}
668
669impl Render for TerminalPanel {
670    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
671        let mut registrar = DivRegistrar::new(
672            |panel, cx| {
673                panel
674                    .pane
675                    .read(cx)
676                    .toolbar()
677                    .read(cx)
678                    .item_of_type::<BufferSearchBar>()
679            },
680            cx,
681        );
682        BufferSearchBar::register(&mut registrar);
683        registrar.into_div().size_full().child(self.pane.clone())
684    }
685}
686
687impl FocusableView for TerminalPanel {
688    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
689        self.pane.focus_handle(cx)
690    }
691}
692
693impl Panel for TerminalPanel {
694    fn position(&self, cx: &WindowContext) -> DockPosition {
695        match TerminalSettings::get_global(cx).dock {
696            TerminalDockPosition::Left => DockPosition::Left,
697            TerminalDockPosition::Bottom => DockPosition::Bottom,
698            TerminalDockPosition::Right => DockPosition::Right,
699        }
700    }
701
702    fn position_is_valid(&self, _: DockPosition) -> bool {
703        true
704    }
705
706    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
707        settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
708            let dock = match position {
709                DockPosition::Left => TerminalDockPosition::Left,
710                DockPosition::Bottom => TerminalDockPosition::Bottom,
711                DockPosition::Right => TerminalDockPosition::Right,
712            };
713            settings.dock = Some(dock);
714        });
715    }
716
717    fn size(&self, cx: &WindowContext) -> Pixels {
718        let settings = TerminalSettings::get_global(cx);
719        match self.position(cx) {
720            DockPosition::Left | DockPosition::Right => {
721                self.width.unwrap_or_else(|| settings.default_width)
722            }
723            DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
724        }
725    }
726
727    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
728        match self.position(cx) {
729            DockPosition::Left | DockPosition::Right => self.width = size,
730            DockPosition::Bottom => self.height = size,
731        }
732        self.serialize(cx);
733        cx.notify();
734    }
735
736    fn is_zoomed(&self, cx: &WindowContext) -> bool {
737        self.pane.read(cx).is_zoomed()
738    }
739
740    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
741        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
742    }
743
744    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
745        if active && self.has_no_terminals(cx) {
746            self.add_terminal(None, None, RevealStrategy::Never, cx)
747                .detach_and_log_err(cx)
748        }
749    }
750
751    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
752        let count = self.pane.read(cx).items_len();
753        if count == 0 {
754            None
755        } else {
756            Some(count.to_string())
757        }
758    }
759
760    fn persistent_name() -> &'static str {
761        "TerminalPanel"
762    }
763
764    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
765        if (self.enabled || !self.has_no_terminals(cx)) && TerminalSettings::get_global(cx).button {
766            Some(IconName::Terminal)
767        } else {
768            None
769        }
770    }
771
772    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
773        Some("Terminal Panel")
774    }
775
776    fn toggle_action(&self) -> Box<dyn gpui::Action> {
777        Box::new(ToggleFocus)
778    }
779}
780
781#[derive(Serialize, Deserialize)]
782struct SerializedTerminalPanel {
783    items: Vec<u64>,
784    active_item_id: Option<u64>,
785    width: Option<Pixels>,
786    height: Option<Pixels>,
787}