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