terminal_panel.rs

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