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