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