terminal_panel.rs

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