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