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