terminal_panel.rs

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