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