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