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