terminal_panel.rs

   1use std::{cmp, ops::ControlFlow, path::PathBuf, process::ExitStatus, sync::Arc, time::Duration};
   2
   3use crate::{
   4    TerminalView, default_working_directory,
   5    persistence::{
   6        SerializedItems, SerializedTerminalPanel, deserialize_terminal_panel, serialize_pane_group,
   7    },
   8};
   9use breadcrumbs::Breadcrumbs;
  10use collections::HashMap;
  11use db::kvp::KEY_VALUE_STORE;
  12use futures::{channel::oneshot, future::join_all};
  13use gpui::{
  14    Action, AnyView, App, AsyncApp, AsyncWindowContext, Context, Corner, Entity, EventEmitter,
  15    ExternalPaths, FocusHandle, Focusable, IntoElement, ParentElement, Pixels, Render, Styled,
  16    Task, WeakEntity, Window, actions,
  17};
  18use itertools::Itertools;
  19use project::{Fs, Project, ProjectEntryId};
  20use search::{BufferSearchBar, buffer_search::DivRegistrar};
  21use settings::{Settings, TerminalDockPosition};
  22use task::{RevealStrategy, RevealTarget, Shell, ShellBuilder, SpawnInTerminal, TaskId};
  23use terminal::{Terminal, terminal_settings::TerminalSettings};
  24use ui::{
  25    ButtonLike, Clickable, ContextMenu, FluentBuilder, PopoverMenu, SplitButton, Toggleable,
  26    Tooltip, prelude::*,
  27};
  28use util::{ResultExt, TryFutureExt};
  29use workspace::{
  30    ActivateNextPane, ActivatePane, ActivatePaneDown, ActivatePaneLeft, ActivatePaneRight,
  31    ActivatePaneUp, ActivatePreviousPane, DraggedSelection, DraggedTab, ItemId, MoveItemToPane,
  32    MoveItemToPaneInDirection, MovePaneDown, MovePaneLeft, MovePaneRight, MovePaneUp, NewTerminal,
  33    Pane, PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitRight, SplitUp, SwapPaneDown,
  34    SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom, Workspace,
  35    dock::{DockPosition, Panel, PanelEvent, PanelHandle},
  36    item::SerializableItem,
  37    move_active_item, move_item, pane,
  38};
  39
  40use anyhow::{Result, anyhow};
  41use zed_actions::assistant::InlineAssist;
  42
  43const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
  44
  45actions!(
  46    terminal_panel,
  47    [
  48        /// Toggles the terminal panel.
  49        Toggle,
  50        /// Toggles focus on the terminal panel.
  51        ToggleFocus
  52    ]
  53);
  54
  55pub fn init(cx: &mut App) {
  56    cx.observe_new(
  57        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
  58            workspace.register_action(TerminalPanel::new_terminal);
  59            workspace.register_action(TerminalPanel::open_terminal);
  60            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
  61                if is_enabled_in_workspace(workspace, cx) {
  62                    workspace.toggle_panel_focus::<TerminalPanel>(window, cx);
  63                }
  64            });
  65            workspace.register_action(|workspace, _: &Toggle, window, cx| {
  66                if is_enabled_in_workspace(workspace, cx) {
  67                    if !workspace.toggle_panel_focus::<TerminalPanel>(window, cx) {
  68                        workspace.close_panel::<TerminalPanel>(window, cx);
  69                    }
  70                }
  71            });
  72        },
  73    )
  74    .detach();
  75}
  76
  77pub struct TerminalPanel {
  78    pub(crate) active_pane: Entity<Pane>,
  79    pub(crate) center: PaneGroup,
  80    fs: Arc<dyn Fs>,
  81    workspace: WeakEntity<Workspace>,
  82    pub(crate) width: Option<Pixels>,
  83    pub(crate) height: Option<Pixels>,
  84    pending_serialization: Task<Option<()>>,
  85    pending_terminals_to_add: usize,
  86    deferred_tasks: HashMap<TaskId, Task<()>>,
  87    assistant_enabled: bool,
  88    assistant_tab_bar_button: Option<AnyView>,
  89    active: bool,
  90}
  91
  92impl TerminalPanel {
  93    pub fn new(workspace: &Workspace, window: &mut Window, cx: &mut Context<Self>) -> Self {
  94        let project = workspace.project();
  95        let pane = new_terminal_pane(workspace.weak_handle(), project.clone(), false, window, cx);
  96        let center = PaneGroup::new(pane.clone());
  97        let terminal_panel = Self {
  98            center,
  99            active_pane: pane,
 100            fs: workspace.app_state().fs.clone(),
 101            workspace: workspace.weak_handle(),
 102            pending_serialization: Task::ready(None),
 103            width: None,
 104            height: None,
 105            pending_terminals_to_add: 0,
 106            deferred_tasks: HashMap::default(),
 107            assistant_enabled: false,
 108            assistant_tab_bar_button: None,
 109            active: false,
 110        };
 111        terminal_panel.apply_tab_bar_buttons(&terminal_panel.active_pane, cx);
 112        terminal_panel
 113    }
 114
 115    pub fn set_assistant_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 116        self.assistant_enabled = enabled;
 117        if enabled {
 118            let focus_handle = self
 119                .active_pane
 120                .read(cx)
 121                .active_item()
 122                .map(|item| item.item_focus_handle(cx))
 123                .unwrap_or(self.focus_handle(cx));
 124            self.assistant_tab_bar_button = Some(
 125                cx.new(move |_| InlineAssistTabBarButton { focus_handle })
 126                    .into(),
 127            );
 128        } else {
 129            self.assistant_tab_bar_button = None;
 130        }
 131        for pane in self.center.panes() {
 132            self.apply_tab_bar_buttons(pane, cx);
 133        }
 134    }
 135
 136    fn apply_tab_bar_buttons(&self, terminal_pane: &Entity<Pane>, cx: &mut Context<Self>) {
 137        let assistant_tab_bar_button = self.assistant_tab_bar_button.clone();
 138        terminal_pane.update(cx, |pane, cx| {
 139            pane.set_render_tab_bar_buttons(cx, move |pane, window, cx| {
 140                let split_context = pane
 141                    .active_item()
 142                    .and_then(|item| item.downcast::<TerminalView>())
 143                    .map(|terminal_view| terminal_view.read(cx).focus_handle.clone());
 144                if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
 145                    return (None, None);
 146                }
 147                let focus_handle = pane.focus_handle(cx);
 148                let right_children = h_flex()
 149                    .gap(DynamicSpacing::Base02.rems(cx))
 150                    .child(
 151                        PopoverMenu::new("terminal-tab-bar-popover-menu")
 152                            .trigger_with_tooltip(
 153                                IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
 154                                Tooltip::text("New…"),
 155                            )
 156                            .anchor(Corner::TopRight)
 157                            .with_handle(pane.new_item_context_menu_handle.clone())
 158                            .menu(move |window, cx| {
 159                                let focus_handle = focus_handle.clone();
 160                                let menu = ContextMenu::build(window, cx, |menu, _, _| {
 161                                    menu.context(focus_handle.clone())
 162                                        .action(
 163                                            "New Terminal",
 164                                            workspace::NewTerminal.boxed_clone(),
 165                                        )
 166                                        // We want the focus to go back to terminal panel once task modal is dismissed,
 167                                        // hence we focus that first. Otherwise, we'd end up without a focused element, as
 168                                        // context menu will be gone the moment we spawn the modal.
 169                                        .action(
 170                                            "Spawn Task",
 171                                            zed_actions::Spawn::modal().boxed_clone(),
 172                                        )
 173                                });
 174
 175                                Some(menu)
 176                            }),
 177                    )
 178                    .children(assistant_tab_bar_button.clone())
 179                    .child(
 180                        PopoverMenu::new("terminal-pane-tab-bar-split")
 181                            .trigger_with_tooltip(
 182                                IconButton::new("terminal-pane-split", IconName::Split)
 183                                    .icon_size(IconSize::Small),
 184                                Tooltip::text("Split Pane"),
 185                            )
 186                            .anchor(Corner::TopRight)
 187                            .with_handle(pane.split_item_context_menu_handle.clone())
 188                            .menu({
 189                                move |window, cx| {
 190                                    ContextMenu::build(window, cx, |menu, _, _| {
 191                                        menu.when_some(
 192                                            split_context.clone(),
 193                                            |menu, split_context| menu.context(split_context),
 194                                        )
 195                                        .action("Split Right", SplitRight.boxed_clone())
 196                                        .action("Split Left", SplitLeft.boxed_clone())
 197                                        .action("Split Up", SplitUp.boxed_clone())
 198                                        .action("Split Down", SplitDown.boxed_clone())
 199                                    })
 200                                    .into()
 201                                }
 202                            }),
 203                    )
 204                    .child({
 205                        let zoomed = pane.is_zoomed();
 206                        IconButton::new("toggle_zoom", IconName::Maximize)
 207                            .icon_size(IconSize::Small)
 208                            .toggle_state(zoomed)
 209                            .selected_icon(IconName::Minimize)
 210                            .on_click(cx.listener(|pane, _, window, cx| {
 211                                pane.toggle_zoom(&workspace::ToggleZoom, window, cx);
 212                            }))
 213                            .tooltip(move |_window, cx| {
 214                                Tooltip::for_action(
 215                                    if zoomed { "Zoom Out" } else { "Zoom In" },
 216                                    &ToggleZoom,
 217                                    cx,
 218                                )
 219                            })
 220                    })
 221                    .into_any_element()
 222                    .into();
 223                (None, right_children)
 224            });
 225        });
 226    }
 227
 228    fn serialization_key(workspace: &Workspace) -> Option<String> {
 229        workspace
 230            .database_id()
 231            .map(|id| i64::from(id).to_string())
 232            .or(workspace.session_id())
 233            .map(|id| format!("{:?}-{:?}", TERMINAL_PANEL_KEY, id))
 234    }
 235
 236    pub async fn load(
 237        workspace: WeakEntity<Workspace>,
 238        mut cx: AsyncWindowContext,
 239    ) -> Result<Entity<Self>> {
 240        let mut terminal_panel = None;
 241
 242        if let Some((database_id, serialization_key)) = workspace
 243            .read_with(&cx, |workspace, _| {
 244                workspace
 245                    .database_id()
 246                    .zip(TerminalPanel::serialization_key(workspace))
 247            })
 248            .ok()
 249            .flatten()
 250            && let Some(serialized_panel) = cx
 251                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 252                .await
 253                .log_err()
 254                .flatten()
 255                .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
 256                .transpose()
 257                .log_err()
 258                .flatten()
 259            && let Ok(serialized) = workspace
 260                .update_in(&mut cx, |workspace, window, cx| {
 261                    deserialize_terminal_panel(
 262                        workspace.weak_handle(),
 263                        workspace.project().clone(),
 264                        database_id,
 265                        serialized_panel,
 266                        window,
 267                        cx,
 268                    )
 269                })?
 270                .await
 271        {
 272            terminal_panel = Some(serialized);
 273        }
 274
 275        let terminal_panel = if let Some(panel) = terminal_panel {
 276            panel
 277        } else {
 278            workspace.update_in(&mut cx, |workspace, window, cx| {
 279                cx.new(|cx| TerminalPanel::new(workspace, window, cx))
 280            })?
 281        };
 282
 283        if let Some(workspace) = workspace.upgrade() {
 284            workspace
 285                .update(&mut cx, |workspace, _| {
 286                    workspace.set_terminal_provider(TerminalProvider(terminal_panel.clone()))
 287                })
 288                .ok();
 289        }
 290
 291        // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
 292        if let Some(workspace) = workspace.upgrade() {
 293            let cleanup_task = workspace.update_in(&mut cx, |workspace, window, cx| {
 294                let alive_item_ids = terminal_panel
 295                    .read(cx)
 296                    .center
 297                    .panes()
 298                    .into_iter()
 299                    .flat_map(|pane| pane.read(cx).items())
 300                    .map(|item| item.item_id().as_u64() as ItemId)
 301                    .collect();
 302                workspace.database_id().map(|workspace_id| {
 303                    TerminalView::cleanup(workspace_id, alive_item_ids, window, cx)
 304                })
 305            })?;
 306            if let Some(task) = cleanup_task {
 307                task.await.log_err();
 308            }
 309        }
 310
 311        if let Some(workspace) = workspace.upgrade() {
 312            let should_focus = workspace
 313                .update_in(&mut cx, |workspace, window, cx| {
 314                    workspace.active_item(cx).is_none()
 315                        && workspace
 316                            .is_dock_at_position_open(terminal_panel.position(window, cx), cx)
 317                })
 318                .unwrap_or(false);
 319
 320            if should_focus {
 321                terminal_panel
 322                    .update_in(&mut cx, |panel, window, cx| {
 323                        panel.active_pane.update(cx, |pane, cx| {
 324                            pane.focus_active_item(window, cx);
 325                        });
 326                    })
 327                    .ok();
 328            }
 329        }
 330        Ok(terminal_panel)
 331    }
 332
 333    fn handle_pane_event(
 334        &mut self,
 335        pane: &Entity<Pane>,
 336        event: &pane::Event,
 337        window: &mut Window,
 338        cx: &mut Context<Self>,
 339    ) {
 340        match event {
 341            pane::Event::ActivateItem { .. } => self.serialize(cx),
 342            pane::Event::RemovedItem { .. } => self.serialize(cx),
 343            pane::Event::Remove { focus_on_pane } => {
 344                let pane_count_before_removal = self.center.panes().len();
 345                let _removal_result = self.center.remove(pane, cx);
 346                if pane_count_before_removal == 1 {
 347                    self.center.first_pane().update(cx, |pane, cx| {
 348                        pane.set_zoomed(false, cx);
 349                    });
 350                    cx.emit(PanelEvent::Close);
 351                } else if let Some(focus_on_pane) =
 352                    focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
 353                {
 354                    focus_on_pane.focus_handle(cx).focus(window, cx);
 355                }
 356            }
 357            pane::Event::ZoomIn => {
 358                for pane in self.center.panes() {
 359                    pane.update(cx, |pane, cx| {
 360                        pane.set_zoomed(true, cx);
 361                    })
 362                }
 363                cx.emit(PanelEvent::ZoomIn);
 364                cx.notify();
 365            }
 366            pane::Event::ZoomOut => {
 367                for pane in self.center.panes() {
 368                    pane.update(cx, |pane, cx| {
 369                        pane.set_zoomed(false, cx);
 370                    })
 371                }
 372                cx.emit(PanelEvent::ZoomOut);
 373                cx.notify();
 374            }
 375            pane::Event::AddItem { item } => {
 376                if let Some(workspace) = self.workspace.upgrade() {
 377                    workspace.update(cx, |workspace, cx| {
 378                        item.added_to_pane(workspace, pane.clone(), window, cx)
 379                    })
 380                }
 381                self.serialize(cx);
 382            }
 383            &pane::Event::Split {
 384                direction,
 385                clone_active_item,
 386            } => {
 387                if clone_active_item {
 388                    let fut = self.new_pane_with_cloned_active_terminal(window, cx);
 389                    let pane = pane.clone();
 390                    cx.spawn_in(window, async move |panel, cx| {
 391                        let Some(new_pane) = fut.await else {
 392                            return;
 393                        };
 394                        panel
 395                            .update_in(cx, |panel, window, cx| {
 396                                panel
 397                                    .center
 398                                    .split(&pane, &new_pane, direction, cx)
 399                                    .log_err();
 400                                window.focus(&new_pane.focus_handle(cx), cx);
 401                            })
 402                            .ok();
 403                    })
 404                    .detach();
 405                } else {
 406                    let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx))
 407                    else {
 408                        return;
 409                    };
 410                    let Ok(project) = self
 411                        .workspace
 412                        .update(cx, |workspace, _| workspace.project().clone())
 413                    else {
 414                        return;
 415                    };
 416                    let new_pane =
 417                        new_terminal_pane(self.workspace.clone(), project, false, window, cx);
 418                    new_pane.update(cx, |pane, cx| {
 419                        pane.add_item(item, true, true, None, window, cx);
 420                    });
 421                    self.center.split(&pane, &new_pane, direction, cx).log_err();
 422                    window.focus(&new_pane.focus_handle(cx), cx);
 423                }
 424            }
 425            pane::Event::Focus => {
 426                self.active_pane = pane.clone();
 427            }
 428            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {
 429                self.serialize(cx);
 430            }
 431
 432            _ => {}
 433        }
 434    }
 435
 436    fn new_pane_with_cloned_active_terminal(
 437        &mut self,
 438        window: &mut Window,
 439        cx: &mut Context<Self>,
 440    ) -> Task<Option<Entity<Pane>>> {
 441        let Some(workspace) = self.workspace.upgrade() else {
 442            return Task::ready(None);
 443        };
 444        let workspace = workspace.read(cx);
 445        let database_id = workspace.database_id();
 446        let weak_workspace = self.workspace.clone();
 447        let project = workspace.project().clone();
 448        let active_pane = &self.active_pane;
 449        let terminal_view = active_pane
 450            .read(cx)
 451            .active_item()
 452            .and_then(|item| item.downcast::<TerminalView>());
 453        let working_directory = terminal_view
 454            .as_ref()
 455            .and_then(|terminal_view| {
 456                terminal_view
 457                    .read(cx)
 458                    .terminal()
 459                    .read(cx)
 460                    .working_directory()
 461            })
 462            .or_else(|| default_working_directory(workspace, cx));
 463        let is_zoomed = active_pane.read(cx).is_zoomed();
 464        cx.spawn_in(window, async move |panel, cx| {
 465            let terminal = project
 466                .update(cx, |project, cx| match terminal_view {
 467                    Some(view) => project.clone_terminal(
 468                        &view.read(cx).terminal.clone(),
 469                        cx,
 470                        working_directory,
 471                    ),
 472                    None => project.create_terminal_shell(working_directory, cx),
 473                })
 474                .ok()?
 475                .await
 476                .log_err()?;
 477
 478            panel
 479                .update_in(cx, move |terminal_panel, window, cx| {
 480                    let terminal_view = Box::new(cx.new(|cx| {
 481                        TerminalView::new(
 482                            terminal.clone(),
 483                            weak_workspace.clone(),
 484                            database_id,
 485                            project.downgrade(),
 486                            window,
 487                            cx,
 488                        )
 489                    }));
 490                    let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
 491                    terminal_panel.apply_tab_bar_buttons(&pane, cx);
 492                    pane.update(cx, |pane, cx| {
 493                        pane.add_item(terminal_view, true, true, None, window, cx);
 494                    });
 495                    Some(pane)
 496                })
 497                .ok()
 498                .flatten()
 499        })
 500    }
 501
 502    pub fn open_terminal(
 503        workspace: &mut Workspace,
 504        action: &workspace::OpenTerminal,
 505        window: &mut Window,
 506        cx: &mut Context<Workspace>,
 507    ) {
 508        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 509            return;
 510        };
 511
 512        terminal_panel
 513            .update(cx, |panel, cx| {
 514                panel.add_terminal_shell(
 515                    Some(action.working_directory.clone()),
 516                    RevealStrategy::Always,
 517                    window,
 518                    cx,
 519                )
 520            })
 521            .detach_and_log_err(cx);
 522    }
 523
 524    pub fn spawn_task(
 525        &mut self,
 526        task: &SpawnInTerminal,
 527        window: &mut Window,
 528        cx: &mut Context<Self>,
 529    ) -> Task<Result<WeakEntity<Terminal>>> {
 530        let Some(workspace) = self.workspace.upgrade() else {
 531            return Task::ready(Err(anyhow!("failed to read workspace")));
 532        };
 533
 534        let project = workspace.read(cx).project().read(cx);
 535
 536        if project.is_via_collab() {
 537            return Task::ready(Err(anyhow!("cannot spawn tasks as a guest")));
 538        }
 539
 540        let remote_client = project.remote_client();
 541        let is_windows = project.path_style(cx).is_windows();
 542        let remote_shell = remote_client
 543            .as_ref()
 544            .and_then(|remote_client| remote_client.read(cx).shell());
 545
 546        let shell = if let Some(remote_shell) = remote_shell
 547            && task.shell == Shell::System
 548        {
 549            Shell::Program(remote_shell)
 550        } else {
 551            task.shell.clone()
 552        };
 553
 554        let builder = ShellBuilder::new(&shell, is_windows);
 555        let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
 556        let (command, args) = builder.build_no_quote(task.command.clone(), &task.args);
 557
 558        let task = SpawnInTerminal {
 559            command_label,
 560            command: Some(command),
 561            args,
 562            ..task.clone()
 563        };
 564
 565        if task.allow_concurrent_runs && task.use_new_terminal {
 566            return self.spawn_in_new_terminal(task, window, cx);
 567        }
 568
 569        let mut terminals_for_task = self.terminals_for_task(&task.full_label, cx);
 570        let Some(existing) = terminals_for_task.pop() else {
 571            return self.spawn_in_new_terminal(task, window, cx);
 572        };
 573
 574        let (existing_item_index, task_pane, existing_terminal) = existing;
 575        if task.allow_concurrent_runs {
 576            return self.replace_terminal(
 577                task,
 578                task_pane,
 579                existing_item_index,
 580                existing_terminal,
 581                window,
 582                cx,
 583            );
 584        }
 585
 586        let (tx, rx) = oneshot::channel();
 587
 588        self.deferred_tasks.insert(
 589            task.id.clone(),
 590            cx.spawn_in(window, async move |terminal_panel, cx| {
 591                wait_for_terminals_tasks(terminals_for_task, cx).await;
 592                let task = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 593                    if task.use_new_terminal {
 594                        terminal_panel.spawn_in_new_terminal(task, window, cx)
 595                    } else {
 596                        terminal_panel.replace_terminal(
 597                            task,
 598                            task_pane,
 599                            existing_item_index,
 600                            existing_terminal,
 601                            window,
 602                            cx,
 603                        )
 604                    }
 605                });
 606                if let Ok(task) = task {
 607                    tx.send(task.await).ok();
 608                }
 609            }),
 610        );
 611
 612        cx.spawn(async move |_, _| rx.await?)
 613    }
 614
 615    fn spawn_in_new_terminal(
 616        &mut self,
 617        spawn_task: SpawnInTerminal,
 618        window: &mut Window,
 619        cx: &mut Context<Self>,
 620    ) -> Task<Result<WeakEntity<Terminal>>> {
 621        let reveal = spawn_task.reveal;
 622        let reveal_target = spawn_task.reveal_target;
 623        match reveal_target {
 624            RevealTarget::Center => self
 625                .workspace
 626                .update(cx, |workspace, cx| {
 627                    Self::add_center_terminal(workspace, window, cx, |project, cx| {
 628                        project.create_terminal_task(spawn_task, cx)
 629                    })
 630                })
 631                .unwrap_or_else(|e| Task::ready(Err(e))),
 632            RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
 633        }
 634    }
 635
 636    /// Create a new Terminal in the current working directory or the user's home directory
 637    fn new_terminal(
 638        workspace: &mut Workspace,
 639        _: &workspace::NewTerminal,
 640        window: &mut Window,
 641        cx: &mut Context<Workspace>,
 642    ) {
 643        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 644            return;
 645        };
 646
 647        terminal_panel
 648            .update(cx, |this, cx| {
 649                this.add_terminal_shell(
 650                    default_working_directory(workspace, cx),
 651                    RevealStrategy::Always,
 652                    window,
 653                    cx,
 654                )
 655            })
 656            .detach_and_log_err(cx);
 657    }
 658
 659    fn terminals_for_task(
 660        &self,
 661        label: &str,
 662        cx: &mut App,
 663    ) -> Vec<(usize, Entity<Pane>, Entity<TerminalView>)> {
 664        let Some(workspace) = self.workspace.upgrade() else {
 665            return Vec::new();
 666        };
 667
 668        let pane_terminal_views = |pane: Entity<Pane>| {
 669            pane.read(cx)
 670                .items()
 671                .enumerate()
 672                .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
 673                .filter_map(|(index, terminal_view)| {
 674                    let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
 675                    if &task_state.spawned_task.full_label == label {
 676                        Some((index, terminal_view))
 677                    } else {
 678                        None
 679                    }
 680                })
 681                .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
 682        };
 683
 684        self.center
 685            .panes()
 686            .into_iter()
 687            .cloned()
 688            .flat_map(pane_terminal_views)
 689            .chain(
 690                workspace
 691                    .read(cx)
 692                    .panes()
 693                    .iter()
 694                    .cloned()
 695                    .flat_map(pane_terminal_views),
 696            )
 697            .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
 698            .collect()
 699    }
 700
 701    fn activate_terminal_view(
 702        &self,
 703        pane: &Entity<Pane>,
 704        item_index: usize,
 705        focus: bool,
 706        window: &mut Window,
 707        cx: &mut App,
 708    ) {
 709        pane.update(cx, |pane, cx| {
 710            pane.activate_item(item_index, true, focus, window, cx)
 711        })
 712    }
 713
 714    pub fn add_center_terminal(
 715        workspace: &mut Workspace,
 716        window: &mut Window,
 717        cx: &mut Context<Workspace>,
 718        create_terminal: impl FnOnce(
 719            &mut Project,
 720            &mut Context<Project>,
 721        ) -> Task<Result<Entity<Terminal>>>
 722        + 'static,
 723    ) -> Task<Result<WeakEntity<Terminal>>> {
 724        if !is_enabled_in_workspace(workspace, cx) {
 725            return Task::ready(Err(anyhow!(
 726                "terminal not yet supported for remote projects"
 727            )));
 728        }
 729        let project = workspace.project().downgrade();
 730        cx.spawn_in(window, async move |workspace, cx| {
 731            let terminal = project.update(cx, create_terminal)?.await?;
 732
 733            workspace.update_in(cx, |workspace, window, cx| {
 734                let terminal_view = cx.new(|cx| {
 735                    TerminalView::new(
 736                        terminal.clone(),
 737                        workspace.weak_handle(),
 738                        workspace.database_id(),
 739                        workspace.project().downgrade(),
 740                        window,
 741                        cx,
 742                    )
 743                });
 744                workspace.add_item_to_active_pane(Box::new(terminal_view), None, true, window, cx);
 745            })?;
 746            Ok(terminal.downgrade())
 747        })
 748    }
 749
 750    pub fn add_terminal_task(
 751        &mut self,
 752        task: SpawnInTerminal,
 753        reveal_strategy: RevealStrategy,
 754        window: &mut Window,
 755        cx: &mut Context<Self>,
 756    ) -> Task<Result<WeakEntity<Terminal>>> {
 757        let workspace = self.workspace.clone();
 758        cx.spawn_in(window, async move |terminal_panel, cx| {
 759            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 760                anyhow::bail!("terminal not yet supported for remote projects");
 761            }
 762            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 763                terminal_panel.pending_terminals_to_add += 1;
 764                terminal_panel.active_pane.clone()
 765            })?;
 766            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 767            let terminal = project
 768                .update(cx, |project, cx| project.create_terminal_task(task, cx))?
 769                .await?;
 770            let result = workspace.update_in(cx, |workspace, window, cx| {
 771                let terminal_view = Box::new(cx.new(|cx| {
 772                    TerminalView::new(
 773                        terminal.clone(),
 774                        workspace.weak_handle(),
 775                        workspace.database_id(),
 776                        workspace.project().downgrade(),
 777                        window,
 778                        cx,
 779                    )
 780                }));
 781
 782                match reveal_strategy {
 783                    RevealStrategy::Always => {
 784                        workspace.focus_panel::<Self>(window, cx);
 785                    }
 786                    RevealStrategy::NoFocus => {
 787                        workspace.open_panel::<Self>(window, cx);
 788                    }
 789                    RevealStrategy::Never => {}
 790                }
 791
 792                pane.update(cx, |pane, cx| {
 793                    let focus = matches!(reveal_strategy, RevealStrategy::Always);
 794                    pane.add_item(terminal_view, true, focus, None, window, cx);
 795                });
 796
 797                Ok(terminal.downgrade())
 798            })?;
 799            terminal_panel.update(cx, |terminal_panel, cx| {
 800                terminal_panel.pending_terminals_to_add =
 801                    terminal_panel.pending_terminals_to_add.saturating_sub(1);
 802                terminal_panel.serialize(cx)
 803            })?;
 804            result
 805        })
 806    }
 807
 808    fn add_terminal_shell(
 809        &mut self,
 810        cwd: Option<PathBuf>,
 811        reveal_strategy: RevealStrategy,
 812        window: &mut Window,
 813        cx: &mut Context<Self>,
 814    ) -> Task<Result<WeakEntity<Terminal>>> {
 815        let workspace = self.workspace.clone();
 816
 817        cx.spawn_in(window, async move |terminal_panel, cx| {
 818            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 819                anyhow::bail!("terminal not yet supported for collaborative projects");
 820            }
 821            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 822                terminal_panel.pending_terminals_to_add += 1;
 823                terminal_panel.active_pane.clone()
 824            })?;
 825            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 826            let terminal = project
 827                .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
 828                .await;
 829
 830            match terminal {
 831                Ok(terminal) => {
 832                    let result = workspace.update_in(cx, |workspace, window, cx| {
 833                        let terminal_view = Box::new(cx.new(|cx| {
 834                            TerminalView::new(
 835                                terminal.clone(),
 836                                workspace.weak_handle(),
 837                                workspace.database_id(),
 838                                workspace.project().downgrade(),
 839                                window,
 840                                cx,
 841                            )
 842                        }));
 843
 844                        match reveal_strategy {
 845                            RevealStrategy::Always => {
 846                                workspace.focus_panel::<Self>(window, cx);
 847                            }
 848                            RevealStrategy::NoFocus => {
 849                                workspace.open_panel::<Self>(window, cx);
 850                            }
 851                            RevealStrategy::Never => {}
 852                        }
 853
 854                        pane.update(cx, |pane, cx| {
 855                            let focus = matches!(reveal_strategy, RevealStrategy::Always);
 856                            pane.add_item(terminal_view, true, focus, None, window, cx);
 857                        });
 858
 859                        Ok(terminal.downgrade())
 860                    })?;
 861                    terminal_panel.update(cx, |terminal_panel, cx| {
 862                        terminal_panel.pending_terminals_to_add =
 863                            terminal_panel.pending_terminals_to_add.saturating_sub(1);
 864                        terminal_panel.serialize(cx)
 865                    })?;
 866                    result
 867                }
 868                Err(error) => {
 869                    pane.update_in(cx, |pane, window, cx| {
 870                        let focus = pane.has_focus(window, cx);
 871                        let failed_to_spawn = cx.new(|cx| FailedToSpawnTerminal {
 872                            error: error.to_string(),
 873                            focus_handle: cx.focus_handle(),
 874                        });
 875                        pane.add_item(Box::new(failed_to_spawn), true, focus, None, window, cx);
 876                    })?;
 877                    Err(error)
 878                }
 879            }
 880        })
 881    }
 882
 883    fn serialize(&mut self, cx: &mut Context<Self>) {
 884        let height = self.height;
 885        let width = self.width;
 886        let Some(serialization_key) = self
 887            .workspace
 888            .read_with(cx, |workspace, _| {
 889                TerminalPanel::serialization_key(workspace)
 890            })
 891            .ok()
 892            .flatten()
 893        else {
 894            return;
 895        };
 896        self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
 897            cx.background_executor()
 898                .timer(Duration::from_millis(50))
 899                .await;
 900            let terminal_panel = terminal_panel.upgrade()?;
 901            let items = terminal_panel
 902                .update(cx, |terminal_panel, cx| {
 903                    SerializedItems::WithSplits(serialize_pane_group(
 904                        &terminal_panel.center,
 905                        &terminal_panel.active_pane,
 906                        cx,
 907                    ))
 908                })
 909                .ok()?;
 910            cx.background_spawn(
 911                async move {
 912                    KEY_VALUE_STORE
 913                        .write_kvp(
 914                            serialization_key,
 915                            serde_json::to_string(&SerializedTerminalPanel {
 916                                items,
 917                                active_item_id: None,
 918                                height,
 919                                width,
 920                            })?,
 921                        )
 922                        .await?;
 923                    anyhow::Ok(())
 924                }
 925                .log_err(),
 926            )
 927            .await;
 928            Some(())
 929        });
 930    }
 931
 932    fn replace_terminal(
 933        &self,
 934        spawn_task: SpawnInTerminal,
 935        task_pane: Entity<Pane>,
 936        terminal_item_index: usize,
 937        terminal_to_replace: Entity<TerminalView>,
 938        window: &mut Window,
 939        cx: &mut Context<Self>,
 940    ) -> Task<Result<WeakEntity<Terminal>>> {
 941        let reveal = spawn_task.reveal;
 942        let task_workspace = self.workspace.clone();
 943        cx.spawn_in(window, async move |terminal_panel, cx| {
 944            let project = terminal_panel.update(cx, |this, cx| {
 945                this.workspace
 946                    .update(cx, |workspace, _| workspace.project().clone())
 947            })??;
 948            let new_terminal = project
 949                .update(cx, |project, cx| {
 950                    project.create_terminal_task(spawn_task, cx)
 951                })?
 952                .await?;
 953            terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
 954                terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
 955            })?;
 956
 957            let reveal_target = terminal_panel.update(cx, |panel, _| {
 958                if panel.center.panes().iter().any(|p| **p == task_pane) {
 959                    RevealTarget::Dock
 960                } else {
 961                    RevealTarget::Center
 962                }
 963            })?;
 964
 965            match reveal {
 966                RevealStrategy::Always => match reveal_target {
 967                    RevealTarget::Center => {
 968                        task_workspace.update_in(cx, |workspace, window, cx| {
 969                            let did_activate = workspace.activate_item(
 970                                &terminal_to_replace,
 971                                true,
 972                                true,
 973                                window,
 974                                cx,
 975                            );
 976
 977                            anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
 978
 979                            anyhow::Ok(())
 980                        })??;
 981                    }
 982                    RevealTarget::Dock => {
 983                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 984                            terminal_panel.activate_terminal_view(
 985                                &task_pane,
 986                                terminal_item_index,
 987                                true,
 988                                window,
 989                                cx,
 990                            )
 991                        })?;
 992
 993                        cx.spawn(async move |cx| {
 994                            task_workspace
 995                                .update_in(cx, |workspace, window, cx| {
 996                                    workspace.focus_panel::<Self>(window, cx)
 997                                })
 998                                .ok()
 999                        })
1000                        .detach();
1001                    }
1002                },
1003                RevealStrategy::NoFocus => match reveal_target {
1004                    RevealTarget::Center => {
1005                        task_workspace.update_in(cx, |workspace, window, cx| {
1006                            workspace.active_pane().focus_handle(cx).focus(window, cx);
1007                        })?;
1008                    }
1009                    RevealTarget::Dock => {
1010                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1011                            terminal_panel.activate_terminal_view(
1012                                &task_pane,
1013                                terminal_item_index,
1014                                false,
1015                                window,
1016                                cx,
1017                            )
1018                        })?;
1019
1020                        cx.spawn(async move |cx| {
1021                            task_workspace
1022                                .update_in(cx, |workspace, window, cx| {
1023                                    workspace.open_panel::<Self>(window, cx)
1024                                })
1025                                .ok()
1026                        })
1027                        .detach();
1028                    }
1029                },
1030                RevealStrategy::Never => {}
1031            }
1032
1033            Ok(new_terminal.downgrade())
1034        })
1035    }
1036
1037    fn has_no_terminals(&self, cx: &App) -> bool {
1038        self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1039    }
1040
1041    pub fn assistant_enabled(&self) -> bool {
1042        self.assistant_enabled
1043    }
1044
1045    fn is_enabled(&self, cx: &App) -> bool {
1046        self.workspace
1047            .upgrade()
1048            .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1049    }
1050
1051    fn activate_pane_in_direction(
1052        &mut self,
1053        direction: SplitDirection,
1054        window: &mut Window,
1055        cx: &mut Context<Self>,
1056    ) {
1057        if let Some(pane) = self
1058            .center
1059            .find_pane_in_direction(&self.active_pane, direction, cx)
1060        {
1061            window.focus(&pane.focus_handle(cx), cx);
1062        } else {
1063            self.workspace
1064                .update(cx, |workspace, cx| {
1065                    workspace.activate_pane_in_direction(direction, window, cx)
1066                })
1067                .ok();
1068        }
1069    }
1070
1071    fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1072        if let Some(to) = self
1073            .center
1074            .find_pane_in_direction(&self.active_pane, direction, cx)
1075            .cloned()
1076        {
1077            self.center.swap(&self.active_pane, &to, cx);
1078            cx.notify();
1079        }
1080    }
1081
1082    fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1083        if self
1084            .center
1085            .move_to_border(&self.active_pane, direction, cx)
1086            .unwrap()
1087        {
1088            cx.notify();
1089        }
1090    }
1091}
1092
1093fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1094    workspace.project().read(cx).supports_terminal(cx)
1095}
1096
1097pub fn new_terminal_pane(
1098    workspace: WeakEntity<Workspace>,
1099    project: Entity<Project>,
1100    zoomed: bool,
1101    window: &mut Window,
1102    cx: &mut Context<TerminalPanel>,
1103) -> Entity<Pane> {
1104    let is_local = project.read(cx).is_local();
1105    let terminal_panel = cx.entity();
1106    let pane = cx.new(|cx| {
1107        let mut pane = Pane::new(
1108            workspace.clone(),
1109            project.clone(),
1110            Default::default(),
1111            None,
1112            NewTerminal.boxed_clone(),
1113            false,
1114            window,
1115            cx,
1116        );
1117        pane.set_zoomed(zoomed, cx);
1118        pane.set_can_navigate(false, cx);
1119        pane.display_nav_history_buttons(None);
1120        pane.set_should_display_tab_bar(|_, _| true);
1121        pane.set_zoom_out_on_close(false);
1122
1123        let split_closure_terminal_panel = terminal_panel.downgrade();
1124        pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1125            if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1126                let is_current_pane = tab.pane == cx.entity();
1127                let Some(can_drag_away) = split_closure_terminal_panel
1128                    .read_with(cx, |terminal_panel, _| {
1129                        let current_panes = terminal_panel.center.panes();
1130                        !current_panes.contains(&&tab.pane)
1131                            || current_panes.len() > 1
1132                            || (!is_current_pane || pane.items_len() > 1)
1133                    })
1134                    .ok()
1135                else {
1136                    return false;
1137                };
1138                if can_drag_away {
1139                    let item = if is_current_pane {
1140                        pane.item_for_index(tab.ix)
1141                    } else {
1142                        tab.pane.read(cx).item_for_index(tab.ix)
1143                    };
1144                    if let Some(item) = item {
1145                        return item.downcast::<TerminalView>().is_some();
1146                    }
1147                }
1148            }
1149            false
1150        })));
1151
1152        let buffer_search_bar = cx.new(|cx| {
1153            search::BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx)
1154        });
1155        let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1156        pane.toolbar().update(cx, |toolbar, cx| {
1157            toolbar.add_item(buffer_search_bar, window, cx);
1158            toolbar.add_item(breadcrumbs, window, cx);
1159        });
1160
1161        let drop_closure_project = project.downgrade();
1162        let drop_closure_terminal_panel = terminal_panel.downgrade();
1163        pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1164            let Some(project) = drop_closure_project.upgrade() else {
1165                return ControlFlow::Break(());
1166            };
1167            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1168                let this_pane = cx.entity();
1169                let item = if tab.pane == this_pane {
1170                    pane.item_for_index(tab.ix)
1171                } else {
1172                    tab.pane.read(cx).item_for_index(tab.ix)
1173                };
1174                if let Some(item) = item {
1175                    if item.downcast::<TerminalView>().is_some() {
1176                        let source = tab.pane.clone();
1177                        let item_id_to_move = item.item_id();
1178
1179                        // If no split direction, let the regular pane drop handler take care of it
1180                        let Some(split_direction) = pane.drag_split_direction() else {
1181                            return ControlFlow::Continue(());
1182                        };
1183
1184                        // Gather data synchronously before deferring
1185                        let is_zoomed = drop_closure_terminal_panel
1186                            .upgrade()
1187                            .map(|terminal_panel| {
1188                                let terminal_panel = terminal_panel.read(cx);
1189                                if terminal_panel.active_pane == this_pane {
1190                                    pane.is_zoomed()
1191                                } else {
1192                                    terminal_panel.active_pane.read(cx).is_zoomed()
1193                                }
1194                            })
1195                            .unwrap_or(false);
1196
1197                        let workspace = workspace.clone();
1198                        let terminal_panel = drop_closure_terminal_panel.clone();
1199
1200                        // Defer the split operation to avoid re-entrancy panic.
1201                        // The pane may be the one currently being updated, so we cannot
1202                        // call mark_positions (via split) synchronously.
1203                        cx.spawn_in(window, async move |_, cx| {
1204                            cx.update(|window, cx| {
1205                                let Ok(new_pane) =
1206                                    terminal_panel.update(cx, |terminal_panel, cx| {
1207                                        let new_pane = new_terminal_pane(
1208                                            workspace, project, is_zoomed, window, cx,
1209                                        );
1210                                        terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1211                                        terminal_panel.center.split(
1212                                            &this_pane,
1213                                            &new_pane,
1214                                            split_direction,
1215                                            cx,
1216                                        )?;
1217                                        anyhow::Ok(new_pane)
1218                                    })
1219                                else {
1220                                    return;
1221                                };
1222
1223                                let Some(new_pane) = new_pane.log_err() else {
1224                                    return;
1225                                };
1226
1227                                move_item(
1228                                    &source,
1229                                    &new_pane,
1230                                    item_id_to_move,
1231                                    new_pane.read(cx).active_item_index(),
1232                                    true,
1233                                    window,
1234                                    cx,
1235                                );
1236                            })
1237                            .ok();
1238                        })
1239                        .detach();
1240                    } else if let Some(project_path) = item.project_path(cx)
1241                        && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1242                    {
1243                        add_paths_to_terminal(pane, &[entry_path], window, cx);
1244                    }
1245                }
1246            } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1247                let project = project.read(cx);
1248                let paths_to_add = selection
1249                    .items()
1250                    .map(|selected_entry| selected_entry.entry_id)
1251                    .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1252                    .filter_map(|project_path| project.absolute_path(&project_path, cx))
1253                    .collect::<Vec<_>>();
1254                if !paths_to_add.is_empty() {
1255                    add_paths_to_terminal(pane, &paths_to_add, window, cx);
1256                }
1257            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1258                if let Some(entry_path) = project
1259                    .read(cx)
1260                    .path_for_entry(entry_id, cx)
1261                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1262                {
1263                    add_paths_to_terminal(pane, &[entry_path], window, cx);
1264                }
1265            } else if is_local && let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1266                add_paths_to_terminal(pane, paths.paths(), window, cx);
1267            }
1268
1269            ControlFlow::Break(())
1270        });
1271
1272        pane
1273    });
1274
1275    cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1276        .detach();
1277    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1278
1279    pane
1280}
1281
1282async fn wait_for_terminals_tasks(
1283    terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1284    cx: &mut AsyncApp,
1285) {
1286    let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
1287        terminal
1288            .update(cx, |terminal_view, cx| {
1289                terminal_view
1290                    .terminal()
1291                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1292            })
1293            .ok()
1294    });
1295    join_all(pending_tasks).await;
1296}
1297
1298fn add_paths_to_terminal(
1299    pane: &mut Pane,
1300    paths: &[PathBuf],
1301    window: &mut Window,
1302    cx: &mut Context<Pane>,
1303) {
1304    if let Some(terminal_view) = pane
1305        .active_item()
1306        .and_then(|item| item.downcast::<TerminalView>())
1307    {
1308        window.focus(&terminal_view.focus_handle(cx), cx);
1309        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1310        new_text.push(' ');
1311        terminal_view.update(cx, |terminal_view, cx| {
1312            terminal_view.terminal().update(cx, |terminal, _| {
1313                terminal.paste(&new_text);
1314            });
1315        });
1316    }
1317}
1318
1319struct FailedToSpawnTerminal {
1320    error: String,
1321    focus_handle: FocusHandle,
1322}
1323
1324impl Focusable for FailedToSpawnTerminal {
1325    fn focus_handle(&self, _: &App) -> FocusHandle {
1326        self.focus_handle.clone()
1327    }
1328}
1329
1330impl Render for FailedToSpawnTerminal {
1331    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1332        let popover_menu = PopoverMenu::new("settings-popover")
1333            .trigger(
1334                IconButton::new("icon-button-popover", IconName::ChevronDown)
1335                    .icon_size(IconSize::XSmall),
1336            )
1337            .menu(move |window, cx| {
1338                Some(ContextMenu::build(window, cx, |context_menu, _, _| {
1339                    context_menu
1340                        .action("Open Settings", zed_actions::OpenSettings.boxed_clone())
1341                        .action(
1342                            "Edit settings.json",
1343                            zed_actions::OpenSettingsFile.boxed_clone(),
1344                        )
1345                }))
1346            })
1347            .anchor(Corner::TopRight)
1348            .offset(gpui::Point {
1349                x: px(0.0),
1350                y: px(2.0),
1351            });
1352
1353        v_flex()
1354            .track_focus(&self.focus_handle)
1355            .size_full()
1356            .p_4()
1357            .items_center()
1358            .justify_center()
1359            .bg(cx.theme().colors().editor_background)
1360            .child(
1361                v_flex()
1362                    .max_w_112()
1363                    .items_center()
1364                    .justify_center()
1365                    .text_center()
1366                    .child(Label::new("Failed to spawn terminal"))
1367                    .child(
1368                        Label::new(self.error.to_string())
1369                            .size(LabelSize::Small)
1370                            .color(Color::Muted)
1371                            .mb_4(),
1372                    )
1373                    .child(SplitButton::new(
1374                        ButtonLike::new("open-settings-ui")
1375                            .child(Label::new("Edit Settings").size(LabelSize::Small))
1376                            .on_click(|_, window, cx| {
1377                                window.dispatch_action(zed_actions::OpenSettings.boxed_clone(), cx);
1378                            }),
1379                        popover_menu.into_any_element(),
1380                    )),
1381            )
1382    }
1383}
1384
1385impl EventEmitter<()> for FailedToSpawnTerminal {}
1386
1387impl workspace::Item for FailedToSpawnTerminal {
1388    type Event = ();
1389
1390    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1391        SharedString::new_static("Failed to spawn terminal")
1392    }
1393}
1394
1395impl EventEmitter<PanelEvent> for TerminalPanel {}
1396
1397impl Render for TerminalPanel {
1398    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1399        let mut registrar = DivRegistrar::new(
1400            |panel, _, cx| {
1401                panel
1402                    .active_pane
1403                    .read(cx)
1404                    .toolbar()
1405                    .read(cx)
1406                    .item_of_type::<BufferSearchBar>()
1407            },
1408            cx,
1409        );
1410        BufferSearchBar::register(&mut registrar);
1411        let registrar = registrar.into_div();
1412        self.workspace
1413            .update(cx, |workspace, cx| {
1414                registrar.size_full().child(self.center.render(
1415                    workspace.zoomed_item(),
1416                    &workspace::PaneRenderContext {
1417                        follower_states: &HashMap::default(),
1418                        active_call: workspace.active_call(),
1419                        active_pane: &self.active_pane,
1420                        app_state: workspace.app_state(),
1421                        project: workspace.project(),
1422                        workspace: &workspace.weak_handle(),
1423                    },
1424                    window,
1425                    cx,
1426                ))
1427            })
1428            .ok()
1429            .map(|div| {
1430                div.on_action({
1431                    cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1432                        terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1433                    })
1434                })
1435                .on_action({
1436                    cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1437                        terminal_panel.activate_pane_in_direction(
1438                            SplitDirection::Right,
1439                            window,
1440                            cx,
1441                        );
1442                    })
1443                })
1444                .on_action({
1445                    cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1446                        terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1447                    })
1448                })
1449                .on_action({
1450                    cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1451                        terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1452                    })
1453                })
1454                .on_action(
1455                    cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1456                        let panes = terminal_panel.center.panes();
1457                        if let Some(ix) = panes
1458                            .iter()
1459                            .position(|pane| **pane == terminal_panel.active_pane)
1460                        {
1461                            let next_ix = (ix + 1) % panes.len();
1462                            window.focus(&panes[next_ix].focus_handle(cx), cx);
1463                        }
1464                    }),
1465                )
1466                .on_action(cx.listener(
1467                    |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1468                        let panes = terminal_panel.center.panes();
1469                        if let Some(ix) = panes
1470                            .iter()
1471                            .position(|pane| **pane == terminal_panel.active_pane)
1472                        {
1473                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1474                            window.focus(&panes[prev_ix].focus_handle(cx), cx);
1475                        }
1476                    },
1477                ))
1478                .on_action(
1479                    cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1480                        let panes = terminal_panel.center.panes();
1481                        if let Some(&pane) = panes.get(action.0) {
1482                            window.focus(&pane.read(cx).focus_handle(cx), cx);
1483                        } else {
1484                            let future =
1485                                terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
1486                            cx.spawn_in(window, async move |terminal_panel, cx| {
1487                                if let Some(new_pane) = future.await {
1488                                    _ = terminal_panel.update_in(
1489                                        cx,
1490                                        |terminal_panel, window, cx| {
1491                                            terminal_panel
1492                                                .center
1493                                                .split(
1494                                                    &terminal_panel.active_pane,
1495                                                    &new_pane,
1496                                                    SplitDirection::Right,
1497                                                    cx,
1498                                                )
1499                                                .log_err();
1500                                            let new_pane = new_pane.read(cx);
1501                                            window.focus(&new_pane.focus_handle(cx), cx);
1502                                        },
1503                                    );
1504                                }
1505                            })
1506                            .detach();
1507                        }
1508                    }),
1509                )
1510                .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1511                    terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1512                }))
1513                .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1514                    terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1515                }))
1516                .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1517                    terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1518                }))
1519                .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1520                    terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1521                }))
1522                .on_action(cx.listener(|terminal_panel, _: &MovePaneLeft, _, cx| {
1523                    terminal_panel.move_pane_to_border(SplitDirection::Left, cx);
1524                }))
1525                .on_action(cx.listener(|terminal_panel, _: &MovePaneRight, _, cx| {
1526                    terminal_panel.move_pane_to_border(SplitDirection::Right, cx);
1527                }))
1528                .on_action(cx.listener(|terminal_panel, _: &MovePaneUp, _, cx| {
1529                    terminal_panel.move_pane_to_border(SplitDirection::Up, cx);
1530                }))
1531                .on_action(cx.listener(|terminal_panel, _: &MovePaneDown, _, cx| {
1532                    terminal_panel.move_pane_to_border(SplitDirection::Down, cx);
1533                }))
1534                .on_action(
1535                    cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1536                        let Some(&target_pane) =
1537                            terminal_panel.center.panes().get(action.destination)
1538                        else {
1539                            return;
1540                        };
1541                        move_active_item(
1542                            &terminal_panel.active_pane,
1543                            target_pane,
1544                            action.focus,
1545                            true,
1546                            window,
1547                            cx,
1548                        );
1549                    }),
1550                )
1551                .on_action(cx.listener(
1552                    |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1553                        let source_pane = &terminal_panel.active_pane;
1554                        if let Some(destination_pane) = terminal_panel
1555                            .center
1556                            .find_pane_in_direction(source_pane, action.direction, cx)
1557                        {
1558                            move_active_item(
1559                                source_pane,
1560                                destination_pane,
1561                                action.focus,
1562                                true,
1563                                window,
1564                                cx,
1565                            );
1566                        };
1567                    },
1568                ))
1569            })
1570            .unwrap_or_else(|| div())
1571    }
1572}
1573
1574impl Focusable for TerminalPanel {
1575    fn focus_handle(&self, cx: &App) -> FocusHandle {
1576        self.active_pane.focus_handle(cx)
1577    }
1578}
1579
1580impl Panel for TerminalPanel {
1581    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1582        match TerminalSettings::get_global(cx).dock {
1583            TerminalDockPosition::Left => DockPosition::Left,
1584            TerminalDockPosition::Bottom => DockPosition::Bottom,
1585            TerminalDockPosition::Right => DockPosition::Right,
1586        }
1587    }
1588
1589    fn position_is_valid(&self, _: DockPosition) -> bool {
1590        true
1591    }
1592
1593    fn set_position(
1594        &mut self,
1595        position: DockPosition,
1596        _window: &mut Window,
1597        cx: &mut Context<Self>,
1598    ) {
1599        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1600            let dock = match position {
1601                DockPosition::Left => TerminalDockPosition::Left,
1602                DockPosition::Bottom => TerminalDockPosition::Bottom,
1603                DockPosition::Right => TerminalDockPosition::Right,
1604            };
1605            settings.terminal.get_or_insert_default().dock = Some(dock);
1606        });
1607    }
1608
1609    fn size(&self, window: &Window, cx: &App) -> Pixels {
1610        let settings = TerminalSettings::get_global(cx);
1611        match self.position(window, cx) {
1612            DockPosition::Left | DockPosition::Right => {
1613                self.width.unwrap_or(settings.default_width)
1614            }
1615            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1616        }
1617    }
1618
1619    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1620        match self.position(window, cx) {
1621            DockPosition::Left | DockPosition::Right => self.width = size,
1622            DockPosition::Bottom => self.height = size,
1623        }
1624        cx.notify();
1625        cx.defer_in(window, |this, _, cx| {
1626            this.serialize(cx);
1627        })
1628    }
1629
1630    fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1631        self.active_pane.read(cx).is_zoomed()
1632    }
1633
1634    fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1635        for pane in self.center.panes() {
1636            pane.update(cx, |pane, cx| {
1637                pane.set_zoomed(zoomed, cx);
1638            })
1639        }
1640        cx.notify();
1641    }
1642
1643    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1644        let old_active = self.active;
1645        self.active = active;
1646        if !active || old_active == active || !self.has_no_terminals(cx) {
1647            return;
1648        }
1649        cx.defer_in(window, |this, window, cx| {
1650            let Ok(kind) = this
1651                .workspace
1652                .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1653            else {
1654                return;
1655            };
1656
1657            this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1658                .detach_and_log_err(cx)
1659        })
1660    }
1661
1662    fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1663        let count = self
1664            .center
1665            .panes()
1666            .into_iter()
1667            .map(|pane| pane.read(cx).items_len())
1668            .sum::<usize>();
1669        if count == 0 {
1670            None
1671        } else {
1672            Some(count.to_string())
1673        }
1674    }
1675
1676    fn persistent_name() -> &'static str {
1677        "TerminalPanel"
1678    }
1679
1680    fn panel_key() -> &'static str {
1681        TERMINAL_PANEL_KEY
1682    }
1683
1684    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1685        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1686            && TerminalSettings::get_global(cx).button
1687        {
1688            Some(IconName::TerminalAlt)
1689        } else {
1690            None
1691        }
1692    }
1693
1694    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1695        Some("Terminal Panel")
1696    }
1697
1698    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1699        Box::new(ToggleFocus)
1700    }
1701
1702    fn pane(&self) -> Option<Entity<Pane>> {
1703        Some(self.active_pane.clone())
1704    }
1705
1706    fn activation_priority(&self) -> u32 {
1707        1
1708    }
1709}
1710
1711struct TerminalProvider(Entity<TerminalPanel>);
1712
1713impl workspace::TerminalProvider for TerminalProvider {
1714    fn spawn(
1715        &self,
1716        task: SpawnInTerminal,
1717        window: &mut Window,
1718        cx: &mut App,
1719    ) -> Task<Option<Result<ExitStatus>>> {
1720        let terminal_panel = self.0.clone();
1721        window.spawn(cx, async move |cx| {
1722            let terminal = terminal_panel
1723                .update_in(cx, |terminal_panel, window, cx| {
1724                    terminal_panel.spawn_task(&task, window, cx)
1725                })
1726                .ok()?
1727                .await;
1728            match terminal {
1729                Ok(terminal) => {
1730                    let exit_status = terminal
1731                        .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1732                        .ok()?
1733                        .await?;
1734                    Some(Ok(exit_status))
1735                }
1736                Err(e) => Some(Err(e)),
1737            }
1738        })
1739    }
1740}
1741
1742struct InlineAssistTabBarButton {
1743    focus_handle: FocusHandle,
1744}
1745
1746impl Render for InlineAssistTabBarButton {
1747    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1748        let focus_handle = self.focus_handle.clone();
1749        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1750            .icon_size(IconSize::Small)
1751            .on_click(cx.listener(|_, _, window, cx| {
1752                window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1753            }))
1754            .tooltip(move |_window, cx| {
1755                Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1756            })
1757    }
1758}
1759
1760#[cfg(test)]
1761mod tests {
1762    use std::num::NonZero;
1763
1764    use super::*;
1765    use gpui::{TestAppContext, UpdateGlobal as _};
1766    use pretty_assertions::assert_eq;
1767    use project::FakeFs;
1768    use settings::SettingsStore;
1769
1770    #[gpui::test]
1771    async fn test_spawn_an_empty_task(cx: &mut TestAppContext) {
1772        init_test(cx);
1773
1774        let fs = FakeFs::new(cx.executor());
1775        let project = Project::test(fs, [], cx).await;
1776        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1777
1778        let (window_handle, terminal_panel) = workspace
1779            .update(cx, |workspace, window, cx| {
1780                let window_handle = window.window_handle();
1781                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1782                (window_handle, terminal_panel)
1783            })
1784            .unwrap();
1785
1786        let task = window_handle
1787            .update(cx, |_, window, cx| {
1788                terminal_panel.update(cx, |terminal_panel, cx| {
1789                    terminal_panel.spawn_task(&SpawnInTerminal::default(), window, cx)
1790                })
1791            })
1792            .unwrap();
1793
1794        let terminal = task.await.unwrap();
1795        let expected_shell = util::get_system_shell();
1796        terminal
1797            .update(cx, |terminal, _| {
1798                let task_metadata = terminal
1799                    .task()
1800                    .expect("When spawning a task, should have the task metadata")
1801                    .spawned_task
1802                    .clone();
1803                assert_eq!(task_metadata.env, HashMap::default());
1804                assert_eq!(task_metadata.cwd, None);
1805                assert_eq!(task_metadata.shell, task::Shell::System);
1806                assert_eq!(
1807                    task_metadata.command,
1808                    Some(expected_shell.clone()),
1809                    "Empty tasks should spawn a -i shell"
1810                );
1811                assert_eq!(task_metadata.args, Vec::<String>::new());
1812                assert_eq!(
1813                    task_metadata.command_label, expected_shell,
1814                    "We show the shell launch for empty commands"
1815                );
1816            })
1817            .unwrap();
1818    }
1819
1820    #[gpui::test]
1821    async fn test_bypass_max_tabs_limit(cx: &mut TestAppContext) {
1822        init_test(cx);
1823
1824        let fs = FakeFs::new(cx.executor());
1825        let project = Project::test(fs, [], cx).await;
1826        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1827
1828        let (window_handle, terminal_panel) = workspace
1829            .update(cx, |workspace, window, cx| {
1830                let window_handle = window.window_handle();
1831                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1832                (window_handle, terminal_panel)
1833            })
1834            .unwrap();
1835
1836        set_max_tabs(cx, Some(3));
1837
1838        for _ in 0..5 {
1839            let task = window_handle
1840                .update(cx, |_, window, cx| {
1841                    terminal_panel.update(cx, |panel, cx| {
1842                        panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1843                    })
1844                })
1845                .unwrap();
1846            task.await.unwrap();
1847        }
1848
1849        cx.run_until_parked();
1850
1851        let item_count =
1852            terminal_panel.read_with(cx, |panel, cx| panel.active_pane.read(cx).items_len());
1853
1854        assert_eq!(
1855            item_count, 5,
1856            "Terminal panel should bypass max_tabs limit and have all 5 terminals"
1857        );
1858    }
1859
1860    // A complex Unix command won't be properly parsed by the Windows terminal hence omit the test there.
1861    #[cfg(unix)]
1862    #[gpui::test]
1863    async fn test_spawn_script_like_task(cx: &mut TestAppContext) {
1864        init_test(cx);
1865
1866        let fs = FakeFs::new(cx.executor());
1867        let project = Project::test(fs, [], cx).await;
1868        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1869
1870        let (window_handle, terminal_panel) = workspace
1871            .update(cx, |workspace, window, cx| {
1872                let window_handle = window.window_handle();
1873                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1874                (window_handle, terminal_panel)
1875            })
1876            .unwrap();
1877
1878        let user_command = r#"REPO_URL=$(git remote get-url origin | sed -e \"s/^git@\\(.*\\):\\(.*\\)\\.git$/https:\\/\\/\\1\\/\\2/\"); COMMIT_SHA=$(git log -1 --format=\"%H\" -- \"${ZED_RELATIVE_FILE}\"); echo \"${REPO_URL}/blob/${COMMIT_SHA}/${ZED_RELATIVE_FILE}#L${ZED_ROW}-$(echo $(($(wc -l <<< \"$ZED_SELECTED_TEXT\") + $ZED_ROW - 1)))\" | xclip -selection clipboard"#.to_string();
1879
1880        let expected_cwd = PathBuf::from("/some/work");
1881        let task = window_handle
1882            .update(cx, |_, window, cx| {
1883                terminal_panel.update(cx, |terminal_panel, cx| {
1884                    terminal_panel.spawn_task(
1885                        &SpawnInTerminal {
1886                            command: Some(user_command.clone()),
1887                            cwd: Some(expected_cwd.clone()),
1888                            ..SpawnInTerminal::default()
1889                        },
1890                        window,
1891                        cx,
1892                    )
1893                })
1894            })
1895            .unwrap();
1896
1897        let terminal = task.await.unwrap();
1898        let shell = util::get_system_shell();
1899        terminal
1900            .update(cx, |terminal, _| {
1901                let task_metadata = terminal
1902                    .task()
1903                    .expect("When spawning a task, should have the task metadata")
1904                    .spawned_task
1905                    .clone();
1906                assert_eq!(task_metadata.env, HashMap::default());
1907                assert_eq!(task_metadata.cwd, Some(expected_cwd));
1908                assert_eq!(task_metadata.shell, task::Shell::System);
1909                assert_eq!(task_metadata.command, Some(shell.clone()));
1910                assert_eq!(
1911                    task_metadata.args,
1912                    vec!["-i".to_string(), "-c".to_string(), user_command.clone(),],
1913                    "Use command should have been moved into the arguments, as we're spawning a new -i shell",
1914                );
1915                assert_eq!(
1916                    task_metadata.command_label,
1917                    format!("{shell} {interactive}-c '{user_command}'", interactive = if cfg!(windows) {""} else {"-i "}),
1918                    "We want to show to the user the entire command spawned");
1919            })
1920            .unwrap();
1921    }
1922
1923    #[gpui::test]
1924    async fn renders_error_if_default_shell_fails(cx: &mut TestAppContext) {
1925        init_test(cx);
1926
1927        cx.update(|cx| {
1928            SettingsStore::update_global(cx, |store, cx| {
1929                store.update_user_settings(cx, |settings| {
1930                    settings.terminal.get_or_insert_default().project.shell =
1931                        Some(settings::Shell::Program("asdf".to_owned()));
1932                });
1933            });
1934        });
1935
1936        let fs = FakeFs::new(cx.executor());
1937        let project = Project::test(fs, [], cx).await;
1938        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1939
1940        let (window_handle, terminal_panel) = workspace
1941            .update(cx, |workspace, window, cx| {
1942                let window_handle = window.window_handle();
1943                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1944                (window_handle, terminal_panel)
1945            })
1946            .unwrap();
1947
1948        window_handle
1949            .update(cx, |_, window, cx| {
1950                terminal_panel.update(cx, |terminal_panel, cx| {
1951                    terminal_panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1952                })
1953            })
1954            .unwrap()
1955            .await
1956            .unwrap_err();
1957
1958        window_handle
1959            .update(cx, |_, _, cx| {
1960                terminal_panel.update(cx, |terminal_panel, cx| {
1961                    assert!(
1962                        terminal_panel
1963                            .active_pane
1964                            .read(cx)
1965                            .items()
1966                            .any(|item| item.downcast::<FailedToSpawnTerminal>().is_some()),
1967                        "should spawn `FailedToSpawnTerminal` pane"
1968                    );
1969                })
1970            })
1971            .unwrap();
1972    }
1973
1974    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
1975        cx.update_global(|store: &mut SettingsStore, cx| {
1976            store.update_user_settings(cx, |settings| {
1977                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
1978            });
1979        });
1980    }
1981
1982    pub fn init_test(cx: &mut TestAppContext) {
1983        cx.update(|cx| {
1984            let store = SettingsStore::test(cx);
1985            cx.set_global(store);
1986            theme::init(theme::LoadThemes::JustBase, cx);
1987            editor::init(cx);
1988            crate::init(cx);
1989        });
1990    }
1991}