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