terminal_panel.rs

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