terminal_panel.rs

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