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 remote_client = self
 530            .workspace
 531            .update(cx, |workspace, cx| {
 532                let project = workspace.project().read(cx);
 533                if project.is_via_collab() {
 534                    Err(anyhow!("cannot spawn tasks as a guest"))
 535                } else {
 536                    Ok(project.remote_client())
 537                }
 538            })
 539            .flatten();
 540
 541        let remote_client = match remote_client {
 542            Ok(remote_client) => remote_client,
 543            Err(e) => return Task::ready(Err(e)),
 544        };
 545
 546        let remote_shell = remote_client
 547            .as_ref()
 548            .and_then(|remote_client| remote_client.read(cx).shell());
 549
 550        let shell = if let Some(remote_shell) = remote_shell
 551            && task.shell == Shell::System
 552        {
 553            Shell::Program(remote_shell)
 554        } else {
 555            task.shell.clone()
 556        };
 557
 558        let builder = ShellBuilder::new(&shell);
 559        let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
 560        let (command, args) = builder.build(task.command.clone(), &task.args);
 561
 562        let task = SpawnInTerminal {
 563            command_label,
 564            command: Some(command),
 565            args,
 566            ..task.clone()
 567        };
 568
 569        if task.allow_concurrent_runs && task.use_new_terminal {
 570            return self.spawn_in_new_terminal(task, window, cx);
 571        }
 572
 573        let mut terminals_for_task = self.terminals_for_task(&task.full_label, cx);
 574        let Some(existing) = terminals_for_task.pop() else {
 575            return self.spawn_in_new_terminal(task, window, cx);
 576        };
 577
 578        let (existing_item_index, task_pane, existing_terminal) = existing;
 579        if task.allow_concurrent_runs {
 580            return self.replace_terminal(
 581                task,
 582                task_pane,
 583                existing_item_index,
 584                existing_terminal,
 585                window,
 586                cx,
 587            );
 588        }
 589
 590        let (tx, rx) = oneshot::channel();
 591
 592        self.deferred_tasks.insert(
 593            task.id.clone(),
 594            cx.spawn_in(window, async move |terminal_panel, cx| {
 595                wait_for_terminals_tasks(terminals_for_task, cx).await;
 596                let task = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 597                    if task.use_new_terminal {
 598                        terminal_panel.spawn_in_new_terminal(task, window, cx)
 599                    } else {
 600                        terminal_panel.replace_terminal(
 601                            task,
 602                            task_pane,
 603                            existing_item_index,
 604                            existing_terminal,
 605                            window,
 606                            cx,
 607                        )
 608                    }
 609                });
 610                if let Ok(task) = task {
 611                    tx.send(task.await).ok();
 612                }
 613            }),
 614        );
 615
 616        cx.spawn(async move |_, _| rx.await?)
 617    }
 618
 619    fn spawn_in_new_terminal(
 620        &mut self,
 621        spawn_task: SpawnInTerminal,
 622        window: &mut Window,
 623        cx: &mut Context<Self>,
 624    ) -> Task<Result<WeakEntity<Terminal>>> {
 625        let reveal = spawn_task.reveal;
 626        let reveal_target = spawn_task.reveal_target;
 627        match reveal_target {
 628            RevealTarget::Center => self
 629                .workspace
 630                .update(cx, |workspace, cx| {
 631                    Self::add_center_terminal(workspace, window, cx, |project, cx| {
 632                        project.create_terminal_task(spawn_task, cx)
 633                    })
 634                })
 635                .unwrap_or_else(|e| Task::ready(Err(e))),
 636            RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
 637        }
 638    }
 639
 640    /// Create a new Terminal in the current working directory or the user's home directory
 641    fn new_terminal(
 642        workspace: &mut Workspace,
 643        _: &workspace::NewTerminal,
 644        window: &mut Window,
 645        cx: &mut Context<Workspace>,
 646    ) {
 647        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 648            return;
 649        };
 650
 651        terminal_panel
 652            .update(cx, |this, cx| {
 653                this.add_terminal_shell(
 654                    default_working_directory(workspace, cx),
 655                    RevealStrategy::Always,
 656                    window,
 657                    cx,
 658                )
 659            })
 660            .detach_and_log_err(cx);
 661    }
 662
 663    fn terminals_for_task(
 664        &self,
 665        label: &str,
 666        cx: &mut App,
 667    ) -> Vec<(usize, Entity<Pane>, Entity<TerminalView>)> {
 668        let Some(workspace) = self.workspace.upgrade() else {
 669            return Vec::new();
 670        };
 671
 672        let pane_terminal_views = |pane: Entity<Pane>| {
 673            pane.read(cx)
 674                .items()
 675                .enumerate()
 676                .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
 677                .filter_map(|(index, terminal_view)| {
 678                    let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
 679                    if &task_state.spawned_task.full_label == label {
 680                        Some((index, terminal_view))
 681                    } else {
 682                        None
 683                    }
 684                })
 685                .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
 686        };
 687
 688        self.center
 689            .panes()
 690            .into_iter()
 691            .cloned()
 692            .flat_map(pane_terminal_views)
 693            .chain(
 694                workspace
 695                    .read(cx)
 696                    .panes()
 697                    .iter()
 698                    .cloned()
 699                    .flat_map(pane_terminal_views),
 700            )
 701            .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
 702            .collect()
 703    }
 704
 705    fn activate_terminal_view(
 706        &self,
 707        pane: &Entity<Pane>,
 708        item_index: usize,
 709        focus: bool,
 710        window: &mut Window,
 711        cx: &mut App,
 712    ) {
 713        pane.update(cx, |pane, cx| {
 714            pane.activate_item(item_index, true, focus, window, cx)
 715        })
 716    }
 717
 718    pub fn add_center_terminal(
 719        workspace: &mut Workspace,
 720        window: &mut Window,
 721        cx: &mut Context<Workspace>,
 722        create_terminal: impl FnOnce(
 723            &mut Project,
 724            &mut Context<Project>,
 725        ) -> Task<Result<Entity<Terminal>>>
 726        + 'static,
 727    ) -> Task<Result<WeakEntity<Terminal>>> {
 728        if !is_enabled_in_workspace(workspace, cx) {
 729            return Task::ready(Err(anyhow!(
 730                "terminal not yet supported for remote projects"
 731            )));
 732        }
 733        let project = workspace.project().downgrade();
 734        cx.spawn_in(window, async move |workspace, cx| {
 735            let terminal = project.update(cx, create_terminal)?.await?;
 736
 737            workspace.update_in(cx, |workspace, window, cx| {
 738                let terminal_view = cx.new(|cx| {
 739                    TerminalView::new(
 740                        terminal.clone(),
 741                        workspace.weak_handle(),
 742                        workspace.database_id(),
 743                        workspace.project().downgrade(),
 744                        window,
 745                        cx,
 746                    )
 747                });
 748                workspace.add_item_to_active_pane(Box::new(terminal_view), None, true, window, cx);
 749            })?;
 750            Ok(terminal.downgrade())
 751        })
 752    }
 753
 754    pub fn add_terminal_task(
 755        &mut self,
 756        task: SpawnInTerminal,
 757        reveal_strategy: RevealStrategy,
 758        window: &mut Window,
 759        cx: &mut Context<Self>,
 760    ) -> Task<Result<WeakEntity<Terminal>>> {
 761        let workspace = self.workspace.clone();
 762        cx.spawn_in(window, async move |terminal_panel, cx| {
 763            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 764                anyhow::bail!("terminal not yet supported for remote projects");
 765            }
 766            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 767                terminal_panel.pending_terminals_to_add += 1;
 768                terminal_panel.active_pane.clone()
 769            })?;
 770            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 771            let terminal = project
 772                .update(cx, |project, cx| project.create_terminal_task(task, cx))?
 773                .await?;
 774            let result = workspace.update_in(cx, |workspace, window, cx| {
 775                let terminal_view = Box::new(cx.new(|cx| {
 776                    TerminalView::new(
 777                        terminal.clone(),
 778                        workspace.weak_handle(),
 779                        workspace.database_id(),
 780                        workspace.project().downgrade(),
 781                        window,
 782                        cx,
 783                    )
 784                }));
 785
 786                match reveal_strategy {
 787                    RevealStrategy::Always => {
 788                        workspace.focus_panel::<Self>(window, cx);
 789                    }
 790                    RevealStrategy::NoFocus => {
 791                        workspace.open_panel::<Self>(window, cx);
 792                    }
 793                    RevealStrategy::Never => {}
 794                }
 795
 796                pane.update(cx, |pane, cx| {
 797                    let focus = pane.has_focus(window, cx)
 798                        || matches!(reveal_strategy, RevealStrategy::Always);
 799                    pane.add_item(terminal_view, true, focus, None, window, cx);
 800                });
 801
 802                Ok(terminal.downgrade())
 803            })?;
 804            terminal_panel.update(cx, |terminal_panel, cx| {
 805                terminal_panel.pending_terminals_to_add =
 806                    terminal_panel.pending_terminals_to_add.saturating_sub(1);
 807                terminal_panel.serialize(cx)
 808            })?;
 809            result
 810        })
 811    }
 812
 813    fn add_terminal_shell(
 814        &mut self,
 815        cwd: Option<PathBuf>,
 816        reveal_strategy: RevealStrategy,
 817        window: &mut Window,
 818        cx: &mut Context<Self>,
 819    ) -> Task<Result<WeakEntity<Terminal>>> {
 820        let workspace = self.workspace.clone();
 821        cx.spawn_in(window, async move |terminal_panel, cx| {
 822            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 823                anyhow::bail!("terminal not yet supported for collaborative projects");
 824            }
 825            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 826                terminal_panel.pending_terminals_to_add += 1;
 827                terminal_panel.active_pane.clone()
 828            })?;
 829            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 830            let terminal = project
 831                .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
 832                .await?;
 833            let result = workspace.update_in(cx, |workspace, window, cx| {
 834                let terminal_view = Box::new(cx.new(|cx| {
 835                    TerminalView::new(
 836                        terminal.clone(),
 837                        workspace.weak_handle(),
 838                        workspace.database_id(),
 839                        workspace.project().downgrade(),
 840                        window,
 841                        cx,
 842                    )
 843                }));
 844
 845                match reveal_strategy {
 846                    RevealStrategy::Always => {
 847                        workspace.focus_panel::<Self>(window, cx);
 848                    }
 849                    RevealStrategy::NoFocus => {
 850                        workspace.open_panel::<Self>(window, cx);
 851                    }
 852                    RevealStrategy::Never => {}
 853                }
 854
 855                pane.update(cx, |pane, cx| {
 856                    let focus = pane.has_focus(window, cx)
 857                        || matches!(reveal_strategy, RevealStrategy::Always);
 858                    pane.add_item(terminal_view, true, focus, None, window, cx);
 859                });
 860
 861                Ok(terminal.downgrade())
 862            })?;
 863            terminal_panel.update(cx, |terminal_panel, cx| {
 864                terminal_panel.pending_terminals_to_add =
 865                    terminal_panel.pending_terminals_to_add.saturating_sub(1);
 866                terminal_panel.serialize(cx)
 867            })?;
 868            result
 869        })
 870    }
 871
 872    fn serialize(&mut self, cx: &mut Context<Self>) {
 873        let height = self.height;
 874        let width = self.width;
 875        let Some(serialization_key) = self
 876            .workspace
 877            .read_with(cx, |workspace, _| {
 878                TerminalPanel::serialization_key(workspace)
 879            })
 880            .ok()
 881            .flatten()
 882        else {
 883            return;
 884        };
 885        self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
 886            cx.background_executor()
 887                .timer(Duration::from_millis(50))
 888                .await;
 889            let terminal_panel = terminal_panel.upgrade()?;
 890            let items = terminal_panel
 891                .update(cx, |terminal_panel, cx| {
 892                    SerializedItems::WithSplits(serialize_pane_group(
 893                        &terminal_panel.center,
 894                        &terminal_panel.active_pane,
 895                        cx,
 896                    ))
 897                })
 898                .ok()?;
 899            cx.background_spawn(
 900                async move {
 901                    KEY_VALUE_STORE
 902                        .write_kvp(
 903                            serialization_key,
 904                            serde_json::to_string(&SerializedTerminalPanel {
 905                                items,
 906                                active_item_id: None,
 907                                height,
 908                                width,
 909                            })?,
 910                        )
 911                        .await?;
 912                    anyhow::Ok(())
 913                }
 914                .log_err(),
 915            )
 916            .await;
 917            Some(())
 918        });
 919    }
 920
 921    fn replace_terminal(
 922        &self,
 923        spawn_task: SpawnInTerminal,
 924        task_pane: Entity<Pane>,
 925        terminal_item_index: usize,
 926        terminal_to_replace: Entity<TerminalView>,
 927        window: &mut Window,
 928        cx: &mut Context<Self>,
 929    ) -> Task<Result<WeakEntity<Terminal>>> {
 930        let reveal = spawn_task.reveal;
 931        let reveal_target = spawn_task.reveal_target;
 932        let task_workspace = self.workspace.clone();
 933        cx.spawn_in(window, async move |terminal_panel, cx| {
 934            let project = terminal_panel.update(cx, |this, cx| {
 935                this.workspace
 936                    .update(cx, |workspace, _| workspace.project().clone())
 937            })??;
 938            let new_terminal = project
 939                .update(cx, |project, cx| {
 940                    project.create_terminal_task(spawn_task, cx)
 941                })?
 942                .await?;
 943            terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
 944                terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
 945            })?;
 946
 947            match reveal {
 948                RevealStrategy::Always => match reveal_target {
 949                    RevealTarget::Center => {
 950                        task_workspace.update_in(cx, |workspace, window, cx| {
 951                            let did_activate = workspace.activate_item(
 952                                &terminal_to_replace,
 953                                true,
 954                                true,
 955                                window,
 956                                cx,
 957                            );
 958
 959                            anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
 960
 961                            anyhow::Ok(())
 962                        })??;
 963                    }
 964                    RevealTarget::Dock => {
 965                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 966                            terminal_panel.activate_terminal_view(
 967                                &task_pane,
 968                                terminal_item_index,
 969                                true,
 970                                window,
 971                                cx,
 972                            )
 973                        })?;
 974
 975                        cx.spawn(async move |cx| {
 976                            task_workspace
 977                                .update_in(cx, |workspace, window, cx| {
 978                                    workspace.focus_panel::<Self>(window, cx)
 979                                })
 980                                .ok()
 981                        })
 982                        .detach();
 983                    }
 984                },
 985                RevealStrategy::NoFocus => match reveal_target {
 986                    RevealTarget::Center => {
 987                        task_workspace.update_in(cx, |workspace, window, cx| {
 988                            workspace.active_pane().focus_handle(cx).focus(window);
 989                        })?;
 990                    }
 991                    RevealTarget::Dock => {
 992                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 993                            terminal_panel.activate_terminal_view(
 994                                &task_pane,
 995                                terminal_item_index,
 996                                false,
 997                                window,
 998                                cx,
 999                            )
1000                        })?;
1001
1002                        cx.spawn(async move |cx| {
1003                            task_workspace
1004                                .update_in(cx, |workspace, window, cx| {
1005                                    workspace.open_panel::<Self>(window, cx)
1006                                })
1007                                .ok()
1008                        })
1009                        .detach();
1010                    }
1011                },
1012                RevealStrategy::Never => {}
1013            }
1014
1015            Ok(new_terminal.downgrade())
1016        })
1017    }
1018
1019    fn has_no_terminals(&self, cx: &App) -> bool {
1020        self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1021    }
1022
1023    pub fn assistant_enabled(&self) -> bool {
1024        self.assistant_enabled
1025    }
1026
1027    fn is_enabled(&self, cx: &App) -> bool {
1028        self.workspace
1029            .upgrade()
1030            .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1031    }
1032
1033    fn activate_pane_in_direction(
1034        &mut self,
1035        direction: SplitDirection,
1036        window: &mut Window,
1037        cx: &mut Context<Self>,
1038    ) {
1039        if let Some(pane) = self
1040            .center
1041            .find_pane_in_direction(&self.active_pane, direction, cx)
1042        {
1043            window.focus(&pane.focus_handle(cx));
1044        } else {
1045            self.workspace
1046                .update(cx, |workspace, cx| {
1047                    workspace.activate_pane_in_direction(direction, window, cx)
1048                })
1049                .ok();
1050        }
1051    }
1052
1053    fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1054        if let Some(to) = self
1055            .center
1056            .find_pane_in_direction(&self.active_pane, direction, cx)
1057            .cloned()
1058        {
1059            self.center.swap(&self.active_pane, &to);
1060            cx.notify();
1061        }
1062    }
1063}
1064
1065fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1066    workspace.project().read(cx).supports_terminal(cx)
1067}
1068
1069pub fn new_terminal_pane(
1070    workspace: WeakEntity<Workspace>,
1071    project: Entity<Project>,
1072    zoomed: bool,
1073    window: &mut Window,
1074    cx: &mut Context<TerminalPanel>,
1075) -> Entity<Pane> {
1076    let is_local = project.read(cx).is_local();
1077    let terminal_panel = cx.entity();
1078    let pane = cx.new(|cx| {
1079        let mut pane = Pane::new(
1080            workspace.clone(),
1081            project.clone(),
1082            Default::default(),
1083            None,
1084            NewTerminal.boxed_clone(),
1085            window,
1086            cx,
1087        );
1088        pane.set_zoomed(zoomed, cx);
1089        pane.set_can_navigate(false, cx);
1090        pane.display_nav_history_buttons(None);
1091        pane.set_should_display_tab_bar(|_, _| true);
1092        pane.set_zoom_out_on_close(false);
1093
1094        let split_closure_terminal_panel = terminal_panel.downgrade();
1095        pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1096            if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1097                let is_current_pane = tab.pane == cx.entity();
1098                let Some(can_drag_away) = split_closure_terminal_panel
1099                    .read_with(cx, |terminal_panel, _| {
1100                        let current_panes = terminal_panel.center.panes();
1101                        !current_panes.contains(&&tab.pane)
1102                            || current_panes.len() > 1
1103                            || (!is_current_pane || pane.items_len() > 1)
1104                    })
1105                    .ok()
1106                else {
1107                    return false;
1108                };
1109                if can_drag_away {
1110                    let item = if is_current_pane {
1111                        pane.item_for_index(tab.ix)
1112                    } else {
1113                        tab.pane.read(cx).item_for_index(tab.ix)
1114                    };
1115                    if let Some(item) = item {
1116                        return item.downcast::<TerminalView>().is_some();
1117                    }
1118                }
1119            }
1120            false
1121        })));
1122
1123        let buffer_search_bar = cx.new(|cx| {
1124            search::BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx)
1125        });
1126        let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1127        pane.toolbar().update(cx, |toolbar, cx| {
1128            toolbar.add_item(buffer_search_bar, window, cx);
1129            toolbar.add_item(breadcrumbs, window, cx);
1130        });
1131
1132        let drop_closure_project = project.downgrade();
1133        let drop_closure_terminal_panel = terminal_panel.downgrade();
1134        pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1135            let Some(project) = drop_closure_project.upgrade() else {
1136                return ControlFlow::Break(());
1137            };
1138            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1139                let this_pane = cx.entity();
1140                let item = if tab.pane == this_pane {
1141                    pane.item_for_index(tab.ix)
1142                } else {
1143                    tab.pane.read(cx).item_for_index(tab.ix)
1144                };
1145                if let Some(item) = item {
1146                    if item.downcast::<TerminalView>().is_some() {
1147                        let source = tab.pane.clone();
1148                        let item_id_to_move = item.item_id();
1149
1150                        let Ok(new_split_pane) = pane
1151                            .drag_split_direction()
1152                            .map(|split_direction| {
1153                                drop_closure_terminal_panel.update(cx, |terminal_panel, cx| {
1154                                    let is_zoomed = if terminal_panel.active_pane == this_pane {
1155                                        pane.is_zoomed()
1156                                    } else {
1157                                        terminal_panel.active_pane.read(cx).is_zoomed()
1158                                    };
1159                                    let new_pane = new_terminal_pane(
1160                                        workspace.clone(),
1161                                        project.clone(),
1162                                        is_zoomed,
1163                                        window,
1164                                        cx,
1165                                    );
1166                                    terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1167                                    terminal_panel.center.split(
1168                                        &this_pane,
1169                                        &new_pane,
1170                                        split_direction,
1171                                    )?;
1172                                    anyhow::Ok(new_pane)
1173                                })
1174                            })
1175                            .transpose()
1176                        else {
1177                            return ControlFlow::Break(());
1178                        };
1179
1180                        match new_split_pane.transpose() {
1181                            // Source pane may be the one currently updated, so defer the move.
1182                            Ok(Some(new_pane)) => cx
1183                                .spawn_in(window, async move |_, cx| {
1184                                    cx.update(|window, cx| {
1185                                        move_item(
1186                                            &source,
1187                                            &new_pane,
1188                                            item_id_to_move,
1189                                            new_pane.read(cx).active_item_index(),
1190                                            true,
1191                                            window,
1192                                            cx,
1193                                        );
1194                                    })
1195                                    .ok();
1196                                })
1197                                .detach(),
1198                            // If we drop into existing pane or current pane,
1199                            // regular pane drop handler will take care of it,
1200                            // using the right tab index for the operation.
1201                            Ok(None) => return ControlFlow::Continue(()),
1202                            err @ Err(_) => {
1203                                err.log_err();
1204                                return ControlFlow::Break(());
1205                            }
1206                        };
1207                    } else if let Some(project_path) = item.project_path(cx)
1208                        && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1209                    {
1210                        add_paths_to_terminal(pane, &[entry_path], window, cx);
1211                    }
1212                }
1213            } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1214                let project = project.read(cx);
1215                let paths_to_add = selection
1216                    .items()
1217                    .map(|selected_entry| selected_entry.entry_id)
1218                    .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1219                    .filter_map(|project_path| project.absolute_path(&project_path, cx))
1220                    .collect::<Vec<_>>();
1221                if !paths_to_add.is_empty() {
1222                    add_paths_to_terminal(pane, &paths_to_add, window, cx);
1223                }
1224            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1225                if let Some(entry_path) = project
1226                    .read(cx)
1227                    .path_for_entry(entry_id, cx)
1228                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1229                {
1230                    add_paths_to_terminal(pane, &[entry_path], window, cx);
1231                }
1232            } else if is_local && let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1233                add_paths_to_terminal(pane, paths.paths(), window, cx);
1234            }
1235
1236            ControlFlow::Break(())
1237        });
1238
1239        pane
1240    });
1241
1242    cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1243        .detach();
1244    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1245
1246    pane
1247}
1248
1249async fn wait_for_terminals_tasks(
1250    terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1251    cx: &mut AsyncApp,
1252) {
1253    let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
1254        terminal
1255            .update(cx, |terminal_view, cx| {
1256                terminal_view
1257                    .terminal()
1258                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1259            })
1260            .ok()
1261    });
1262    join_all(pending_tasks).await;
1263}
1264
1265fn add_paths_to_terminal(
1266    pane: &mut Pane,
1267    paths: &[PathBuf],
1268    window: &mut Window,
1269    cx: &mut Context<Pane>,
1270) {
1271    if let Some(terminal_view) = pane
1272        .active_item()
1273        .and_then(|item| item.downcast::<TerminalView>())
1274    {
1275        window.focus(&terminal_view.focus_handle(cx));
1276        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1277        new_text.push(' ');
1278        terminal_view.update(cx, |terminal_view, cx| {
1279            terminal_view.terminal().update(cx, |terminal, _| {
1280                terminal.paste(&new_text);
1281            });
1282        });
1283    }
1284}
1285
1286impl EventEmitter<PanelEvent> for TerminalPanel {}
1287
1288impl Render for TerminalPanel {
1289    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1290        let mut registrar = DivRegistrar::new(
1291            |panel, _, cx| {
1292                panel
1293                    .active_pane
1294                    .read(cx)
1295                    .toolbar()
1296                    .read(cx)
1297                    .item_of_type::<BufferSearchBar>()
1298            },
1299            cx,
1300        );
1301        BufferSearchBar::register(&mut registrar);
1302        let registrar = registrar.into_div();
1303        self.workspace
1304            .update(cx, |workspace, cx| {
1305                registrar.size_full().child(self.center.render(
1306                    workspace.zoomed_item(),
1307                    &workspace::PaneRenderContext {
1308                        follower_states: &HashMap::default(),
1309                        active_call: workspace.active_call(),
1310                        active_pane: &self.active_pane,
1311                        app_state: workspace.app_state(),
1312                        project: workspace.project(),
1313                        workspace: &workspace.weak_handle(),
1314                    },
1315                    window,
1316                    cx,
1317                ))
1318            })
1319            .ok()
1320            .map(|div| {
1321                div.on_action({
1322                    cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1323                        terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1324                    })
1325                })
1326                .on_action({
1327                    cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1328                        terminal_panel.activate_pane_in_direction(
1329                            SplitDirection::Right,
1330                            window,
1331                            cx,
1332                        );
1333                    })
1334                })
1335                .on_action({
1336                    cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1337                        terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1338                    })
1339                })
1340                .on_action({
1341                    cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1342                        terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1343                    })
1344                })
1345                .on_action(
1346                    cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1347                        let panes = terminal_panel.center.panes();
1348                        if let Some(ix) = panes
1349                            .iter()
1350                            .position(|pane| **pane == terminal_panel.active_pane)
1351                        {
1352                            let next_ix = (ix + 1) % panes.len();
1353                            window.focus(&panes[next_ix].focus_handle(cx));
1354                        }
1355                    }),
1356                )
1357                .on_action(cx.listener(
1358                    |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1359                        let panes = terminal_panel.center.panes();
1360                        if let Some(ix) = panes
1361                            .iter()
1362                            .position(|pane| **pane == terminal_panel.active_pane)
1363                        {
1364                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1365                            window.focus(&panes[prev_ix].focus_handle(cx));
1366                        }
1367                    },
1368                ))
1369                .on_action(
1370                    cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1371                        let panes = terminal_panel.center.panes();
1372                        if let Some(&pane) = panes.get(action.0) {
1373                            window.focus(&pane.read(cx).focus_handle(cx));
1374                        } else {
1375                            let future =
1376                                terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
1377                            cx.spawn_in(window, async move |terminal_panel, cx| {
1378                                if let Some(new_pane) = future.await {
1379                                    _ = terminal_panel.update_in(
1380                                        cx,
1381                                        |terminal_panel, window, cx| {
1382                                            terminal_panel
1383                                                .center
1384                                                .split(
1385                                                    &terminal_panel.active_pane,
1386                                                    &new_pane,
1387                                                    SplitDirection::Right,
1388                                                )
1389                                                .log_err();
1390                                            let new_pane = new_pane.read(cx);
1391                                            window.focus(&new_pane.focus_handle(cx));
1392                                        },
1393                                    );
1394                                }
1395                            })
1396                            .detach();
1397                        }
1398                    }),
1399                )
1400                .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1401                    terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1402                }))
1403                .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1404                    terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1405                }))
1406                .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1407                    terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1408                }))
1409                .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1410                    terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1411                }))
1412                .on_action(
1413                    cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1414                        let Some(&target_pane) =
1415                            terminal_panel.center.panes().get(action.destination)
1416                        else {
1417                            return;
1418                        };
1419                        move_active_item(
1420                            &terminal_panel.active_pane,
1421                            target_pane,
1422                            action.focus,
1423                            true,
1424                            window,
1425                            cx,
1426                        );
1427                    }),
1428                )
1429                .on_action(cx.listener(
1430                    |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1431                        let source_pane = &terminal_panel.active_pane;
1432                        if let Some(destination_pane) = terminal_panel
1433                            .center
1434                            .find_pane_in_direction(source_pane, action.direction, cx)
1435                        {
1436                            move_active_item(
1437                                source_pane,
1438                                destination_pane,
1439                                action.focus,
1440                                true,
1441                                window,
1442                                cx,
1443                            );
1444                        };
1445                    },
1446                ))
1447            })
1448            .unwrap_or_else(|| div())
1449    }
1450}
1451
1452impl Focusable for TerminalPanel {
1453    fn focus_handle(&self, cx: &App) -> FocusHandle {
1454        self.active_pane.focus_handle(cx)
1455    }
1456}
1457
1458impl Panel for TerminalPanel {
1459    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1460        match TerminalSettings::get_global(cx).dock {
1461            TerminalDockPosition::Left => DockPosition::Left,
1462            TerminalDockPosition::Bottom => DockPosition::Bottom,
1463            TerminalDockPosition::Right => DockPosition::Right,
1464        }
1465    }
1466
1467    fn position_is_valid(&self, _: DockPosition) -> bool {
1468        true
1469    }
1470
1471    fn set_position(
1472        &mut self,
1473        position: DockPosition,
1474        _window: &mut Window,
1475        cx: &mut Context<Self>,
1476    ) {
1477        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1478            let dock = match position {
1479                DockPosition::Left => TerminalDockPosition::Left,
1480                DockPosition::Bottom => TerminalDockPosition::Bottom,
1481                DockPosition::Right => TerminalDockPosition::Right,
1482            };
1483            settings.terminal.get_or_insert_default().dock = Some(dock);
1484        });
1485    }
1486
1487    fn size(&self, window: &Window, cx: &App) -> Pixels {
1488        let settings = TerminalSettings::get_global(cx);
1489        match self.position(window, cx) {
1490            DockPosition::Left | DockPosition::Right => {
1491                self.width.unwrap_or(settings.default_width)
1492            }
1493            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1494        }
1495    }
1496
1497    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1498        match self.position(window, cx) {
1499            DockPosition::Left | DockPosition::Right => self.width = size,
1500            DockPosition::Bottom => self.height = size,
1501        }
1502        cx.notify();
1503        cx.defer_in(window, |this, _, cx| {
1504            this.serialize(cx);
1505        })
1506    }
1507
1508    fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1509        self.active_pane.read(cx).is_zoomed()
1510    }
1511
1512    fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1513        for pane in self.center.panes() {
1514            pane.update(cx, |pane, cx| {
1515                pane.set_zoomed(zoomed, cx);
1516            })
1517        }
1518        cx.notify();
1519    }
1520
1521    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1522        let old_active = self.active;
1523        self.active = active;
1524        if !active || old_active == active || !self.has_no_terminals(cx) {
1525            return;
1526        }
1527        cx.defer_in(window, |this, window, cx| {
1528            let Ok(kind) = this
1529                .workspace
1530                .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1531            else {
1532                return;
1533            };
1534
1535            this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1536                .detach_and_log_err(cx)
1537        })
1538    }
1539
1540    fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1541        let count = self
1542            .center
1543            .panes()
1544            .into_iter()
1545            .map(|pane| pane.read(cx).items_len())
1546            .sum::<usize>();
1547        if count == 0 {
1548            None
1549        } else {
1550            Some(count.to_string())
1551        }
1552    }
1553
1554    fn persistent_name() -> &'static str {
1555        "TerminalPanel"
1556    }
1557
1558    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1559        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1560            && TerminalSettings::get_global(cx).button
1561        {
1562            Some(IconName::TerminalAlt)
1563        } else {
1564            None
1565        }
1566    }
1567
1568    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1569        Some("Terminal Panel")
1570    }
1571
1572    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1573        Box::new(ToggleFocus)
1574    }
1575
1576    fn pane(&self) -> Option<Entity<Pane>> {
1577        Some(self.active_pane.clone())
1578    }
1579
1580    fn activation_priority(&self) -> u32 {
1581        1
1582    }
1583}
1584
1585struct TerminalProvider(Entity<TerminalPanel>);
1586
1587impl workspace::TerminalProvider for TerminalProvider {
1588    fn spawn(
1589        &self,
1590        task: SpawnInTerminal,
1591        window: &mut Window,
1592        cx: &mut App,
1593    ) -> Task<Option<Result<ExitStatus>>> {
1594        let terminal_panel = self.0.clone();
1595        window.spawn(cx, async move |cx| {
1596            let terminal = terminal_panel
1597                .update_in(cx, |terminal_panel, window, cx| {
1598                    terminal_panel.spawn_task(&task, window, cx)
1599                })
1600                .ok()?
1601                .await;
1602            match terminal {
1603                Ok(terminal) => {
1604                    let exit_status = terminal
1605                        .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1606                        .ok()?
1607                        .await?;
1608                    Some(Ok(exit_status))
1609                }
1610                Err(e) => Some(Err(e)),
1611            }
1612        })
1613    }
1614}
1615
1616struct InlineAssistTabBarButton {
1617    focus_handle: FocusHandle,
1618}
1619
1620impl Render for InlineAssistTabBarButton {
1621    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1622        let focus_handle = self.focus_handle.clone();
1623        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1624            .icon_size(IconSize::Small)
1625            .on_click(cx.listener(|_, _, window, cx| {
1626                window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1627            }))
1628            .tooltip(move |window, cx| {
1629                Tooltip::for_action_in(
1630                    "Inline Assist",
1631                    &InlineAssist::default(),
1632                    &focus_handle,
1633                    window,
1634                    cx,
1635                )
1636            })
1637    }
1638}
1639
1640#[cfg(test)]
1641mod tests {
1642    use super::*;
1643    use gpui::TestAppContext;
1644    use pretty_assertions::assert_eq;
1645    use project::FakeFs;
1646    use settings::SettingsStore;
1647
1648    #[gpui::test]
1649    async fn test_spawn_an_empty_task(cx: &mut TestAppContext) {
1650        init_test(cx);
1651
1652        let fs = FakeFs::new(cx.executor());
1653        let project = Project::test(fs, [], cx).await;
1654        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1655
1656        let (window_handle, terminal_panel) = workspace
1657            .update(cx, |workspace, window, cx| {
1658                let window_handle = window.window_handle();
1659                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1660                (window_handle, terminal_panel)
1661            })
1662            .unwrap();
1663
1664        let task = window_handle
1665            .update(cx, |_, window, cx| {
1666                terminal_panel.update(cx, |terminal_panel, cx| {
1667                    terminal_panel.spawn_task(&SpawnInTerminal::default(), window, cx)
1668                })
1669            })
1670            .unwrap();
1671
1672        let terminal = task.await.unwrap();
1673        let expected_shell = util::get_system_shell();
1674        terminal
1675            .update(cx, |terminal, _| {
1676                let task_metadata = terminal
1677                    .task()
1678                    .expect("When spawning a task, should have the task metadata")
1679                    .spawned_task
1680                    .clone();
1681                assert_eq!(task_metadata.env, HashMap::default());
1682                assert_eq!(task_metadata.cwd, None);
1683                assert_eq!(task_metadata.shell, task::Shell::System);
1684                assert_eq!(
1685                    task_metadata.command,
1686                    Some(expected_shell.clone()),
1687                    "Empty tasks should spawn a -i shell"
1688                );
1689                assert_eq!(task_metadata.args, Vec::<String>::new());
1690                assert_eq!(
1691                    task_metadata.command_label, expected_shell,
1692                    "We show the shell launch for empty commands"
1693                );
1694            })
1695            .unwrap();
1696    }
1697
1698    // A complex Unix command won't be properly parsed by the Windows terminal hence omit the test there.
1699    #[cfg(unix)]
1700    #[gpui::test]
1701    async fn test_spawn_script_like_task(cx: &mut TestAppContext) {
1702        init_test(cx);
1703
1704        let fs = FakeFs::new(cx.executor());
1705        let project = Project::test(fs, [], cx).await;
1706        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1707
1708        let (window_handle, terminal_panel) = workspace
1709            .update(cx, |workspace, window, cx| {
1710                let window_handle = window.window_handle();
1711                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1712                (window_handle, terminal_panel)
1713            })
1714            .unwrap();
1715
1716        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();
1717
1718        let expected_cwd = PathBuf::from("/some/work");
1719        let task = window_handle
1720            .update(cx, |_, window, cx| {
1721                terminal_panel.update(cx, |terminal_panel, cx| {
1722                    terminal_panel.spawn_task(
1723                        &SpawnInTerminal {
1724                            command: Some(user_command.clone()),
1725                            cwd: Some(expected_cwd.clone()),
1726                            ..SpawnInTerminal::default()
1727                        },
1728                        window,
1729                        cx,
1730                    )
1731                })
1732            })
1733            .unwrap();
1734
1735        let terminal = task.await.unwrap();
1736        let shell = util::get_system_shell();
1737        terminal
1738            .update(cx, |terminal, _| {
1739                let task_metadata = terminal
1740                    .task()
1741                    .expect("When spawning a task, should have the task metadata")
1742                    .spawned_task
1743                    .clone();
1744                assert_eq!(task_metadata.env, HashMap::default());
1745                assert_eq!(task_metadata.cwd, Some(expected_cwd));
1746                assert_eq!(task_metadata.shell, task::Shell::System);
1747                assert_eq!(task_metadata.command, Some(shell.clone()));
1748                assert_eq!(
1749                    task_metadata.args,
1750                    vec!["-i".to_string(), "-c".to_string(), user_command.clone(),],
1751                    "Use command should have been moved into the arguments, as we're spawning a new -i shell",
1752                );
1753                assert_eq!(
1754                    task_metadata.command_label,
1755                    format!("{shell} {interactive}-c '{user_command}'", interactive = if cfg!(windows) {""} else {"-i "}),
1756                    "We want to show to the user the entire command spawned");
1757            })
1758            .unwrap();
1759    }
1760
1761    pub fn init_test(cx: &mut TestAppContext) {
1762        cx.update(|cx| {
1763            let store = SettingsStore::test(cx);
1764            cx.set_global(store);
1765            theme::init(theme::LoadThemes::JustBase, cx);
1766            client::init_settings(cx);
1767            language::init(cx);
1768            Project::init_settings(cx);
1769            workspace::init_settings(cx);
1770            editor::init(cx);
1771            crate::init(cx);
1772        });
1773    }
1774}