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