terminal_panel.rs

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