terminal_panel.rs

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