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