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