terminal_panel.rs

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