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
321        terminal_panel.update(cx, |panel, cx| {
322            panel.add_terminal(
323                Some(action.working_directory.clone()),
324                None,
325                RevealStrategy::Always,
326                cx,
327            )
328        });
329    }
330
331    fn spawn_task(&mut self, spawn_in_terminal: &SpawnInTerminal, cx: &mut ViewContext<Self>) {
332        let mut spawn_task = spawn_in_terminal.clone();
333        // Set up shell args unconditionally, as tasks are always spawned inside of a shell.
334        let Some((shell, mut user_args)) = (match TerminalSettings::get_global(cx).shell.clone() {
335            Shell::System => std::env::var("SHELL").ok().map(|shell| (shell, Vec::new())),
336            Shell::Program(shell) => Some((shell, Vec::new())),
337            Shell::WithArguments { program, args } => Some((program, args)),
338        }) else {
339            return;
340        };
341
342        spawn_task.command_label = format!("{shell} -i -c `{}`", spawn_task.command_label);
343        let task_command = std::mem::replace(&mut spawn_task.command, shell);
344        let task_args = std::mem::take(&mut spawn_task.args);
345        let combined_command = task_args
346            .into_iter()
347            .fold(task_command, |mut command, arg| {
348                command.push(' ');
349                command.push_str(&arg);
350                command
351            });
352        user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command]);
353        spawn_task.args = user_args;
354        let spawn_task = spawn_task;
355
356        let reveal = spawn_task.reveal;
357        let working_directory = spawn_in_terminal.cwd.clone();
358        let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
359        let use_new_terminal = spawn_in_terminal.use_new_terminal;
360
361        if allow_concurrent_runs && use_new_terminal {
362            self.spawn_in_new_terminal(spawn_task, working_directory, cx);
363            return;
364        }
365
366        let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.full_label, cx);
367        if terminals_for_task.is_empty() {
368            self.spawn_in_new_terminal(spawn_task, working_directory, cx);
369            return;
370        }
371        let (existing_item_index, existing_terminal) = terminals_for_task
372            .last()
373            .expect("covered no terminals case above")
374            .clone();
375        if allow_concurrent_runs {
376            debug_assert!(
377                !use_new_terminal,
378                "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
379            );
380            self.replace_terminal(
381                working_directory,
382                spawn_task,
383                existing_item_index,
384                existing_terminal,
385                cx,
386            );
387        } else {
388            self.deferred_tasks.insert(
389                spawn_in_terminal.id.clone(),
390                cx.spawn(|terminal_panel, mut cx| async move {
391                    wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
392                    terminal_panel
393                        .update(&mut cx, |terminal_panel, cx| {
394                            if use_new_terminal {
395                                terminal_panel.spawn_in_new_terminal(
396                                    spawn_task,
397                                    working_directory,
398                                    cx,
399                                );
400                            } else {
401                                terminal_panel.replace_terminal(
402                                    working_directory,
403                                    spawn_task,
404                                    existing_item_index,
405                                    existing_terminal,
406                                    cx,
407                                );
408                            }
409                        })
410                        .ok();
411                }),
412            );
413
414            match reveal {
415                RevealStrategy::Always => {
416                    self.activate_terminal_view(existing_item_index, cx);
417                    let task_workspace = self.workspace.clone();
418                    cx.spawn(|_, mut cx| async move {
419                        task_workspace
420                            .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
421                            .ok()
422                    })
423                    .detach();
424                }
425                RevealStrategy::Never => {}
426            }
427        }
428    }
429
430    fn spawn_in_new_terminal(
431        &mut self,
432        spawn_task: SpawnInTerminal,
433        working_directory: Option<PathBuf>,
434        cx: &mut ViewContext<Self>,
435    ) {
436        let reveal = spawn_task.reveal;
437        self.add_terminal(working_directory, Some(spawn_task), reveal, cx);
438    }
439
440    /// Create a new Terminal in the current working directory or the user's home directory
441    fn new_terminal(
442        workspace: &mut Workspace,
443        _: &workspace::NewTerminal,
444        cx: &mut ViewContext<Workspace>,
445    ) {
446        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
447            return;
448        };
449
450        terminal_panel.update(cx, |this, cx| {
451            this.add_terminal(None, None, RevealStrategy::Always, cx)
452        });
453    }
454
455    fn terminals_for_task(
456        &self,
457        label: &str,
458        cx: &mut AppContext,
459    ) -> Vec<(usize, View<TerminalView>)> {
460        self.pane
461            .read(cx)
462            .items()
463            .enumerate()
464            .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
465            .filter_map(|(index, terminal_view)| {
466                let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
467                if &task_state.full_label == label {
468                    Some((index, terminal_view))
469                } else {
470                    None
471                }
472            })
473            .collect()
474    }
475
476    fn activate_terminal_view(&self, item_index: usize, cx: &mut WindowContext) {
477        self.pane.update(cx, |pane, cx| {
478            pane.activate_item(item_index, true, true, cx)
479        })
480    }
481
482    fn add_terminal(
483        &mut self,
484        working_directory: Option<PathBuf>,
485        spawn_task: Option<SpawnInTerminal>,
486        reveal_strategy: RevealStrategy,
487        cx: &mut ViewContext<Self>,
488    ) {
489        let workspace = self.workspace.clone();
490        self.pending_terminals_to_add += 1;
491
492        cx.spawn(|terminal_panel, mut cx| async move {
493            let pane = terminal_panel.update(&mut cx, |this, _| this.pane.clone())?;
494            workspace.update(&mut cx, |workspace, cx| {
495                if workspace.project().read(cx).is_remote() {
496                    workspace.show_error(
497                        &anyhow::anyhow!("Cannot open terminals on remote projects (yet!)"),
498                        cx,
499                    );
500                    return;
501                };
502
503                let working_directory = if let Some(working_directory) = working_directory {
504                    Some(working_directory)
505                } else {
506                    let working_directory_strategy =
507                        TerminalSettings::get_global(cx).working_directory.clone();
508                    crate::get_working_directory(workspace, cx, working_directory_strategy)
509                };
510
511                let window = cx.window_handle();
512                if let Some(terminal) = workspace.project().update(cx, |project, cx| {
513                    project
514                        .create_terminal(working_directory, spawn_task, window, cx)
515                        .log_err()
516                }) {
517                    let terminal = Box::new(cx.new_view(|cx| {
518                        TerminalView::new(
519                            terminal,
520                            workspace.weak_handle(),
521                            workspace.database_id(),
522                            cx,
523                        )
524                    }));
525                    pane.update(cx, |pane, cx| {
526                        let focus = pane.has_focus(cx);
527                        pane.add_item(terminal, true, focus, None, cx);
528                    });
529                }
530                if reveal_strategy == RevealStrategy::Always {
531                    workspace.focus_panel::<Self>(cx);
532                }
533            })?;
534            terminal_panel.update(&mut cx, |this, cx| {
535                this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
536                this.serialize(cx)
537            })?;
538            anyhow::Ok(())
539        })
540        .detach_and_log_err(cx);
541    }
542
543    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
544        let mut items_to_serialize = HashSet::default();
545        let items = self
546            .pane
547            .read(cx)
548            .items()
549            .filter_map(|item| {
550                let terminal_view = item.act_as::<TerminalView>(cx)?;
551                if terminal_view.read(cx).terminal().read(cx).task().is_some() {
552                    None
553                } else {
554                    let id = item.item_id().as_u64();
555                    items_to_serialize.insert(id);
556                    Some(id)
557                }
558            })
559            .collect::<Vec<_>>();
560        let active_item_id = self
561            .pane
562            .read(cx)
563            .active_item()
564            .map(|item| item.item_id().as_u64())
565            .filter(|active_id| items_to_serialize.contains(active_id));
566        let height = self.height;
567        let width = self.width;
568        self.pending_serialization = cx.background_executor().spawn(
569            async move {
570                KEY_VALUE_STORE
571                    .write_kvp(
572                        TERMINAL_PANEL_KEY.into(),
573                        serde_json::to_string(&SerializedTerminalPanel {
574                            items,
575                            active_item_id,
576                            height,
577                            width,
578                        })?,
579                    )
580                    .await?;
581                anyhow::Ok(())
582            }
583            .log_err(),
584        );
585    }
586
587    fn replace_terminal(
588        &self,
589        working_directory: Option<PathBuf>,
590        spawn_task: SpawnInTerminal,
591        terminal_item_index: usize,
592        terminal_to_replace: View<TerminalView>,
593        cx: &mut ViewContext<'_, Self>,
594    ) -> Option<()> {
595        let project = self
596            .workspace
597            .update(cx, |workspace, _| workspace.project().clone())
598            .ok()?;
599
600        let reveal = spawn_task.reveal;
601        let window = cx.window_handle();
602        let new_terminal = project.update(cx, |project, cx| {
603            project
604                .create_terminal(working_directory, Some(spawn_task), window, cx)
605                .log_err()
606        })?;
607        terminal_to_replace.update(cx, |terminal_to_replace, cx| {
608            terminal_to_replace.set_terminal(new_terminal, cx);
609        });
610
611        match reveal {
612            RevealStrategy::Always => {
613                self.activate_terminal_view(terminal_item_index, cx);
614                let task_workspace = self.workspace.clone();
615                cx.spawn(|_, mut cx| async move {
616                    task_workspace
617                        .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
618                        .ok()
619                })
620                .detach();
621            }
622            RevealStrategy::Never => {}
623        }
624
625        Some(())
626    }
627
628    pub fn pane(&self) -> &View<Pane> {
629        &self.pane
630    }
631
632    fn has_no_terminals(&mut self, cx: &mut ViewContext<'_, Self>) -> bool {
633        self.pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
634    }
635}
636
637async fn wait_for_terminals_tasks(
638    terminals_for_task: Vec<(usize, View<TerminalView>)>,
639    cx: &mut AsyncWindowContext,
640) {
641    let pending_tasks = terminals_for_task.iter().filter_map(|(_, terminal)| {
642        terminal
643            .update(cx, |terminal_view, cx| {
644                terminal_view
645                    .terminal()
646                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
647            })
648            .ok()
649    });
650    let _: Vec<()> = join_all(pending_tasks).await;
651}
652
653fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
654    if let Some(terminal_view) = pane
655        .active_item()
656        .and_then(|item| item.downcast::<TerminalView>())
657    {
658        cx.focus_view(&terminal_view);
659        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
660        new_text.push(' ');
661        terminal_view.update(cx, |terminal_view, cx| {
662            terminal_view.terminal().update(cx, |terminal, _| {
663                terminal.paste(&new_text);
664            });
665        });
666    }
667}
668
669impl EventEmitter<PanelEvent> for TerminalPanel {}
670
671impl Render for TerminalPanel {
672    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
673        let mut registrar = DivRegistrar::new(
674            |panel, cx| {
675                panel
676                    .pane
677                    .read(cx)
678                    .toolbar()
679                    .read(cx)
680                    .item_of_type::<BufferSearchBar>()
681            },
682            cx,
683        );
684        BufferSearchBar::register(&mut registrar);
685        registrar.into_div().size_full().child(self.pane.clone())
686    }
687}
688
689impl FocusableView for TerminalPanel {
690    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
691        self.pane.focus_handle(cx)
692    }
693}
694
695impl Panel for TerminalPanel {
696    fn position(&self, cx: &WindowContext) -> DockPosition {
697        match TerminalSettings::get_global(cx).dock {
698            TerminalDockPosition::Left => DockPosition::Left,
699            TerminalDockPosition::Bottom => DockPosition::Bottom,
700            TerminalDockPosition::Right => DockPosition::Right,
701        }
702    }
703
704    fn position_is_valid(&self, _: DockPosition) -> bool {
705        true
706    }
707
708    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
709        settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
710            let dock = match position {
711                DockPosition::Left => TerminalDockPosition::Left,
712                DockPosition::Bottom => TerminalDockPosition::Bottom,
713                DockPosition::Right => TerminalDockPosition::Right,
714            };
715            settings.dock = Some(dock);
716        });
717    }
718
719    fn size(&self, cx: &WindowContext) -> Pixels {
720        let settings = TerminalSettings::get_global(cx);
721        match self.position(cx) {
722            DockPosition::Left | DockPosition::Right => {
723                self.width.unwrap_or_else(|| settings.default_width)
724            }
725            DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
726        }
727    }
728
729    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
730        match self.position(cx) {
731            DockPosition::Left | DockPosition::Right => self.width = size,
732            DockPosition::Bottom => self.height = size,
733        }
734        self.serialize(cx);
735        cx.notify();
736    }
737
738    fn is_zoomed(&self, cx: &WindowContext) -> bool {
739        self.pane.read(cx).is_zoomed()
740    }
741
742    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
743        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
744    }
745
746    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
747        if active && self.has_no_terminals(cx) {
748            self.add_terminal(None, None, RevealStrategy::Never, cx);
749        }
750    }
751
752    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
753        let count = self.pane.read(cx).items_len();
754        if count == 0 {
755            None
756        } else {
757            Some(count.to_string())
758        }
759    }
760
761    fn persistent_name() -> &'static str {
762        "TerminalPanel"
763    }
764
765    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
766        TerminalSettings::get_global(cx)
767            .button
768            .then(|| IconName::Terminal)
769    }
770
771    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
772        Some("Terminal Panel")
773    }
774
775    fn toggle_action(&self) -> Box<dyn gpui::Action> {
776        Box::new(ToggleFocus)
777    }
778}
779
780#[derive(Serialize, Deserialize)]
781struct SerializedTerminalPanel {
782    items: Vec<u64>,
783    active_item_id: Option<u64>,
784    width: Option<Pixels>,
785    height: Option<Pixels>,
786}