terminal_panel.rs

   1use std::{cmp, ops::ControlFlow, path::PathBuf, sync::Arc, time::Duration};
   2
   3use crate::{
   4    default_working_directory,
   5    persistence::{
   6        deserialize_terminal_panel, serialize_pane_group, SerializedItems, SerializedTerminalPanel,
   7    },
   8    TerminalView,
   9};
  10use breadcrumbs::Breadcrumbs;
  11use collections::HashMap;
  12use db::kvp::KEY_VALUE_STORE;
  13use futures::future::join_all;
  14use gpui::{
  15    actions, Action, AnyView, AppContext, AsyncWindowContext, Corner, Entity, EventEmitter,
  16    ExternalPaths, FocusHandle, FocusableView, IntoElement, Model, ParentElement, Pixels, Render,
  17    Styled, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
  18};
  19use itertools::Itertools;
  20use project::{terminals::TerminalKind, Fs, Project, ProjectEntryId};
  21use search::{buffer_search::DivRegistrar, BufferSearchBar};
  22use settings::Settings;
  23use task::{RevealStrategy, RevealTarget, Shell, SpawnInTerminal, TaskId};
  24use terminal::{
  25    terminal_settings::{TerminalDockPosition, TerminalSettings},
  26    Terminal,
  27};
  28use ui::{
  29    prelude::*, ButtonCommon, Clickable, ContextMenu, FluentBuilder, PopoverMenu, Toggleable,
  30    Tooltip,
  31};
  32use util::{ResultExt, TryFutureExt};
  33use workspace::{
  34    dock::{DockPosition, Panel, PanelEvent},
  35    item::SerializableItem,
  36    move_active_item, move_item, pane,
  37    ui::IconName,
  38    ActivateNextPane, ActivatePane, ActivatePaneInDirection, ActivatePreviousPane, DraggedTab,
  39    ItemId, MoveItemToPane, MoveItemToPaneInDirection, NewTerminal, Pane, PaneGroup,
  40    SplitDirection, SplitDown, SplitLeft, SplitRight, SplitUp, SwapPaneInDirection, ToggleZoom,
  41    Workspace,
  42};
  43
  44use anyhow::{anyhow, Context, Result};
  45use zed_actions::InlineAssist;
  46
  47const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
  48
  49actions!(terminal_panel, [ToggleFocus]);
  50
  51pub fn init(cx: &mut AppContext) {
  52    cx.observe_new_views(
  53        |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
  54            workspace.register_action(TerminalPanel::new_terminal);
  55            workspace.register_action(TerminalPanel::open_terminal);
  56            workspace.register_action(|workspace, _: &ToggleFocus, cx| {
  57                if is_enabled_in_workspace(workspace, cx) {
  58                    workspace.toggle_panel_focus::<TerminalPanel>(cx);
  59                }
  60            });
  61        },
  62    )
  63    .detach();
  64}
  65
  66pub struct TerminalPanel {
  67    pub(crate) active_pane: View<Pane>,
  68    pub(crate) center: PaneGroup,
  69    fs: Arc<dyn Fs>,
  70    workspace: WeakView<Workspace>,
  71    pub(crate) width: Option<Pixels>,
  72    pub(crate) height: Option<Pixels>,
  73    pending_serialization: Task<Option<()>>,
  74    pending_terminals_to_add: usize,
  75    deferred_tasks: HashMap<TaskId, Task<()>>,
  76    assistant_enabled: bool,
  77    assistant_tab_bar_button: Option<AnyView>,
  78}
  79
  80impl TerminalPanel {
  81    pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
  82        let project = workspace.project();
  83        let pane = new_terminal_pane(workspace.weak_handle(), project.clone(), false, cx);
  84        let center = PaneGroup::new(pane.clone());
  85        cx.focus_view(&pane);
  86        let terminal_panel = Self {
  87            center,
  88            active_pane: pane,
  89            fs: workspace.app_state().fs.clone(),
  90            workspace: workspace.weak_handle(),
  91            pending_serialization: Task::ready(None),
  92            width: None,
  93            height: None,
  94            pending_terminals_to_add: 0,
  95            deferred_tasks: HashMap::default(),
  96            assistant_enabled: false,
  97            assistant_tab_bar_button: None,
  98        };
  99        terminal_panel.apply_tab_bar_buttons(&terminal_panel.active_pane, cx);
 100        terminal_panel
 101    }
 102
 103    pub fn asssistant_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
 104        self.assistant_enabled = enabled;
 105        if enabled {
 106            let focus_handle = self
 107                .active_pane
 108                .read(cx)
 109                .active_item()
 110                .map(|item| item.focus_handle(cx))
 111                .unwrap_or(self.focus_handle(cx));
 112            self.assistant_tab_bar_button = Some(
 113                cx.new_view(move |_| InlineAssistTabBarButton { focus_handle })
 114                    .into(),
 115            );
 116        } else {
 117            self.assistant_tab_bar_button = None;
 118        }
 119        for pane in self.center.panes() {
 120            self.apply_tab_bar_buttons(pane, cx);
 121        }
 122    }
 123
 124    fn apply_tab_bar_buttons(&self, terminal_pane: &View<Pane>, cx: &mut ViewContext<Self>) {
 125        let assistant_tab_bar_button = self.assistant_tab_bar_button.clone();
 126        terminal_pane.update(cx, |pane, cx| {
 127            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 128                let split_context = pane
 129                    .active_item()
 130                    .and_then(|item| item.downcast::<TerminalView>())
 131                    .map(|terminal_view| terminal_view.read(cx).focus_handle.clone());
 132                if !pane.has_focus(cx) && !pane.context_menu_focused(cx) {
 133                    return (None, None);
 134                }
 135                let focus_handle = pane.focus_handle(cx);
 136                let right_children = h_flex()
 137                    .gap(DynamicSpacing::Base02.rems(cx))
 138                    .child(
 139                        PopoverMenu::new("terminal-tab-bar-popover-menu")
 140                            .trigger(
 141                                IconButton::new("plus", IconName::Plus)
 142                                    .icon_size(IconSize::Small)
 143                                    .tooltip(|cx| Tooltip::text("New…", cx)),
 144                            )
 145                            .anchor(Corner::TopRight)
 146                            .with_handle(pane.new_item_context_menu_handle.clone())
 147                            .menu(move |cx| {
 148                                let focus_handle = focus_handle.clone();
 149                                let menu = ContextMenu::build(cx, |menu, _| {
 150                                    menu.context(focus_handle.clone())
 151                                        .action(
 152                                            "New Terminal",
 153                                            workspace::NewTerminal.boxed_clone(),
 154                                        )
 155                                        // We want the focus to go back to terminal panel once task modal is dismissed,
 156                                        // hence we focus that first. Otherwise, we'd end up without a focused element, as
 157                                        // context menu will be gone the moment we spawn the modal.
 158                                        .action(
 159                                            "Spawn task",
 160                                            zed_actions::Spawn::modal().boxed_clone(),
 161                                        )
 162                                });
 163
 164                                Some(menu)
 165                            }),
 166                    )
 167                    .children(assistant_tab_bar_button.clone())
 168                    .child(
 169                        PopoverMenu::new("terminal-pane-tab-bar-split")
 170                            .trigger(
 171                                IconButton::new("terminal-pane-split", IconName::Split)
 172                                    .icon_size(IconSize::Small)
 173                                    .tooltip(|cx| Tooltip::text("Split Pane", cx)),
 174                            )
 175                            .anchor(Corner::TopRight)
 176                            .with_handle(pane.split_item_context_menu_handle.clone())
 177                            .menu({
 178                                let split_context = split_context.clone();
 179                                move |cx| {
 180                                    ContextMenu::build(cx, |menu, _| {
 181                                        menu.when_some(
 182                                            split_context.clone(),
 183                                            |menu, split_context| menu.context(split_context),
 184                                        )
 185                                        .action("Split Right", SplitRight.boxed_clone())
 186                                        .action("Split Left", SplitLeft.boxed_clone())
 187                                        .action("Split Up", SplitUp.boxed_clone())
 188                                        .action("Split Down", SplitDown.boxed_clone())
 189                                    })
 190                                    .into()
 191                                }
 192                            }),
 193                    )
 194                    .child({
 195                        let zoomed = pane.is_zoomed();
 196                        IconButton::new("toggle_zoom", IconName::Maximize)
 197                            .icon_size(IconSize::Small)
 198                            .toggle_state(zoomed)
 199                            .selected_icon(IconName::Minimize)
 200                            .on_click(cx.listener(|pane, _, cx| {
 201                                pane.toggle_zoom(&workspace::ToggleZoom, cx);
 202                            }))
 203                            .tooltip(move |cx| {
 204                                Tooltip::for_action(
 205                                    if zoomed { "Zoom Out" } else { "Zoom In" },
 206                                    &ToggleZoom,
 207                                    cx,
 208                                )
 209                            })
 210                    })
 211                    .into_any_element()
 212                    .into();
 213                (None, right_children)
 214            });
 215        });
 216    }
 217
 218    pub async fn load(
 219        workspace: WeakView<Workspace>,
 220        mut cx: AsyncWindowContext,
 221    ) -> Result<View<Self>> {
 222        let serialized_panel = cx
 223            .background_executor()
 224            .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
 225            .await
 226            .log_err()
 227            .flatten()
 228            .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
 229            .transpose()
 230            .log_err()
 231            .flatten();
 232
 233        let terminal_panel = workspace
 234            .update(&mut cx, |workspace, cx| {
 235                match serialized_panel.zip(workspace.database_id()) {
 236                    Some((serialized_panel, database_id)) => deserialize_terminal_panel(
 237                        workspace.weak_handle(),
 238                        workspace.project().clone(),
 239                        database_id,
 240                        serialized_panel,
 241                        cx,
 242                    ),
 243                    None => Task::ready(Ok(cx.new_view(|cx| TerminalPanel::new(workspace, cx)))),
 244                }
 245            })?
 246            .await?;
 247
 248        if let Some(workspace) = workspace.upgrade() {
 249            terminal_panel
 250                .update(&mut cx, |_, cx| {
 251                    cx.subscribe(&workspace, |terminal_panel, _, e, cx| {
 252                        if let workspace::Event::SpawnTask {
 253                            action: spawn_in_terminal,
 254                        } = e
 255                        {
 256                            terminal_panel.spawn_task(spawn_in_terminal, cx);
 257                        };
 258                    })
 259                    .detach();
 260                })
 261                .ok();
 262        }
 263
 264        // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
 265        if let Some(workspace) = workspace.upgrade() {
 266            let cleanup_task = workspace.update(&mut cx, |workspace, cx| {
 267                let alive_item_ids = terminal_panel
 268                    .read(cx)
 269                    .center
 270                    .panes()
 271                    .into_iter()
 272                    .flat_map(|pane| pane.read(cx).items())
 273                    .map(|item| item.item_id().as_u64() as ItemId)
 274                    .collect();
 275                workspace
 276                    .database_id()
 277                    .map(|workspace_id| TerminalView::cleanup(workspace_id, alive_item_ids, cx))
 278            })?;
 279            if let Some(task) = cleanup_task {
 280                task.await.log_err();
 281            }
 282        }
 283
 284        Ok(terminal_panel)
 285    }
 286
 287    fn handle_pane_event(
 288        &mut self,
 289        pane: View<Pane>,
 290        event: &pane::Event,
 291        cx: &mut ViewContext<Self>,
 292    ) {
 293        match event {
 294            pane::Event::ActivateItem { .. } => self.serialize(cx),
 295            pane::Event::RemovedItem { .. } => self.serialize(cx),
 296            pane::Event::Remove { focus_on_pane } => {
 297                let pane_count_before_removal = self.center.panes().len();
 298                let _removal_result = self.center.remove(&pane);
 299                if pane_count_before_removal == 1 {
 300                    self.center.first_pane().update(cx, |pane, cx| {
 301                        pane.set_zoomed(false, cx);
 302                    });
 303                    cx.emit(PanelEvent::Close);
 304                } else {
 305                    if let Some(focus_on_pane) =
 306                        focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
 307                    {
 308                        focus_on_pane.focus_handle(cx).focus(cx);
 309                    }
 310                }
 311            }
 312            pane::Event::ZoomIn => {
 313                for pane in self.center.panes() {
 314                    pane.update(cx, |pane, cx| {
 315                        pane.set_zoomed(true, cx);
 316                    })
 317                }
 318                cx.emit(PanelEvent::ZoomIn);
 319                cx.notify();
 320            }
 321            pane::Event::ZoomOut => {
 322                for pane in self.center.panes() {
 323                    pane.update(cx, |pane, cx| {
 324                        pane.set_zoomed(false, cx);
 325                    })
 326                }
 327                cx.emit(PanelEvent::ZoomOut);
 328                cx.notify();
 329            }
 330            pane::Event::AddItem { item } => {
 331                if let Some(workspace) = self.workspace.upgrade() {
 332                    workspace.update(cx, |workspace, cx| {
 333                        item.added_to_pane(workspace, pane.clone(), cx)
 334                    })
 335                }
 336                self.serialize(cx);
 337            }
 338            pane::Event::Split(direction) => {
 339                let Some(new_pane) = self.new_pane_with_cloned_active_terminal(cx) else {
 340                    return;
 341                };
 342                let pane = pane.clone();
 343                let direction = *direction;
 344                self.center.split(&pane, &new_pane, direction).log_err();
 345                cx.focus_view(&new_pane);
 346            }
 347            pane::Event::Focus => {
 348                self.active_pane = pane.clone();
 349            }
 350
 351            _ => {}
 352        }
 353    }
 354
 355    fn new_pane_with_cloned_active_terminal(
 356        &mut self,
 357        cx: &mut ViewContext<Self>,
 358    ) -> Option<View<Pane>> {
 359        let workspace = self.workspace.upgrade()?;
 360        let workspace = workspace.read(cx);
 361        let database_id = workspace.database_id();
 362        let weak_workspace = self.workspace.clone();
 363        let project = workspace.project().clone();
 364        let (working_directory, python_venv_directory) = self
 365            .active_pane
 366            .read(cx)
 367            .active_item()
 368            .and_then(|item| item.downcast::<TerminalView>())
 369            .map(|terminal_view| {
 370                let terminal = terminal_view.read(cx).terminal().read(cx);
 371                (
 372                    terminal
 373                        .working_directory()
 374                        .or_else(|| default_working_directory(workspace, cx)),
 375                    terminal.python_venv_directory.clone(),
 376                )
 377            })
 378            .unwrap_or((None, None));
 379        let kind = TerminalKind::Shell(working_directory);
 380        let window = cx.window_handle();
 381        let terminal = project
 382            .update(cx, |project, cx| {
 383                project.create_terminal_with_venv(kind, python_venv_directory, window, cx)
 384            })
 385            .ok()?;
 386
 387        let terminal_view = Box::new(cx.new_view(|cx| {
 388            TerminalView::new(
 389                terminal.clone(),
 390                weak_workspace.clone(),
 391                database_id,
 392                project.downgrade(),
 393                cx,
 394            )
 395        }));
 396        let pane = new_terminal_pane(
 397            weak_workspace,
 398            project,
 399            self.active_pane.read(cx).is_zoomed(),
 400            cx,
 401        );
 402        self.apply_tab_bar_buttons(&pane, cx);
 403        pane.update(cx, |pane, cx| {
 404            pane.add_item(terminal_view, true, true, None, cx);
 405        });
 406
 407        Some(pane)
 408    }
 409
 410    pub fn open_terminal(
 411        workspace: &mut Workspace,
 412        action: &workspace::OpenTerminal,
 413        cx: &mut ViewContext<Workspace>,
 414    ) {
 415        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 416            return;
 417        };
 418
 419        terminal_panel
 420            .update(cx, |panel, cx| {
 421                panel.add_terminal(
 422                    TerminalKind::Shell(Some(action.working_directory.clone())),
 423                    RevealStrategy::Always,
 424                    cx,
 425                )
 426            })
 427            .detach_and_log_err(cx);
 428    }
 429
 430    fn spawn_task(&mut self, spawn_in_terminal: &SpawnInTerminal, cx: &mut ViewContext<Self>) {
 431        let mut spawn_task = spawn_in_terminal.clone();
 432        let Ok(is_local) = self
 433            .workspace
 434            .update(cx, |workspace, cx| workspace.project().read(cx).is_local())
 435        else {
 436            return;
 437        };
 438        if let ControlFlow::Break(_) =
 439            Self::fill_command(is_local, spawn_in_terminal, &mut spawn_task)
 440        {
 441            return;
 442        }
 443        let spawn_task = spawn_task;
 444
 445        let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
 446        let use_new_terminal = spawn_in_terminal.use_new_terminal;
 447
 448        if allow_concurrent_runs && use_new_terminal {
 449            self.spawn_in_new_terminal(spawn_task, cx)
 450                .detach_and_log_err(cx);
 451            return;
 452        }
 453
 454        let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.full_label, cx);
 455        if terminals_for_task.is_empty() {
 456            self.spawn_in_new_terminal(spawn_task, cx)
 457                .detach_and_log_err(cx);
 458            return;
 459        }
 460        let (existing_item_index, task_pane, existing_terminal) = terminals_for_task
 461            .last()
 462            .expect("covered no terminals case above")
 463            .clone();
 464        let id = spawn_in_terminal.id.clone();
 465        cx.spawn(move |this, mut cx| async move {
 466            if allow_concurrent_runs {
 467                debug_assert!(
 468                    !use_new_terminal,
 469                    "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
 470                );
 471                this.update(&mut cx, |terminal_panel, cx| {
 472                    terminal_panel.replace_terminal(
 473                        spawn_task,
 474                        task_pane,
 475                        existing_item_index,
 476                        existing_terminal,
 477                        cx,
 478                    )
 479                })?
 480                .await;
 481            } else {
 482                this.update(&mut cx, |this, cx| {
 483                    this.deferred_tasks.insert(
 484                        id,
 485                        cx.spawn(|terminal_panel, mut cx| async move {
 486                            wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
 487                            let Ok(Some(new_terminal_task)) =
 488                                terminal_panel.update(&mut cx, |terminal_panel, cx| {
 489                                    if use_new_terminal {
 490                                        terminal_panel
 491                                            .spawn_in_new_terminal(spawn_task, cx)
 492                                            .detach_and_log_err(cx);
 493                                        None
 494                                    } else {
 495                                        Some(terminal_panel.replace_terminal(
 496                                            spawn_task,
 497                                            task_pane,
 498                                            existing_item_index,
 499                                            existing_terminal,
 500                                            cx,
 501                                        ))
 502                                    }
 503                                })
 504                            else {
 505                                return;
 506                            };
 507                            new_terminal_task.await;
 508                        }),
 509                    );
 510                })
 511                .ok();
 512            }
 513            anyhow::Result::<_, anyhow::Error>::Ok(())
 514        })
 515        .detach()
 516    }
 517
 518    pub fn fill_command(
 519        is_local: bool,
 520        spawn_in_terminal: &SpawnInTerminal,
 521        spawn_task: &mut SpawnInTerminal,
 522    ) -> ControlFlow<()> {
 523        let Some((shell, mut user_args)) = (match spawn_in_terminal.shell.clone() {
 524            Shell::System => {
 525                if is_local {
 526                    retrieve_system_shell().map(|shell| (shell, Vec::new()))
 527                } else {
 528                    Some(("\"${SHELL:-sh}\"".to_string(), Vec::new()))
 529                }
 530            }
 531            Shell::Program(shell) => Some((shell, Vec::new())),
 532            Shell::WithArguments { program, args, .. } => Some((program, args)),
 533        }) else {
 534            return ControlFlow::Break(());
 535        };
 536        #[cfg(target_os = "windows")]
 537        let windows_shell_type = to_windows_shell_type(&shell);
 538        #[cfg(not(target_os = "windows"))]
 539        {
 540            spawn_task.command_label = format!("{shell} -i -c '{}'", spawn_task.command_label);
 541        }
 542        #[cfg(target_os = "windows")]
 543        {
 544            use crate::terminal_panel::WindowsShellType;
 545
 546            match windows_shell_type {
 547                WindowsShellType::Powershell => {
 548                    spawn_task.command_label = format!("{shell} -C '{}'", spawn_task.command_label)
 549                }
 550                WindowsShellType::Cmd => {
 551                    spawn_task.command_label = format!("{shell} /C '{}'", spawn_task.command_label)
 552                }
 553                WindowsShellType::Other => {
 554                    spawn_task.command_label =
 555                        format!("{shell} -i -c '{}'", spawn_task.command_label)
 556                }
 557            }
 558        }
 559        let task_command = std::mem::replace(&mut spawn_task.command, shell);
 560        let task_args = std::mem::take(&mut spawn_task.args);
 561        let combined_command = task_args
 562            .into_iter()
 563            .fold(task_command, |mut command, arg| {
 564                command.push(' ');
 565                #[cfg(not(target_os = "windows"))]
 566                command.push_str(&arg);
 567                #[cfg(target_os = "windows")]
 568                command.push_str(&to_windows_shell_variable(windows_shell_type, arg));
 569                command
 570            });
 571        #[cfg(not(target_os = "windows"))]
 572        user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command]);
 573        #[cfg(target_os = "windows")]
 574        {
 575            use crate::terminal_panel::WindowsShellType;
 576
 577            match windows_shell_type {
 578                WindowsShellType::Powershell => {
 579                    user_args.extend(["-C".to_owned(), combined_command])
 580                }
 581                WindowsShellType::Cmd => user_args.extend(["/C".to_owned(), combined_command]),
 582                WindowsShellType::Other => {
 583                    user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command])
 584                }
 585            }
 586        }
 587        spawn_task.args = user_args;
 588        // Set up shell args unconditionally, as tasks are always spawned inside of a shell.
 589
 590        ControlFlow::Continue(())
 591    }
 592
 593    pub fn spawn_in_new_terminal(
 594        &mut self,
 595        spawn_task: SpawnInTerminal,
 596        cx: &mut ViewContext<Self>,
 597    ) -> Task<Result<Model<Terminal>>> {
 598        let reveal = spawn_task.reveal;
 599        let reveal_target = spawn_task.reveal_target;
 600        let kind = TerminalKind::Task(spawn_task);
 601        match reveal_target {
 602            RevealTarget::Center => self
 603                .workspace
 604                .update(cx, |workspace, cx| {
 605                    Self::add_center_terminal(workspace, kind, cx)
 606                })
 607                .unwrap_or_else(|e| Task::ready(Err(e))),
 608            RevealTarget::Dock => self.add_terminal(kind, reveal, cx),
 609        }
 610    }
 611
 612    /// Create a new Terminal in the current working directory or the user's home directory
 613    fn new_terminal(
 614        workspace: &mut Workspace,
 615        _: &workspace::NewTerminal,
 616        cx: &mut ViewContext<Workspace>,
 617    ) {
 618        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 619            return;
 620        };
 621
 622        let kind = TerminalKind::Shell(default_working_directory(workspace, cx));
 623
 624        terminal_panel
 625            .update(cx, |this, cx| {
 626                this.add_terminal(kind, RevealStrategy::Always, cx)
 627            })
 628            .detach_and_log_err(cx);
 629    }
 630
 631    fn terminals_for_task(
 632        &self,
 633        label: &str,
 634        cx: &mut AppContext,
 635    ) -> Vec<(usize, View<Pane>, View<TerminalView>)> {
 636        let Some(workspace) = self.workspace.upgrade() else {
 637            return Vec::new();
 638        };
 639
 640        let pane_terminal_views = |pane: View<Pane>| {
 641            pane.read(cx)
 642                .items()
 643                .enumerate()
 644                .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
 645                .filter_map(|(index, terminal_view)| {
 646                    let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
 647                    if &task_state.full_label == label {
 648                        Some((index, terminal_view))
 649                    } else {
 650                        None
 651                    }
 652                })
 653                .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
 654        };
 655
 656        self.center
 657            .panes()
 658            .into_iter()
 659            .cloned()
 660            .flat_map(pane_terminal_views)
 661            .chain(
 662                workspace
 663                    .read(cx)
 664                    .panes()
 665                    .into_iter()
 666                    .cloned()
 667                    .flat_map(pane_terminal_views),
 668            )
 669            .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
 670            .collect()
 671    }
 672
 673    fn activate_terminal_view(
 674        &self,
 675        pane: &View<Pane>,
 676        item_index: usize,
 677        focus: bool,
 678        cx: &mut WindowContext,
 679    ) {
 680        pane.update(cx, |pane, cx| {
 681            pane.activate_item(item_index, true, focus, cx)
 682        })
 683    }
 684
 685    pub fn add_center_terminal(
 686        workspace: &mut Workspace,
 687        kind: TerminalKind,
 688        cx: &mut ViewContext<Workspace>,
 689    ) -> Task<Result<Model<Terminal>>> {
 690        if !is_enabled_in_workspace(workspace, cx) {
 691            return Task::ready(Err(anyhow!(
 692                "terminal not yet supported for remote projects"
 693            )));
 694        }
 695        let window = cx.window_handle();
 696        let project = workspace.project().downgrade();
 697        cx.spawn(move |workspace, mut cx| async move {
 698            let terminal = project
 699                .update(&mut cx, |project, cx| {
 700                    project.create_terminal(kind, window, cx)
 701                })?
 702                .await?;
 703
 704            workspace.update(&mut cx, |workspace, cx| {
 705                let view = cx.new_view(|cx| {
 706                    TerminalView::new(
 707                        terminal.clone(),
 708                        workspace.weak_handle(),
 709                        workspace.database_id(),
 710                        workspace.project().downgrade(),
 711                        cx,
 712                    )
 713                });
 714                workspace.add_item_to_active_pane(Box::new(view), None, true, cx);
 715            })?;
 716            Ok(terminal)
 717        })
 718    }
 719
 720    fn add_terminal(
 721        &mut self,
 722        kind: TerminalKind,
 723        reveal_strategy: RevealStrategy,
 724        cx: &mut ViewContext<Self>,
 725    ) -> Task<Result<Model<Terminal>>> {
 726        let workspace = self.workspace.clone();
 727        cx.spawn(|terminal_panel, mut cx| async move {
 728            if workspace.update(&mut cx, |workspace, cx| {
 729                !is_enabled_in_workspace(workspace, cx)
 730            })? {
 731                anyhow::bail!("terminal not yet supported for remote projects");
 732            }
 733            let pane = terminal_panel.update(&mut cx, |terminal_panel, _| {
 734                terminal_panel.pending_terminals_to_add += 1;
 735                terminal_panel.active_pane.clone()
 736            })?;
 737            let project = workspace.update(&mut cx, |workspace, _| workspace.project().clone())?;
 738            let window = cx.window_handle();
 739            let terminal = project
 740                .update(&mut cx, |project, cx| {
 741                    project.create_terminal(kind, window, cx)
 742                })?
 743                .await?;
 744            let result = workspace.update(&mut cx, |workspace, cx| {
 745                let terminal_view = Box::new(cx.new_view(|cx| {
 746                    TerminalView::new(
 747                        terminal.clone(),
 748                        workspace.weak_handle(),
 749                        workspace.database_id(),
 750                        workspace.project().downgrade(),
 751                        cx,
 752                    )
 753                }));
 754
 755                match reveal_strategy {
 756                    RevealStrategy::Always => {
 757                        workspace.focus_panel::<Self>(cx);
 758                    }
 759                    RevealStrategy::NoFocus => {
 760                        workspace.open_panel::<Self>(cx);
 761                    }
 762                    RevealStrategy::Never => {}
 763                }
 764
 765                pane.update(cx, |pane, cx| {
 766                    let focus =
 767                        pane.has_focus(cx) || matches!(reveal_strategy, RevealStrategy::Always);
 768                    pane.add_item(terminal_view, true, focus, None, cx);
 769                });
 770
 771                Ok(terminal)
 772            })?;
 773            terminal_panel.update(&mut cx, |this, cx| {
 774                this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
 775                this.serialize(cx)
 776            })?;
 777            result
 778        })
 779    }
 780
 781    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
 782        let height = self.height;
 783        let width = self.width;
 784        self.pending_serialization = cx.spawn(|terminal_panel, mut cx| async move {
 785            cx.background_executor()
 786                .timer(Duration::from_millis(50))
 787                .await;
 788            let terminal_panel = terminal_panel.upgrade()?;
 789            let items = terminal_panel
 790                .update(&mut cx, |terminal_panel, cx| {
 791                    SerializedItems::WithSplits(serialize_pane_group(
 792                        &terminal_panel.center,
 793                        &terminal_panel.active_pane,
 794                        cx,
 795                    ))
 796                })
 797                .ok()?;
 798            cx.background_executor()
 799                .spawn(
 800                    async move {
 801                        KEY_VALUE_STORE
 802                            .write_kvp(
 803                                TERMINAL_PANEL_KEY.into(),
 804                                serde_json::to_string(&SerializedTerminalPanel {
 805                                    items,
 806                                    active_item_id: None,
 807                                    height,
 808                                    width,
 809                                })?,
 810                            )
 811                            .await?;
 812                        anyhow::Ok(())
 813                    }
 814                    .log_err(),
 815                )
 816                .await;
 817            Some(())
 818        });
 819    }
 820
 821    fn replace_terminal(
 822        &self,
 823        spawn_task: SpawnInTerminal,
 824        task_pane: View<Pane>,
 825        terminal_item_index: usize,
 826        terminal_to_replace: View<TerminalView>,
 827        cx: &mut ViewContext<'_, Self>,
 828    ) -> Task<Option<()>> {
 829        let reveal = spawn_task.reveal;
 830        let reveal_target = spawn_task.reveal_target;
 831        let window = cx.window_handle();
 832        let task_workspace = self.workspace.clone();
 833        cx.spawn(move |terminal_panel, mut cx| async move {
 834            let project = terminal_panel
 835                .update(&mut cx, |this, cx| {
 836                    this.workspace
 837                        .update(cx, |workspace, _| workspace.project().clone())
 838                        .ok()
 839                })
 840                .ok()
 841                .flatten()?;
 842            let new_terminal = project
 843                .update(&mut cx, |project, cx| {
 844                    project.create_terminal(TerminalKind::Task(spawn_task), window, cx)
 845                })
 846                .ok()?
 847                .await
 848                .log_err()?;
 849            terminal_to_replace
 850                .update(&mut cx, |terminal_to_replace, cx| {
 851                    terminal_to_replace.set_terminal(new_terminal, cx);
 852                })
 853                .ok()?;
 854
 855            match reveal {
 856                RevealStrategy::Always => match reveal_target {
 857                    RevealTarget::Center => {
 858                        task_workspace
 859                            .update(&mut cx, |workspace, cx| {
 860                                workspace
 861                                    .active_item(cx)
 862                                    .context("retrieving active terminal item in the workspace")
 863                                    .log_err()?
 864                                    .focus_handle(cx)
 865                                    .focus(cx);
 866                                Some(())
 867                            })
 868                            .ok()??;
 869                    }
 870                    RevealTarget::Dock => {
 871                        terminal_panel
 872                            .update(&mut cx, |terminal_panel, cx| {
 873                                terminal_panel.activate_terminal_view(
 874                                    &task_pane,
 875                                    terminal_item_index,
 876                                    true,
 877                                    cx,
 878                                )
 879                            })
 880                            .ok()?;
 881
 882                        cx.spawn(|mut cx| async move {
 883                            task_workspace
 884                                .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
 885                                .ok()
 886                        })
 887                        .detach();
 888                    }
 889                },
 890                RevealStrategy::NoFocus => match reveal_target {
 891                    RevealTarget::Center => {
 892                        task_workspace
 893                            .update(&mut cx, |workspace, cx| {
 894                                workspace.active_pane().focus_handle(cx).focus(cx);
 895                            })
 896                            .ok()?;
 897                    }
 898                    RevealTarget::Dock => {
 899                        terminal_panel
 900                            .update(&mut cx, |terminal_panel, cx| {
 901                                terminal_panel.activate_terminal_view(
 902                                    &task_pane,
 903                                    terminal_item_index,
 904                                    false,
 905                                    cx,
 906                                )
 907                            })
 908                            .ok()?;
 909
 910                        cx.spawn(|mut cx| async move {
 911                            task_workspace
 912                                .update(&mut cx, |workspace, cx| workspace.open_panel::<Self>(cx))
 913                                .ok()
 914                        })
 915                        .detach();
 916                    }
 917                },
 918                RevealStrategy::Never => {}
 919            }
 920
 921            Some(())
 922        })
 923    }
 924
 925    fn has_no_terminals(&self, cx: &WindowContext) -> bool {
 926        self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
 927    }
 928
 929    pub fn assistant_enabled(&self) -> bool {
 930        self.assistant_enabled
 931    }
 932
 933    fn is_enabled(&self, cx: &WindowContext) -> bool {
 934        self.workspace.upgrade().map_or(false, |workspace| {
 935            is_enabled_in_workspace(workspace.read(cx), cx)
 936        })
 937    }
 938}
 939
 940fn is_enabled_in_workspace(workspace: &Workspace, cx: &WindowContext) -> bool {
 941    workspace.project().read(cx).supports_terminal(cx)
 942}
 943
 944pub fn new_terminal_pane(
 945    workspace: WeakView<Workspace>,
 946    project: Model<Project>,
 947    zoomed: bool,
 948    cx: &mut ViewContext<TerminalPanel>,
 949) -> View<Pane> {
 950    let is_local = project.read(cx).is_local();
 951    let terminal_panel = cx.view().clone();
 952    let pane = cx.new_view(|cx| {
 953        let mut pane = Pane::new(
 954            workspace.clone(),
 955            project.clone(),
 956            Default::default(),
 957            None,
 958            NewTerminal.boxed_clone(),
 959            cx,
 960        );
 961        pane.set_zoomed(zoomed, cx);
 962        pane.set_can_navigate(false, cx);
 963        pane.display_nav_history_buttons(None);
 964        pane.set_should_display_tab_bar(|_| true);
 965        pane.set_zoom_out_on_close(false);
 966
 967        let split_closure_terminal_panel = terminal_panel.downgrade();
 968        pane.set_can_split(Some(Arc::new(move |pane, dragged_item, cx| {
 969            if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
 970                let is_current_pane = &tab.pane == cx.view();
 971                let Some(can_drag_away) = split_closure_terminal_panel
 972                    .update(cx, |terminal_panel, _| {
 973                        let current_panes = terminal_panel.center.panes();
 974                        !current_panes.contains(&&tab.pane)
 975                            || current_panes.len() > 1
 976                            || (!is_current_pane || pane.items_len() > 1)
 977                    })
 978                    .ok()
 979                else {
 980                    return false;
 981                };
 982                if can_drag_away {
 983                    let item = if is_current_pane {
 984                        pane.item_for_index(tab.ix)
 985                    } else {
 986                        tab.pane.read(cx).item_for_index(tab.ix)
 987                    };
 988                    if let Some(item) = item {
 989                        return item.downcast::<TerminalView>().is_some();
 990                    }
 991                }
 992            }
 993            false
 994        })));
 995
 996        let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
 997        let breadcrumbs = cx.new_view(|_| Breadcrumbs::new());
 998        pane.toolbar().update(cx, |toolbar, cx| {
 999            toolbar.add_item(buffer_search_bar, cx);
1000            toolbar.add_item(breadcrumbs, cx);
1001        });
1002
1003        let drop_closure_project = project.downgrade();
1004        let drop_closure_terminal_panel = terminal_panel.downgrade();
1005        pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
1006            let Some(project) = drop_closure_project.upgrade() else {
1007                return ControlFlow::Break(());
1008            };
1009            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1010                let this_pane = cx.view().clone();
1011                let item = if tab.pane == this_pane {
1012                    pane.item_for_index(tab.ix)
1013                } else {
1014                    tab.pane.read(cx).item_for_index(tab.ix)
1015                };
1016                if let Some(item) = item {
1017                    if item.downcast::<TerminalView>().is_some() {
1018                        let source = tab.pane.clone();
1019                        let item_id_to_move = item.item_id();
1020
1021                        let Ok(new_split_pane) = pane
1022                            .drag_split_direction()
1023                            .map(|split_direction| {
1024                                drop_closure_terminal_panel.update(cx, |terminal_panel, cx| {
1025                                    let is_zoomed = if terminal_panel.active_pane == this_pane {
1026                                        pane.is_zoomed()
1027                                    } else {
1028                                        terminal_panel.active_pane.read(cx).is_zoomed()
1029                                    };
1030                                    let new_pane = new_terminal_pane(
1031                                        workspace.clone(),
1032                                        project.clone(),
1033                                        is_zoomed,
1034                                        cx,
1035                                    );
1036                                    terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1037                                    terminal_panel.center.split(
1038                                        &this_pane,
1039                                        &new_pane,
1040                                        split_direction,
1041                                    )?;
1042                                    anyhow::Ok(new_pane)
1043                                })
1044                            })
1045                            .transpose()
1046                        else {
1047                            return ControlFlow::Break(());
1048                        };
1049
1050                        match new_split_pane.transpose() {
1051                            // Source pane may be the one currently updated, so defer the move.
1052                            Ok(Some(new_pane)) => cx
1053                                .spawn(|_, mut cx| async move {
1054                                    cx.update(|cx| {
1055                                        move_item(
1056                                            &source,
1057                                            &new_pane,
1058                                            item_id_to_move,
1059                                            new_pane.read(cx).active_item_index(),
1060                                            cx,
1061                                        );
1062                                    })
1063                                    .ok();
1064                                })
1065                                .detach(),
1066                            // If we drop into existing pane or current pane,
1067                            // regular pane drop handler will take care of it,
1068                            // using the right tab index for the operation.
1069                            Ok(None) => return ControlFlow::Continue(()),
1070                            err @ Err(_) => {
1071                                err.log_err();
1072                                return ControlFlow::Break(());
1073                            }
1074                        };
1075                    } else if let Some(project_path) = item.project_path(cx) {
1076                        if let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1077                        {
1078                            add_paths_to_terminal(pane, &[entry_path], cx);
1079                        }
1080                    }
1081                }
1082            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1083                if let Some(entry_path) = project
1084                    .read(cx)
1085                    .path_for_entry(entry_id, cx)
1086                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1087                {
1088                    add_paths_to_terminal(pane, &[entry_path], cx);
1089                }
1090            } else if is_local {
1091                if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1092                    add_paths_to_terminal(pane, paths.paths(), cx);
1093                }
1094            }
1095
1096            ControlFlow::Break(())
1097        });
1098
1099        pane
1100    });
1101
1102    cx.subscribe(&pane, TerminalPanel::handle_pane_event)
1103        .detach();
1104    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1105
1106    pane
1107}
1108
1109async fn wait_for_terminals_tasks(
1110    terminals_for_task: Vec<(usize, View<Pane>, View<TerminalView>)>,
1111    cx: &mut AsyncWindowContext,
1112) {
1113    let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
1114        terminal
1115            .update(cx, |terminal_view, cx| {
1116                terminal_view
1117                    .terminal()
1118                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1119            })
1120            .ok()
1121    });
1122    let _: Vec<()> = join_all(pending_tasks).await;
1123}
1124
1125fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
1126    if let Some(terminal_view) = pane
1127        .active_item()
1128        .and_then(|item| item.downcast::<TerminalView>())
1129    {
1130        cx.focus_view(&terminal_view);
1131        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1132        new_text.push(' ');
1133        terminal_view.update(cx, |terminal_view, cx| {
1134            terminal_view.terminal().update(cx, |terminal, _| {
1135                terminal.paste(&new_text);
1136            });
1137        });
1138    }
1139}
1140
1141impl EventEmitter<PanelEvent> for TerminalPanel {}
1142
1143impl Render for TerminalPanel {
1144    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1145        let mut registrar = DivRegistrar::new(
1146            |panel, cx| {
1147                panel
1148                    .active_pane
1149                    .read(cx)
1150                    .toolbar()
1151                    .read(cx)
1152                    .item_of_type::<BufferSearchBar>()
1153            },
1154            cx,
1155        );
1156        BufferSearchBar::register(&mut registrar);
1157        let registrar = registrar.into_div();
1158        self.workspace
1159            .update(cx, |workspace, cx| {
1160                registrar.size_full().child(self.center.render(
1161                    workspace.project(),
1162                    &HashMap::default(),
1163                    None,
1164                    &self.active_pane,
1165                    workspace.zoomed_item(),
1166                    workspace.app_state(),
1167                    cx,
1168                ))
1169            })
1170            .ok()
1171            .map(|div| {
1172                div.on_action({
1173                    cx.listener(|terminal_panel, action: &ActivatePaneInDirection, cx| {
1174                        if let Some(pane) = terminal_panel.center.find_pane_in_direction(
1175                            &terminal_panel.active_pane,
1176                            action.0,
1177                            cx,
1178                        ) {
1179                            cx.focus_view(&pane);
1180                        } else {
1181                            terminal_panel
1182                                .workspace
1183                                .update(cx, |workspace, cx| {
1184                                    workspace.activate_pane_in_direction(action.0, cx)
1185                                })
1186                                .ok();
1187                        }
1188                    })
1189                })
1190                .on_action(
1191                    cx.listener(|terminal_panel, _action: &ActivateNextPane, cx| {
1192                        let panes = terminal_panel.center.panes();
1193                        if let Some(ix) = panes
1194                            .iter()
1195                            .position(|pane| **pane == terminal_panel.active_pane)
1196                        {
1197                            let next_ix = (ix + 1) % panes.len();
1198                            cx.focus_view(&panes[next_ix]);
1199                        }
1200                    }),
1201                )
1202                .on_action(
1203                    cx.listener(|terminal_panel, _action: &ActivatePreviousPane, cx| {
1204                        let panes = terminal_panel.center.panes();
1205                        if let Some(ix) = panes
1206                            .iter()
1207                            .position(|pane| **pane == terminal_panel.active_pane)
1208                        {
1209                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1210                            cx.focus_view(&panes[prev_ix]);
1211                        }
1212                    }),
1213                )
1214                .on_action(cx.listener(|terminal_panel, action: &ActivatePane, cx| {
1215                    let panes = terminal_panel.center.panes();
1216                    if let Some(&pane) = panes.get(action.0) {
1217                        cx.focus_view(pane);
1218                    } else {
1219                        if let Some(new_pane) =
1220                            terminal_panel.new_pane_with_cloned_active_terminal(cx)
1221                        {
1222                            terminal_panel
1223                                .center
1224                                .split(
1225                                    &terminal_panel.active_pane,
1226                                    &new_pane,
1227                                    SplitDirection::Right,
1228                                )
1229                                .log_err();
1230                            cx.focus_view(&new_pane);
1231                        }
1232                    }
1233                }))
1234                .on_action(
1235                    cx.listener(|terminal_panel, action: &SwapPaneInDirection, cx| {
1236                        if let Some(to) = terminal_panel
1237                            .center
1238                            .find_pane_in_direction(&terminal_panel.active_pane, action.0, cx)
1239                            .cloned()
1240                        {
1241                            terminal_panel.center.swap(&terminal_panel.active_pane, &to);
1242                            cx.notify();
1243                        }
1244                    }),
1245                )
1246                .on_action(cx.listener(|terminal_panel, action: &MoveItemToPane, cx| {
1247                    let Some(&target_pane) = terminal_panel.center.panes().get(action.destination)
1248                    else {
1249                        return;
1250                    };
1251                    move_active_item(
1252                        &terminal_panel.active_pane,
1253                        target_pane,
1254                        action.focus,
1255                        true,
1256                        cx,
1257                    );
1258                }))
1259                .on_action(cx.listener(
1260                    |terminal_panel, action: &MoveItemToPaneInDirection, cx| {
1261                        let source_pane = &terminal_panel.active_pane;
1262                        if let Some(destination_pane) = terminal_panel
1263                            .center
1264                            .find_pane_in_direction(source_pane, action.direction, cx)
1265                        {
1266                            move_active_item(source_pane, destination_pane, action.focus, true, cx);
1267                        };
1268                    },
1269                ))
1270            })
1271            .unwrap_or_else(|| div())
1272    }
1273}
1274
1275impl FocusableView for TerminalPanel {
1276    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1277        self.active_pane.focus_handle(cx)
1278    }
1279}
1280
1281impl Panel for TerminalPanel {
1282    fn position(&self, cx: &WindowContext) -> DockPosition {
1283        match TerminalSettings::get_global(cx).dock {
1284            TerminalDockPosition::Left => DockPosition::Left,
1285            TerminalDockPosition::Bottom => DockPosition::Bottom,
1286            TerminalDockPosition::Right => DockPosition::Right,
1287        }
1288    }
1289
1290    fn position_is_valid(&self, _: DockPosition) -> bool {
1291        true
1292    }
1293
1294    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1295        settings::update_settings_file::<TerminalSettings>(
1296            self.fs.clone(),
1297            cx,
1298            move |settings, _| {
1299                let dock = match position {
1300                    DockPosition::Left => TerminalDockPosition::Left,
1301                    DockPosition::Bottom => TerminalDockPosition::Bottom,
1302                    DockPosition::Right => TerminalDockPosition::Right,
1303                };
1304                settings.dock = Some(dock);
1305            },
1306        );
1307    }
1308
1309    fn size(&self, cx: &WindowContext) -> Pixels {
1310        let settings = TerminalSettings::get_global(cx);
1311        match self.position(cx) {
1312            DockPosition::Left | DockPosition::Right => {
1313                self.width.unwrap_or(settings.default_width)
1314            }
1315            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1316        }
1317    }
1318
1319    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1320        match self.position(cx) {
1321            DockPosition::Left | DockPosition::Right => self.width = size,
1322            DockPosition::Bottom => self.height = size,
1323        }
1324        self.serialize(cx);
1325        cx.notify();
1326    }
1327
1328    fn is_zoomed(&self, cx: &WindowContext) -> bool {
1329        self.active_pane.read(cx).is_zoomed()
1330    }
1331
1332    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1333        for pane in self.center.panes() {
1334            pane.update(cx, |pane, cx| {
1335                pane.set_zoomed(zoomed, cx);
1336            })
1337        }
1338        cx.notify();
1339    }
1340
1341    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1342        if !active || !self.has_no_terminals(cx) {
1343            return;
1344        }
1345        cx.defer(|this, cx| {
1346            let Ok(kind) = this.workspace.update(cx, |workspace, cx| {
1347                TerminalKind::Shell(default_working_directory(workspace, cx))
1348            }) else {
1349                return;
1350            };
1351
1352            this.add_terminal(kind, RevealStrategy::Always, cx)
1353                .detach_and_log_err(cx)
1354        })
1355    }
1356
1357    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
1358        let count = self
1359            .center
1360            .panes()
1361            .into_iter()
1362            .map(|pane| pane.read(cx).items_len())
1363            .sum::<usize>();
1364        if count == 0 {
1365            None
1366        } else {
1367            Some(count.to_string())
1368        }
1369    }
1370
1371    fn persistent_name() -> &'static str {
1372        "TerminalPanel"
1373    }
1374
1375    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1376        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1377            && TerminalSettings::get_global(cx).button
1378        {
1379            Some(IconName::Terminal)
1380        } else {
1381            None
1382        }
1383    }
1384
1385    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1386        Some("Terminal Panel")
1387    }
1388
1389    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1390        Box::new(ToggleFocus)
1391    }
1392
1393    fn pane(&self) -> Option<View<Pane>> {
1394        Some(self.active_pane.clone())
1395    }
1396}
1397
1398struct InlineAssistTabBarButton {
1399    focus_handle: FocusHandle,
1400}
1401
1402impl Render for InlineAssistTabBarButton {
1403    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1404        let focus_handle = self.focus_handle.clone();
1405        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1406            .icon_size(IconSize::Small)
1407            .on_click(cx.listener(|_, _, cx| {
1408                cx.dispatch_action(InlineAssist::default().boxed_clone());
1409            }))
1410            .tooltip(move |cx| {
1411                Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1412            })
1413    }
1414}
1415
1416fn retrieve_system_shell() -> Option<String> {
1417    #[cfg(not(target_os = "windows"))]
1418    {
1419        use anyhow::Context;
1420        use util::ResultExt;
1421
1422        std::env::var("SHELL")
1423            .context("Error finding SHELL in env.")
1424            .log_err()
1425    }
1426    // `alacritty_terminal` uses this as default on Windows. See:
1427    // https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
1428    #[cfg(target_os = "windows")]
1429    return Some("powershell".to_owned());
1430}
1431
1432#[cfg(target_os = "windows")]
1433fn to_windows_shell_variable(shell_type: WindowsShellType, input: String) -> String {
1434    match shell_type {
1435        WindowsShellType::Powershell => to_powershell_variable(input),
1436        WindowsShellType::Cmd => to_cmd_variable(input),
1437        WindowsShellType::Other => input,
1438    }
1439}
1440
1441#[cfg(target_os = "windows")]
1442fn to_windows_shell_type(shell: &str) -> WindowsShellType {
1443    if shell == "powershell"
1444        || shell.ends_with("powershell.exe")
1445        || shell == "pwsh"
1446        || shell.ends_with("pwsh.exe")
1447    {
1448        WindowsShellType::Powershell
1449    } else if shell == "cmd" || shell.ends_with("cmd.exe") {
1450        WindowsShellType::Cmd
1451    } else {
1452        // Someother shell detected, the user might install and use a
1453        // unix-like shell.
1454        WindowsShellType::Other
1455    }
1456}
1457
1458/// Convert `${SOME_VAR}`, `$SOME_VAR` to `%SOME_VAR%`.
1459#[inline]
1460#[cfg(target_os = "windows")]
1461fn to_cmd_variable(input: String) -> String {
1462    if let Some(var_str) = input.strip_prefix("${") {
1463        if var_str.find(':').is_none() {
1464            // If the input starts with "${", remove the trailing "}"
1465            format!("%{}%", &var_str[..var_str.len() - 1])
1466        } else {
1467            // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
1468            // which will result in the task failing to run in such cases.
1469            input
1470        }
1471    } else if let Some(var_str) = input.strip_prefix('$') {
1472        // If the input starts with "$", directly append to "$env:"
1473        format!("%{}%", var_str)
1474    } else {
1475        // If no prefix is found, return the input as is
1476        input
1477    }
1478}
1479
1480/// Convert `${SOME_VAR}`, `$SOME_VAR` to `$env:SOME_VAR`.
1481#[inline]
1482#[cfg(target_os = "windows")]
1483fn to_powershell_variable(input: String) -> String {
1484    if let Some(var_str) = input.strip_prefix("${") {
1485        if var_str.find(':').is_none() {
1486            // If the input starts with "${", remove the trailing "}"
1487            format!("$env:{}", &var_str[..var_str.len() - 1])
1488        } else {
1489            // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
1490            // which will result in the task failing to run in such cases.
1491            input
1492        }
1493    } else if let Some(var_str) = input.strip_prefix('$') {
1494        // If the input starts with "$", directly append to "$env:"
1495        format!("$env:{}", var_str)
1496    } else {
1497        // If no prefix is found, return the input as is
1498        input
1499    }
1500}
1501
1502#[cfg(target_os = "windows")]
1503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1504enum WindowsShellType {
1505    Powershell,
1506    Cmd,
1507    Other,
1508}