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 terminal_panel_for_split_check = terminal_panel.clone();
 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 current_pane = cx.view().clone();
 971                let can_drag_away =
 972                    terminal_panel_for_split_check.update(cx, |terminal_panel, _| {
 973                        let current_panes = terminal_panel.center.panes();
 974                        !current_panes.contains(&&tab.pane)
 975                            || current_panes.len() > 1
 976                            || (tab.pane != current_pane || pane.items_len() > 1)
 977                    });
 978                if can_drag_away {
 979                    let item = if tab.pane == current_pane {
 980                        pane.item_for_index(tab.ix)
 981                    } else {
 982                        tab.pane.read(cx).item_for_index(tab.ix)
 983                    };
 984                    if let Some(item) = item {
 985                        return item.downcast::<TerminalView>().is_some();
 986                    }
 987                }
 988            }
 989            false
 990        })));
 991
 992        let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
 993        let breadcrumbs = cx.new_view(|_| Breadcrumbs::new());
 994        pane.toolbar().update(cx, |toolbar, cx| {
 995            toolbar.add_item(buffer_search_bar, cx);
 996            toolbar.add_item(breadcrumbs, cx);
 997        });
 998
 999        pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
1000            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1001                let this_pane = cx.view().clone();
1002                let item = if tab.pane == this_pane {
1003                    pane.item_for_index(tab.ix)
1004                } else {
1005                    tab.pane.read(cx).item_for_index(tab.ix)
1006                };
1007                if let Some(item) = item {
1008                    if item.downcast::<TerminalView>().is_some() {
1009                        let source = tab.pane.clone();
1010                        let item_id_to_move = item.item_id();
1011
1012                        let new_split_pane = pane
1013                            .drag_split_direction()
1014                            .map(|split_direction| {
1015                                terminal_panel.update(cx, |terminal_panel, cx| {
1016                                    let is_zoomed = if terminal_panel.active_pane == this_pane {
1017                                        pane.is_zoomed()
1018                                    } else {
1019                                        terminal_panel.active_pane.read(cx).is_zoomed()
1020                                    };
1021                                    let new_pane = new_terminal_pane(
1022                                        workspace.clone(),
1023                                        project.clone(),
1024                                        is_zoomed,
1025                                        cx,
1026                                    );
1027                                    terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1028                                    terminal_panel.center.split(
1029                                        &this_pane,
1030                                        &new_pane,
1031                                        split_direction,
1032                                    )?;
1033                                    anyhow::Ok(new_pane)
1034                                })
1035                            })
1036                            .transpose();
1037
1038                        match new_split_pane {
1039                            // Source pane may be the one currently updated, so defer the move.
1040                            Ok(Some(new_pane)) => cx
1041                                .spawn(|_, mut cx| async move {
1042                                    cx.update(|cx| {
1043                                        move_item(
1044                                            &source,
1045                                            &new_pane,
1046                                            item_id_to_move,
1047                                            new_pane.read(cx).active_item_index(),
1048                                            cx,
1049                                        );
1050                                    })
1051                                    .ok();
1052                                })
1053                                .detach(),
1054                            // If we drop into existing pane or current pane,
1055                            // regular pane drop handler will take care of it,
1056                            // using the right tab index for the operation.
1057                            Ok(None) => return ControlFlow::Continue(()),
1058                            err @ Err(_) => {
1059                                err.log_err();
1060                                return ControlFlow::Break(());
1061                            }
1062                        };
1063                    } else if let Some(project_path) = item.project_path(cx) {
1064                        if let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1065                        {
1066                            add_paths_to_terminal(pane, &[entry_path], cx);
1067                        }
1068                    }
1069                }
1070            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1071                if let Some(entry_path) = project
1072                    .read(cx)
1073                    .path_for_entry(entry_id, cx)
1074                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1075                {
1076                    add_paths_to_terminal(pane, &[entry_path], cx);
1077                }
1078            } else if is_local {
1079                if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1080                    add_paths_to_terminal(pane, paths.paths(), cx);
1081                }
1082            }
1083
1084            ControlFlow::Break(())
1085        });
1086
1087        pane
1088    });
1089
1090    cx.subscribe(&pane, TerminalPanel::handle_pane_event)
1091        .detach();
1092    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1093
1094    pane
1095}
1096
1097async fn wait_for_terminals_tasks(
1098    terminals_for_task: Vec<(usize, View<Pane>, View<TerminalView>)>,
1099    cx: &mut AsyncWindowContext,
1100) {
1101    let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
1102        terminal
1103            .update(cx, |terminal_view, cx| {
1104                terminal_view
1105                    .terminal()
1106                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1107            })
1108            .ok()
1109    });
1110    let _: Vec<()> = join_all(pending_tasks).await;
1111}
1112
1113fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
1114    if let Some(terminal_view) = pane
1115        .active_item()
1116        .and_then(|item| item.downcast::<TerminalView>())
1117    {
1118        cx.focus_view(&terminal_view);
1119        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1120        new_text.push(' ');
1121        terminal_view.update(cx, |terminal_view, cx| {
1122            terminal_view.terminal().update(cx, |terminal, _| {
1123                terminal.paste(&new_text);
1124            });
1125        });
1126    }
1127}
1128
1129impl EventEmitter<PanelEvent> for TerminalPanel {}
1130
1131impl Render for TerminalPanel {
1132    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1133        let mut registrar = DivRegistrar::new(
1134            |panel, cx| {
1135                panel
1136                    .active_pane
1137                    .read(cx)
1138                    .toolbar()
1139                    .read(cx)
1140                    .item_of_type::<BufferSearchBar>()
1141            },
1142            cx,
1143        );
1144        BufferSearchBar::register(&mut registrar);
1145        let registrar = registrar.into_div();
1146        self.workspace
1147            .update(cx, |workspace, cx| {
1148                registrar.size_full().child(self.center.render(
1149                    workspace.project(),
1150                    &HashMap::default(),
1151                    None,
1152                    &self.active_pane,
1153                    workspace.zoomed_item(),
1154                    workspace.app_state(),
1155                    cx,
1156                ))
1157            })
1158            .ok()
1159            .map(|div| {
1160                div.on_action({
1161                    cx.listener(|terminal_panel, action: &ActivatePaneInDirection, cx| {
1162                        if let Some(pane) = terminal_panel.center.find_pane_in_direction(
1163                            &terminal_panel.active_pane,
1164                            action.0,
1165                            cx,
1166                        ) {
1167                            cx.focus_view(&pane);
1168                        } else {
1169                            terminal_panel
1170                                .workspace
1171                                .update(cx, |workspace, cx| {
1172                                    workspace.activate_pane_in_direction(action.0, cx)
1173                                })
1174                                .ok();
1175                        }
1176                    })
1177                })
1178                .on_action(
1179                    cx.listener(|terminal_panel, _action: &ActivateNextPane, cx| {
1180                        let panes = terminal_panel.center.panes();
1181                        if let Some(ix) = panes
1182                            .iter()
1183                            .position(|pane| **pane == terminal_panel.active_pane)
1184                        {
1185                            let next_ix = (ix + 1) % panes.len();
1186                            cx.focus_view(&panes[next_ix]);
1187                        }
1188                    }),
1189                )
1190                .on_action(
1191                    cx.listener(|terminal_panel, _action: &ActivatePreviousPane, 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 prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1198                            cx.focus_view(&panes[prev_ix]);
1199                        }
1200                    }),
1201                )
1202                .on_action(cx.listener(|terminal_panel, action: &ActivatePane, cx| {
1203                    let panes = terminal_panel.center.panes();
1204                    if let Some(&pane) = panes.get(action.0) {
1205                        cx.focus_view(pane);
1206                    } else {
1207                        if let Some(new_pane) =
1208                            terminal_panel.new_pane_with_cloned_active_terminal(cx)
1209                        {
1210                            terminal_panel
1211                                .center
1212                                .split(
1213                                    &terminal_panel.active_pane,
1214                                    &new_pane,
1215                                    SplitDirection::Right,
1216                                )
1217                                .log_err();
1218                            cx.focus_view(&new_pane);
1219                        }
1220                    }
1221                }))
1222                .on_action(
1223                    cx.listener(|terminal_panel, action: &SwapPaneInDirection, cx| {
1224                        if let Some(to) = terminal_panel
1225                            .center
1226                            .find_pane_in_direction(&terminal_panel.active_pane, action.0, cx)
1227                            .cloned()
1228                        {
1229                            terminal_panel.center.swap(&terminal_panel.active_pane, &to);
1230                            cx.notify();
1231                        }
1232                    }),
1233                )
1234                .on_action(cx.listener(|terminal_panel, action: &MoveItemToPane, cx| {
1235                    let Some(&target_pane) = terminal_panel.center.panes().get(action.destination)
1236                    else {
1237                        return;
1238                    };
1239                    move_active_item(
1240                        &terminal_panel.active_pane,
1241                        target_pane,
1242                        action.focus,
1243                        true,
1244                        cx,
1245                    );
1246                }))
1247                .on_action(cx.listener(
1248                    |terminal_panel, action: &MoveItemToPaneInDirection, cx| {
1249                        let source_pane = &terminal_panel.active_pane;
1250                        if let Some(destination_pane) = terminal_panel
1251                            .center
1252                            .find_pane_in_direction(source_pane, action.direction, cx)
1253                        {
1254                            move_active_item(source_pane, destination_pane, action.focus, true, cx);
1255                        };
1256                    },
1257                ))
1258            })
1259            .unwrap_or_else(|| div())
1260    }
1261}
1262
1263impl FocusableView for TerminalPanel {
1264    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1265        self.active_pane.focus_handle(cx)
1266    }
1267}
1268
1269impl Panel for TerminalPanel {
1270    fn position(&self, cx: &WindowContext) -> DockPosition {
1271        match TerminalSettings::get_global(cx).dock {
1272            TerminalDockPosition::Left => DockPosition::Left,
1273            TerminalDockPosition::Bottom => DockPosition::Bottom,
1274            TerminalDockPosition::Right => DockPosition::Right,
1275        }
1276    }
1277
1278    fn position_is_valid(&self, _: DockPosition) -> bool {
1279        true
1280    }
1281
1282    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1283        settings::update_settings_file::<TerminalSettings>(
1284            self.fs.clone(),
1285            cx,
1286            move |settings, _| {
1287                let dock = match position {
1288                    DockPosition::Left => TerminalDockPosition::Left,
1289                    DockPosition::Bottom => TerminalDockPosition::Bottom,
1290                    DockPosition::Right => TerminalDockPosition::Right,
1291                };
1292                settings.dock = Some(dock);
1293            },
1294        );
1295    }
1296
1297    fn size(&self, cx: &WindowContext) -> Pixels {
1298        let settings = TerminalSettings::get_global(cx);
1299        match self.position(cx) {
1300            DockPosition::Left | DockPosition::Right => {
1301                self.width.unwrap_or(settings.default_width)
1302            }
1303            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1304        }
1305    }
1306
1307    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1308        match self.position(cx) {
1309            DockPosition::Left | DockPosition::Right => self.width = size,
1310            DockPosition::Bottom => self.height = size,
1311        }
1312        self.serialize(cx);
1313        cx.notify();
1314    }
1315
1316    fn is_zoomed(&self, cx: &WindowContext) -> bool {
1317        self.active_pane.read(cx).is_zoomed()
1318    }
1319
1320    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1321        for pane in self.center.panes() {
1322            pane.update(cx, |pane, cx| {
1323                pane.set_zoomed(zoomed, cx);
1324            })
1325        }
1326        cx.notify();
1327    }
1328
1329    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1330        if !active || !self.has_no_terminals(cx) {
1331            return;
1332        }
1333        cx.defer(|this, cx| {
1334            let Ok(kind) = this.workspace.update(cx, |workspace, cx| {
1335                TerminalKind::Shell(default_working_directory(workspace, cx))
1336            }) else {
1337                return;
1338            };
1339
1340            this.add_terminal(kind, RevealStrategy::Always, cx)
1341                .detach_and_log_err(cx)
1342        })
1343    }
1344
1345    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
1346        let count = self
1347            .center
1348            .panes()
1349            .into_iter()
1350            .map(|pane| pane.read(cx).items_len())
1351            .sum::<usize>();
1352        if count == 0 {
1353            None
1354        } else {
1355            Some(count.to_string())
1356        }
1357    }
1358
1359    fn persistent_name() -> &'static str {
1360        "TerminalPanel"
1361    }
1362
1363    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1364        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1365            && TerminalSettings::get_global(cx).button
1366        {
1367            Some(IconName::Terminal)
1368        } else {
1369            None
1370        }
1371    }
1372
1373    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1374        Some("Terminal Panel")
1375    }
1376
1377    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1378        Box::new(ToggleFocus)
1379    }
1380
1381    fn pane(&self) -> Option<View<Pane>> {
1382        Some(self.active_pane.clone())
1383    }
1384}
1385
1386struct InlineAssistTabBarButton {
1387    focus_handle: FocusHandle,
1388}
1389
1390impl Render for InlineAssistTabBarButton {
1391    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1392        let focus_handle = self.focus_handle.clone();
1393        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1394            .icon_size(IconSize::Small)
1395            .on_click(cx.listener(|_, _, cx| {
1396                cx.dispatch_action(InlineAssist::default().boxed_clone());
1397            }))
1398            .tooltip(move |cx| {
1399                Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1400            })
1401    }
1402}
1403
1404fn retrieve_system_shell() -> Option<String> {
1405    #[cfg(not(target_os = "windows"))]
1406    {
1407        use anyhow::Context;
1408        use util::ResultExt;
1409
1410        std::env::var("SHELL")
1411            .context("Error finding SHELL in env.")
1412            .log_err()
1413    }
1414    // `alacritty_terminal` uses this as default on Windows. See:
1415    // https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
1416    #[cfg(target_os = "windows")]
1417    return Some("powershell".to_owned());
1418}
1419
1420#[cfg(target_os = "windows")]
1421fn to_windows_shell_variable(shell_type: WindowsShellType, input: String) -> String {
1422    match shell_type {
1423        WindowsShellType::Powershell => to_powershell_variable(input),
1424        WindowsShellType::Cmd => to_cmd_variable(input),
1425        WindowsShellType::Other => input,
1426    }
1427}
1428
1429#[cfg(target_os = "windows")]
1430fn to_windows_shell_type(shell: &str) -> WindowsShellType {
1431    if shell == "powershell"
1432        || shell.ends_with("powershell.exe")
1433        || shell == "pwsh"
1434        || shell.ends_with("pwsh.exe")
1435    {
1436        WindowsShellType::Powershell
1437    } else if shell == "cmd" || shell.ends_with("cmd.exe") {
1438        WindowsShellType::Cmd
1439    } else {
1440        // Someother shell detected, the user might install and use a
1441        // unix-like shell.
1442        WindowsShellType::Other
1443    }
1444}
1445
1446/// Convert `${SOME_VAR}`, `$SOME_VAR` to `%SOME_VAR%`.
1447#[inline]
1448#[cfg(target_os = "windows")]
1449fn to_cmd_variable(input: String) -> String {
1450    if let Some(var_str) = input.strip_prefix("${") {
1451        if var_str.find(':').is_none() {
1452            // If the input starts with "${", remove the trailing "}"
1453            format!("%{}%", &var_str[..var_str.len() - 1])
1454        } else {
1455            // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
1456            // which will result in the task failing to run in such cases.
1457            input
1458        }
1459    } else if let Some(var_str) = input.strip_prefix('$') {
1460        // If the input starts with "$", directly append to "$env:"
1461        format!("%{}%", var_str)
1462    } else {
1463        // If no prefix is found, return the input as is
1464        input
1465    }
1466}
1467
1468/// Convert `${SOME_VAR}`, `$SOME_VAR` to `$env:SOME_VAR`.
1469#[inline]
1470#[cfg(target_os = "windows")]
1471fn to_powershell_variable(input: String) -> String {
1472    if let Some(var_str) = input.strip_prefix("${") {
1473        if var_str.find(':').is_none() {
1474            // If the input starts with "${", remove the trailing "}"
1475            format!("$env:{}", &var_str[..var_str.len() - 1])
1476        } else {
1477            // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
1478            // which will result in the task failing to run in such cases.
1479            input
1480        }
1481    } else if let Some(var_str) = input.strip_prefix('$') {
1482        // If the input starts with "$", directly append to "$env:"
1483        format!("$env:{}", var_str)
1484    } else {
1485        // If no prefix is found, return the input as is
1486        input
1487    }
1488}
1489
1490#[cfg(target_os = "windows")]
1491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1492enum WindowsShellType {
1493    Powershell,
1494    Cmd,
1495    Other,
1496}