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