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<Entity<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    pub fn spawn_in_new_terminal(
 556        &mut self,
 557        spawn_task: SpawnInTerminal,
 558        window: &mut Window,
 559        cx: &mut Context<Self>,
 560    ) -> Task<Result<Entity<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<Entity<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)
 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<Entity<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)
 739            })?;
 740            terminal_panel.update(cx, |this, cx| {
 741                this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
 742                this.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            .update(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<Entity<Terminal>>> {
 806        let reveal = spawn_task.reveal;
 807        let reveal_target = spawn_task.reveal_target;
 808        let window_handle = window.window_handle();
 809        let task_workspace = self.workspace.clone();
 810        cx.spawn_in(window, async move |terminal_panel, cx| {
 811            let project = terminal_panel.update(cx, |this, cx| {
 812                this.workspace
 813                    .update(cx, |workspace, _| workspace.project().clone())
 814            })??;
 815            let new_terminal = project
 816                .update(cx, |project, cx| {
 817                    project.create_terminal(TerminalKind::Task(spawn_task), window_handle, cx)
 818                })?
 819                .await?;
 820            terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
 821                terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
 822            })?;
 823
 824            match reveal {
 825                RevealStrategy::Always => match reveal_target {
 826                    RevealTarget::Center => {
 827                        task_workspace.update_in(cx, |workspace, window, cx| {
 828                            workspace
 829                                .active_item(cx)
 830                                .context("retrieving active terminal item in the workspace")?
 831                                .item_focus_handle(cx)
 832                                .focus(window);
 833                            anyhow::Ok(())
 834                        })??;
 835                    }
 836                    RevealTarget::Dock => {
 837                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 838                            terminal_panel.activate_terminal_view(
 839                                &task_pane,
 840                                terminal_item_index,
 841                                true,
 842                                window,
 843                                cx,
 844                            )
 845                        })?;
 846
 847                        cx.spawn(async move |cx| {
 848                            task_workspace
 849                                .update_in(cx, |workspace, window, cx| {
 850                                    workspace.focus_panel::<Self>(window, cx)
 851                                })
 852                                .ok()
 853                        })
 854                        .detach();
 855                    }
 856                },
 857                RevealStrategy::NoFocus => match reveal_target {
 858                    RevealTarget::Center => {
 859                        task_workspace.update_in(cx, |workspace, window, cx| {
 860                            workspace.active_pane().focus_handle(cx).focus(window);
 861                        })?;
 862                    }
 863                    RevealTarget::Dock => {
 864                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 865                            terminal_panel.activate_terminal_view(
 866                                &task_pane,
 867                                terminal_item_index,
 868                                false,
 869                                window,
 870                                cx,
 871                            )
 872                        })?;
 873
 874                        cx.spawn(async move |cx| {
 875                            task_workspace
 876                                .update_in(cx, |workspace, window, cx| {
 877                                    workspace.open_panel::<Self>(window, cx)
 878                                })
 879                                .ok()
 880                        })
 881                        .detach();
 882                    }
 883                },
 884                RevealStrategy::Never => {}
 885            }
 886
 887            Ok(new_terminal)
 888        })
 889    }
 890
 891    fn has_no_terminals(&self, cx: &App) -> bool {
 892        self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
 893    }
 894
 895    pub fn assistant_enabled(&self) -> bool {
 896        self.assistant_enabled
 897    }
 898
 899    fn is_enabled(&self, cx: &App) -> bool {
 900        self.workspace.upgrade().map_or(false, |workspace| {
 901            is_enabled_in_workspace(workspace.read(cx), cx)
 902        })
 903    }
 904
 905    fn activate_pane_in_direction(
 906        &mut self,
 907        direction: SplitDirection,
 908        window: &mut Window,
 909        cx: &mut Context<Self>,
 910    ) {
 911        if let Some(pane) = self
 912            .center
 913            .find_pane_in_direction(&self.active_pane, direction, cx)
 914        {
 915            window.focus(&pane.focus_handle(cx));
 916        } else {
 917            self.workspace
 918                .update(cx, |workspace, cx| {
 919                    workspace.activate_pane_in_direction(direction, window, cx)
 920                })
 921                .ok();
 922        }
 923    }
 924
 925    fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 926        if let Some(to) = self
 927            .center
 928            .find_pane_in_direction(&self.active_pane, direction, cx)
 929            .cloned()
 930        {
 931            self.center.swap(&self.active_pane, &to);
 932            cx.notify();
 933        }
 934    }
 935}
 936
 937fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
 938    workspace.project().read(cx).supports_terminal(cx)
 939}
 940
 941pub fn new_terminal_pane(
 942    workspace: WeakEntity<Workspace>,
 943    project: Entity<Project>,
 944    zoomed: bool,
 945    window: &mut Window,
 946    cx: &mut Context<TerminalPanel>,
 947) -> Entity<Pane> {
 948    let is_local = project.read(cx).is_local();
 949    let terminal_panel = cx.entity().clone();
 950    let pane = cx.new(|cx| {
 951        let mut pane = Pane::new(
 952            workspace.clone(),
 953            project.clone(),
 954            Default::default(),
 955            None,
 956            NewTerminal.boxed_clone(),
 957            window,
 958            cx,
 959        );
 960        pane.set_zoomed(zoomed, cx);
 961        pane.set_can_navigate(false, cx);
 962        pane.display_nav_history_buttons(None);
 963        pane.set_should_display_tab_bar(|_, _| true);
 964        pane.set_zoom_out_on_close(false);
 965
 966        let split_closure_terminal_panel = terminal_panel.downgrade();
 967        pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
 968            if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
 969                let is_current_pane = tab.pane == cx.entity();
 970                let Some(can_drag_away) = split_closure_terminal_panel
 971                    .update(cx, |terminal_panel, _| {
 972                        let current_panes = terminal_panel.center.panes();
 973                        !current_panes.contains(&&tab.pane)
 974                            || current_panes.len() > 1
 975                            || (!is_current_pane || pane.items_len() > 1)
 976                    })
 977                    .ok()
 978                else {
 979                    return false;
 980                };
 981                if can_drag_away {
 982                    let item = if is_current_pane {
 983                        pane.item_for_index(tab.ix)
 984                    } else {
 985                        tab.pane.read(cx).item_for_index(tab.ix)
 986                    };
 987                    if let Some(item) = item {
 988                        return item.downcast::<TerminalView>().is_some();
 989                    }
 990                }
 991            }
 992            false
 993        })));
 994
 995        let buffer_search_bar = cx.new(|cx| {
 996            search::BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx)
 997        });
 998        let breadcrumbs = cx.new(|_| Breadcrumbs::new());
 999        pane.toolbar().update(cx, |toolbar, cx| {
1000            toolbar.add_item(buffer_search_bar, window, cx);
1001            toolbar.add_item(breadcrumbs, window, cx);
1002        });
1003
1004        let drop_closure_project = project.downgrade();
1005        let drop_closure_terminal_panel = terminal_panel.downgrade();
1006        pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1007            let Some(project) = drop_closure_project.upgrade() else {
1008                return ControlFlow::Break(());
1009            };
1010            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1011                let this_pane = cx.entity().clone();
1012                let item = if tab.pane == this_pane {
1013                    pane.item_for_index(tab.ix)
1014                } else {
1015                    tab.pane.read(cx).item_for_index(tab.ix)
1016                };
1017                if let Some(item) = item {
1018                    if item.downcast::<TerminalView>().is_some() {
1019                        let source = tab.pane.clone();
1020                        let item_id_to_move = item.item_id();
1021
1022                        let Ok(new_split_pane) = pane
1023                            .drag_split_direction()
1024                            .map(|split_direction| {
1025                                drop_closure_terminal_panel.update(cx, |terminal_panel, cx| {
1026                                    let is_zoomed = if terminal_panel.active_pane == this_pane {
1027                                        pane.is_zoomed()
1028                                    } else {
1029                                        terminal_panel.active_pane.read(cx).is_zoomed()
1030                                    };
1031                                    let new_pane = new_terminal_pane(
1032                                        workspace.clone(),
1033                                        project.clone(),
1034                                        is_zoomed,
1035                                        window,
1036                                        cx,
1037                                    );
1038                                    terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1039                                    terminal_panel.center.split(
1040                                        &this_pane,
1041                                        &new_pane,
1042                                        split_direction,
1043                                    )?;
1044                                    anyhow::Ok(new_pane)
1045                                })
1046                            })
1047                            .transpose()
1048                        else {
1049                            return ControlFlow::Break(());
1050                        };
1051
1052                        match new_split_pane.transpose() {
1053                            // Source pane may be the one currently updated, so defer the move.
1054                            Ok(Some(new_pane)) => cx
1055                                .spawn_in(window, async move |_, cx| {
1056                                    cx.update(|window, cx| {
1057                                        move_item(
1058                                            &source,
1059                                            &new_pane,
1060                                            item_id_to_move,
1061                                            new_pane.read(cx).active_item_index(),
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                        if 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                }
1085            } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1086                let project = project.read(cx);
1087                let paths_to_add = selection
1088                    .items()
1089                    .map(|selected_entry| selected_entry.entry_id)
1090                    .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1091                    .filter_map(|project_path| project.absolute_path(&project_path, cx))
1092                    .collect::<Vec<_>>();
1093                if !paths_to_add.is_empty() {
1094                    add_paths_to_terminal(pane, &paths_to_add, window, cx);
1095                }
1096            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1097                if let Some(entry_path) = project
1098                    .read(cx)
1099                    .path_for_entry(entry_id, cx)
1100                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1101                {
1102                    add_paths_to_terminal(pane, &[entry_path], window, cx);
1103                }
1104            } else if is_local {
1105                if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1106                    add_paths_to_terminal(pane, paths.paths(), window, cx);
1107                }
1108            }
1109
1110            ControlFlow::Break(())
1111        });
1112
1113        pane
1114    });
1115
1116    cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1117        .detach();
1118    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1119
1120    pane
1121}
1122
1123async fn wait_for_terminals_tasks(
1124    terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1125    cx: &mut AsyncApp,
1126) {
1127    let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
1128        terminal
1129            .update(cx, |terminal_view, cx| {
1130                terminal_view
1131                    .terminal()
1132                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1133            })
1134            .ok()
1135    });
1136    let _: Vec<_> = join_all(pending_tasks).await;
1137}
1138
1139fn add_paths_to_terminal(
1140    pane: &mut Pane,
1141    paths: &[PathBuf],
1142    window: &mut Window,
1143    cx: &mut Context<Pane>,
1144) {
1145    if let Some(terminal_view) = pane
1146        .active_item()
1147        .and_then(|item| item.downcast::<TerminalView>())
1148    {
1149        window.focus(&terminal_view.focus_handle(cx));
1150        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1151        new_text.push(' ');
1152        terminal_view.update(cx, |terminal_view, cx| {
1153            terminal_view.terminal().update(cx, |terminal, _| {
1154                terminal.paste(&new_text);
1155            });
1156        });
1157    }
1158}
1159
1160impl EventEmitter<PanelEvent> for TerminalPanel {}
1161
1162impl Render for TerminalPanel {
1163    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1164        let mut registrar = DivRegistrar::new(
1165            |panel, _, cx| {
1166                panel
1167                    .active_pane
1168                    .read(cx)
1169                    .toolbar()
1170                    .read(cx)
1171                    .item_of_type::<BufferSearchBar>()
1172            },
1173            cx,
1174        );
1175        BufferSearchBar::register(&mut registrar);
1176        let registrar = registrar.into_div();
1177        self.workspace
1178            .update(cx, |workspace, cx| {
1179                registrar.size_full().child(self.center.render(
1180                    workspace.zoomed_item(),
1181                    &workspace::PaneRenderContext {
1182                        follower_states: &&HashMap::default(),
1183                        active_call: workspace.active_call(),
1184                        active_pane: &self.active_pane,
1185                        app_state: &workspace.app_state(),
1186                        project: workspace.project(),
1187                        workspace: &workspace.weak_handle(),
1188                    },
1189                    window,
1190                    cx,
1191                ))
1192            })
1193            .ok()
1194            .map(|div| {
1195                div.on_action({
1196                    cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1197                        terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1198                    })
1199                })
1200                .on_action({
1201                    cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1202                        terminal_panel.activate_pane_in_direction(
1203                            SplitDirection::Right,
1204                            window,
1205                            cx,
1206                        );
1207                    })
1208                })
1209                .on_action({
1210                    cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1211                        terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1212                    })
1213                })
1214                .on_action({
1215                    cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1216                        terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1217                    })
1218                })
1219                .on_action(
1220                    cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1221                        let panes = terminal_panel.center.panes();
1222                        if let Some(ix) = panes
1223                            .iter()
1224                            .position(|pane| **pane == terminal_panel.active_pane)
1225                        {
1226                            let next_ix = (ix + 1) % panes.len();
1227                            window.focus(&panes[next_ix].focus_handle(cx));
1228                        }
1229                    }),
1230                )
1231                .on_action(cx.listener(
1232                    |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1233                        let panes = terminal_panel.center.panes();
1234                        if let Some(ix) = panes
1235                            .iter()
1236                            .position(|pane| **pane == terminal_panel.active_pane)
1237                        {
1238                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1239                            window.focus(&panes[prev_ix].focus_handle(cx));
1240                        }
1241                    },
1242                ))
1243                .on_action(
1244                    cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1245                        let panes = terminal_panel.center.panes();
1246                        if let Some(&pane) = panes.get(action.0) {
1247                            window.focus(&pane.read(cx).focus_handle(cx));
1248                        } else {
1249                            if let Some(new_pane) =
1250                                terminal_panel.new_pane_with_cloned_active_terminal(window, cx)
1251                            {
1252                                terminal_panel
1253                                    .center
1254                                    .split(
1255                                        &terminal_panel.active_pane,
1256                                        &new_pane,
1257                                        SplitDirection::Right,
1258                                    )
1259                                    .log_err();
1260                                window.focus(&new_pane.focus_handle(cx));
1261                            }
1262                        }
1263                    }),
1264                )
1265                .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1266                    terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1267                }))
1268                .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1269                    terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1270                }))
1271                .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1272                    terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1273                }))
1274                .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1275                    terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1276                }))
1277                .on_action(
1278                    cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1279                        let Some(&target_pane) =
1280                            terminal_panel.center.panes().get(action.destination)
1281                        else {
1282                            return;
1283                        };
1284                        move_active_item(
1285                            &terminal_panel.active_pane,
1286                            target_pane,
1287                            action.focus,
1288                            true,
1289                            window,
1290                            cx,
1291                        );
1292                    }),
1293                )
1294                .on_action(cx.listener(
1295                    |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1296                        let source_pane = &terminal_panel.active_pane;
1297                        if let Some(destination_pane) = terminal_panel
1298                            .center
1299                            .find_pane_in_direction(source_pane, action.direction, cx)
1300                        {
1301                            move_active_item(
1302                                source_pane,
1303                                destination_pane,
1304                                action.focus,
1305                                true,
1306                                window,
1307                                cx,
1308                            );
1309                        };
1310                    },
1311                ))
1312            })
1313            .unwrap_or_else(|| div())
1314    }
1315}
1316
1317impl Focusable for TerminalPanel {
1318    fn focus_handle(&self, cx: &App) -> FocusHandle {
1319        self.active_pane.focus_handle(cx)
1320    }
1321}
1322
1323impl Panel for TerminalPanel {
1324    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1325        match TerminalSettings::get_global(cx).dock {
1326            TerminalDockPosition::Left => DockPosition::Left,
1327            TerminalDockPosition::Bottom => DockPosition::Bottom,
1328            TerminalDockPosition::Right => DockPosition::Right,
1329        }
1330    }
1331
1332    fn position_is_valid(&self, _: DockPosition) -> bool {
1333        true
1334    }
1335
1336    fn set_position(
1337        &mut self,
1338        position: DockPosition,
1339        _window: &mut Window,
1340        cx: &mut Context<Self>,
1341    ) {
1342        settings::update_settings_file::<TerminalSettings>(
1343            self.fs.clone(),
1344            cx,
1345            move |settings, _| {
1346                let dock = match position {
1347                    DockPosition::Left => TerminalDockPosition::Left,
1348                    DockPosition::Bottom => TerminalDockPosition::Bottom,
1349                    DockPosition::Right => TerminalDockPosition::Right,
1350                };
1351                settings.dock = Some(dock);
1352            },
1353        );
1354    }
1355
1356    fn size(&self, window: &Window, cx: &App) -> Pixels {
1357        let settings = TerminalSettings::get_global(cx);
1358        match self.position(window, cx) {
1359            DockPosition::Left | DockPosition::Right => {
1360                self.width.unwrap_or(settings.default_width)
1361            }
1362            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1363        }
1364    }
1365
1366    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1367        match self.position(window, cx) {
1368            DockPosition::Left | DockPosition::Right => self.width = size,
1369            DockPosition::Bottom => self.height = size,
1370        }
1371        cx.notify();
1372        cx.defer_in(window, |this, _, cx| {
1373            this.serialize(cx);
1374        })
1375    }
1376
1377    fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1378        self.active_pane.read(cx).is_zoomed()
1379    }
1380
1381    fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1382        for pane in self.center.panes() {
1383            pane.update(cx, |pane, cx| {
1384                pane.set_zoomed(zoomed, cx);
1385            })
1386        }
1387        cx.notify();
1388    }
1389
1390    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1391        let old_active = self.active;
1392        self.active = active;
1393        if !active || old_active == active || !self.has_no_terminals(cx) {
1394            return;
1395        }
1396        cx.defer_in(window, |this, window, cx| {
1397            let Ok(kind) = this.workspace.update(cx, |workspace, cx| {
1398                TerminalKind::Shell(default_working_directory(workspace, cx))
1399            }) else {
1400                return;
1401            };
1402
1403            this.add_terminal(kind, RevealStrategy::Always, window, cx)
1404                .detach_and_log_err(cx)
1405        })
1406    }
1407
1408    fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1409        let count = self
1410            .center
1411            .panes()
1412            .into_iter()
1413            .map(|pane| pane.read(cx).items_len())
1414            .sum::<usize>();
1415        if count == 0 {
1416            None
1417        } else {
1418            Some(count.to_string())
1419        }
1420    }
1421
1422    fn persistent_name() -> &'static str {
1423        "TerminalPanel"
1424    }
1425
1426    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1427        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1428            && TerminalSettings::get_global(cx).button
1429        {
1430            Some(IconName::Terminal)
1431        } else {
1432            None
1433        }
1434    }
1435
1436    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1437        Some("Terminal Panel")
1438    }
1439
1440    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1441        Box::new(ToggleFocus)
1442    }
1443
1444    fn pane(&self) -> Option<Entity<Pane>> {
1445        Some(self.active_pane.clone())
1446    }
1447
1448    fn activation_priority(&self) -> u32 {
1449        1
1450    }
1451}
1452
1453struct TerminalProvider(Entity<TerminalPanel>);
1454
1455impl workspace::TerminalProvider for TerminalProvider {
1456    fn spawn(
1457        &self,
1458        task: SpawnInTerminal,
1459        window: &mut Window,
1460        cx: &mut App,
1461    ) -> Task<Result<ExitStatus>> {
1462        let this = self.0.clone();
1463        window.spawn(cx, async move |cx| {
1464            let terminal = this
1465                .update_in(cx, |terminal_panel, window, cx| {
1466                    terminal_panel.spawn_task(&task, window, cx)
1467                })?
1468                .await?;
1469            let Some(exit_code) = terminal
1470                .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1471                .await
1472            else {
1473                return Err(anyhow!("Task cancelled"));
1474            };
1475
1476            Ok(exit_code)
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}