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