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