terminal_panel.rs

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