terminal_panel.rs

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