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, TerminalDockPosition};
  22use task::{RevealStrategy, RevealTarget, Shell, ShellBuilder, SpawnInTerminal, TaskId};
  23use terminal::{Terminal, terminal_settings::TerminalSettings};
  24use ui::{
  25    ButtonLike, Clickable, ContextMenu, FluentBuilder, PopoverMenu, SplitButton, Toggleable,
  26    Tooltip, prelude::*,
  27};
  28use util::{ResultExt, TryFutureExt};
  29use workspace::{
  30    ActivateNextPane, ActivatePane, ActivatePaneDown, ActivatePaneLeft, ActivatePaneRight,
  31    ActivatePaneUp, ActivatePreviousPane, DraggedSelection, DraggedTab, ItemId, MoveItemToPane,
  32    MoveItemToPaneInDirection, MovePaneDown, MovePaneLeft, MovePaneRight, MovePaneUp, Pane,
  33    PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitMode, SplitRight, SplitUp, SwapPaneDown,
  34    SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom, Workspace,
  35    dock::{DockPosition, Panel, PanelEvent, PanelHandle},
  36    item::SerializableItem,
  37    move_active_item, move_item, pane,
  38};
  39
  40use anyhow::{Result, anyhow};
  41use zed_actions::assistant::InlineAssist;
  42
  43const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
  44
  45actions!(
  46    terminal_panel,
  47    [
  48        /// Toggles the terminal panel.
  49        Toggle,
  50        /// Toggles focus on the terminal panel.
  51        ToggleFocus
  52    ]
  53);
  54
  55pub fn init(cx: &mut App) {
  56    cx.observe_new(
  57        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
  58            workspace.register_action(TerminalPanel::new_terminal);
  59            workspace.register_action(TerminalPanel::open_terminal);
  60            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
  61                if is_enabled_in_workspace(workspace, cx) {
  62                    workspace.toggle_panel_focus::<TerminalPanel>(window, cx);
  63                }
  64            });
  65            workspace.register_action(|workspace, _: &Toggle, window, cx| {
  66                if is_enabled_in_workspace(workspace, cx) {
  67                    if !workspace.toggle_panel_focus::<TerminalPanel>(window, cx) {
  68                        workspace.close_panel::<TerminalPanel>(window, cx);
  69                    }
  70                }
  71            });
  72        },
  73    )
  74    .detach();
  75}
  76
  77pub struct TerminalPanel {
  78    pub(crate) active_pane: Entity<Pane>,
  79    pub(crate) center: PaneGroup,
  80    fs: Arc<dyn Fs>,
  81    workspace: WeakEntity<Workspace>,
  82    pub(crate) width: Option<Pixels>,
  83    pub(crate) height: Option<Pixels>,
  84    pending_serialization: Task<Option<()>>,
  85    pending_terminals_to_add: usize,
  86    deferred_tasks: HashMap<TaskId, Task<()>>,
  87    assistant_enabled: bool,
  88    assistant_tab_bar_button: Option<AnyView>,
  89    active: bool,
  90}
  91
  92impl TerminalPanel {
  93    pub fn new(workspace: &Workspace, window: &mut Window, cx: &mut Context<Self>) -> Self {
  94        let project = workspace.project();
  95        let pane = new_terminal_pane(workspace.weak_handle(), project.clone(), false, window, cx);
  96        let center = PaneGroup::new(pane.clone());
  97        let terminal_panel = Self {
  98            center,
  99            active_pane: pane,
 100            fs: workspace.app_state().fs.clone(),
 101            workspace: workspace.weak_handle(),
 102            pending_serialization: Task::ready(None),
 103            width: None,
 104            height: None,
 105            pending_terminals_to_add: 0,
 106            deferred_tasks: HashMap::default(),
 107            assistant_enabled: false,
 108            assistant_tab_bar_button: None,
 109            active: false,
 110        };
 111        terminal_panel.apply_tab_bar_buttons(&terminal_panel.active_pane, cx);
 112        terminal_panel
 113    }
 114
 115    pub fn set_assistant_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 116        self.assistant_enabled = enabled;
 117        if enabled {
 118            let focus_handle = self
 119                .active_pane
 120                .read(cx)
 121                .active_item()
 122                .map(|item| item.item_focus_handle(cx))
 123                .unwrap_or(self.focus_handle(cx));
 124            self.assistant_tab_bar_button = Some(
 125                cx.new(move |_| InlineAssistTabBarButton { focus_handle })
 126                    .into(),
 127            );
 128        } else {
 129            self.assistant_tab_bar_button = None;
 130        }
 131        for pane in self.center.panes() {
 132            self.apply_tab_bar_buttons(pane, cx);
 133        }
 134    }
 135
 136    fn apply_tab_bar_buttons(&self, terminal_pane: &Entity<Pane>, cx: &mut Context<Self>) {
 137        let assistant_tab_bar_button = self.assistant_tab_bar_button.clone();
 138        terminal_pane.update(cx, |pane, cx| {
 139            pane.set_render_tab_bar_buttons(cx, move |pane, window, cx| {
 140                let split_context = pane
 141                    .active_item()
 142                    .and_then(|item| item.downcast::<TerminalView>())
 143                    .map(|terminal_view| terminal_view.read(cx).focus_handle.clone());
 144                let has_focused_rename_editor = pane
 145                    .active_item()
 146                    .and_then(|item| item.downcast::<TerminalView>())
 147                    .is_some_and(|view| view.read(cx).rename_editor_is_focused(window, cx));
 148                if !pane.has_focus(window, cx)
 149                    && !pane.context_menu_focused(window, cx)
 150                    && !has_focused_rename_editor
 151                {
 152                    return (None, None);
 153                }
 154                let focus_handle = pane.focus_handle(cx);
 155                let right_children = h_flex()
 156                    .gap(DynamicSpacing::Base02.rems(cx))
 157                    .child(
 158                        PopoverMenu::new("terminal-tab-bar-popover-menu")
 159                            .trigger_with_tooltip(
 160                                IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
 161                                Tooltip::text("New…"),
 162                            )
 163                            .anchor(Corner::TopRight)
 164                            .with_handle(pane.new_item_context_menu_handle.clone())
 165                            .menu(move |window, cx| {
 166                                let focus_handle = focus_handle.clone();
 167                                let menu = ContextMenu::build(window, cx, |menu, _, _| {
 168                                    menu.context(focus_handle.clone())
 169                                        .action(
 170                                            "New Terminal",
 171                                            workspace::NewTerminal::default().boxed_clone(),
 172                                        )
 173                                        // We want the focus to go back to terminal panel once task modal is dismissed,
 174                                        // hence we focus that first. Otherwise, we'd end up without a focused element, as
 175                                        // context menu will be gone the moment we spawn the modal.
 176                                        .action(
 177                                            "Spawn Task",
 178                                            zed_actions::Spawn::modal().boxed_clone(),
 179                                        )
 180                                });
 181
 182                                Some(menu)
 183                            }),
 184                    )
 185                    .children(assistant_tab_bar_button.clone())
 186                    .child(
 187                        PopoverMenu::new("terminal-pane-tab-bar-split")
 188                            .trigger_with_tooltip(
 189                                IconButton::new("terminal-pane-split", IconName::Split)
 190                                    .icon_size(IconSize::Small),
 191                                Tooltip::text("Split Pane"),
 192                            )
 193                            .anchor(Corner::TopRight)
 194                            .with_handle(pane.split_item_context_menu_handle.clone())
 195                            .menu({
 196                                move |window, cx| {
 197                                    ContextMenu::build(window, cx, |menu, _, _| {
 198                                        menu.when_some(
 199                                            split_context.clone(),
 200                                            |menu, split_context| menu.context(split_context),
 201                                        )
 202                                        .action("Split Right", SplitRight::default().boxed_clone())
 203                                        .action("Split Left", SplitLeft::default().boxed_clone())
 204                                        .action("Split Up", SplitUp::default().boxed_clone())
 205                                        .action("Split Down", SplitDown::default().boxed_clone())
 206                                    })
 207                                    .into()
 208                                }
 209                            }),
 210                    )
 211                    .child({
 212                        let zoomed = pane.is_zoomed();
 213                        IconButton::new("toggle_zoom", IconName::Maximize)
 214                            .icon_size(IconSize::Small)
 215                            .toggle_state(zoomed)
 216                            .selected_icon(IconName::Minimize)
 217                            .on_click(cx.listener(|pane, _, window, cx| {
 218                                pane.toggle_zoom(&workspace::ToggleZoom, window, cx);
 219                            }))
 220                            .tooltip(move |_window, cx| {
 221                                Tooltip::for_action(
 222                                    if zoomed { "Zoom Out" } else { "Zoom In" },
 223                                    &ToggleZoom,
 224                                    cx,
 225                                )
 226                            })
 227                    })
 228                    .into_any_element()
 229                    .into();
 230                (None, right_children)
 231            });
 232        });
 233    }
 234
 235    fn serialization_key(workspace: &Workspace) -> Option<String> {
 236        workspace
 237            .database_id()
 238            .map(|id| i64::from(id).to_string())
 239            .or(workspace.session_id())
 240            .map(|id| format!("{:?}-{:?}", TERMINAL_PANEL_KEY, id))
 241    }
 242
 243    pub async fn load(
 244        workspace: WeakEntity<Workspace>,
 245        mut cx: AsyncWindowContext,
 246    ) -> Result<Entity<Self>> {
 247        let mut terminal_panel = None;
 248
 249        if let Some((database_id, serialization_key)) = workspace
 250            .read_with(&cx, |workspace, _| {
 251                workspace
 252                    .database_id()
 253                    .zip(TerminalPanel::serialization_key(workspace))
 254            })
 255            .ok()
 256            .flatten()
 257            && let Some(serialized_panel) = cx
 258                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 259                .await
 260                .log_err()
 261                .flatten()
 262                .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
 263                .transpose()
 264                .log_err()
 265                .flatten()
 266            && let Ok(serialized) = workspace
 267                .update_in(&mut cx, |workspace, window, cx| {
 268                    deserialize_terminal_panel(
 269                        workspace.weak_handle(),
 270                        workspace.project().clone(),
 271                        database_id,
 272                        serialized_panel,
 273                        window,
 274                        cx,
 275                    )
 276                })?
 277                .await
 278        {
 279            terminal_panel = Some(serialized);
 280        }
 281
 282        let terminal_panel = if let Some(panel) = terminal_panel {
 283            panel
 284        } else {
 285            workspace.update_in(&mut cx, |workspace, window, cx| {
 286                cx.new(|cx| TerminalPanel::new(workspace, window, cx))
 287            })?
 288        };
 289
 290        if let Some(workspace) = workspace.upgrade() {
 291            workspace.update(&mut cx, |workspace, _| {
 292                workspace.set_terminal_provider(TerminalProvider(terminal_panel.clone()))
 293            });
 294        }
 295
 296        // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
 297        if let Some(workspace) = workspace.upgrade() {
 298            let cleanup_task = workspace.update_in(&mut cx, |workspace, window, cx| {
 299                let alive_item_ids = terminal_panel
 300                    .read(cx)
 301                    .center
 302                    .panes()
 303                    .into_iter()
 304                    .flat_map(|pane| pane.read(cx).items())
 305                    .map(|item| item.item_id().as_u64() as ItemId)
 306                    .collect();
 307                workspace.database_id().map(|workspace_id| {
 308                    TerminalView::cleanup(workspace_id, alive_item_ids, window, cx)
 309                })
 310            })?;
 311            if let Some(task) = cleanup_task {
 312                task.await.log_err();
 313            }
 314        }
 315
 316        if let Some(workspace) = workspace.upgrade() {
 317            let should_focus = workspace
 318                .update_in(&mut cx, |workspace, window, cx| {
 319                    workspace.active_item(cx).is_none()
 320                        && workspace
 321                            .is_dock_at_position_open(terminal_panel.position(window, cx), cx)
 322                })
 323                .unwrap_or(false);
 324
 325            if should_focus {
 326                terminal_panel
 327                    .update_in(&mut cx, |panel, window, cx| {
 328                        panel.active_pane.update(cx, |pane, cx| {
 329                            pane.focus_active_item(window, cx);
 330                        });
 331                    })
 332                    .ok();
 333            }
 334        }
 335        Ok(terminal_panel)
 336    }
 337
 338    fn handle_pane_event(
 339        &mut self,
 340        pane: &Entity<Pane>,
 341        event: &pane::Event,
 342        window: &mut Window,
 343        cx: &mut Context<Self>,
 344    ) {
 345        match event {
 346            pane::Event::ActivateItem { .. } => self.serialize(cx),
 347            pane::Event::RemovedItem { .. } => self.serialize(cx),
 348            pane::Event::Remove { focus_on_pane } => {
 349                let pane_count_before_removal = self.center.panes().len();
 350                let _removal_result = self.center.remove(pane, cx);
 351                if pane_count_before_removal == 1 {
 352                    self.center.first_pane().update(cx, |pane, cx| {
 353                        pane.set_zoomed(false, cx);
 354                    });
 355                    cx.emit(PanelEvent::Close);
 356                } else if let Some(focus_on_pane) =
 357                    focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
 358                {
 359                    focus_on_pane.focus_handle(cx).focus(window, cx);
 360                }
 361            }
 362            pane::Event::ZoomIn => {
 363                for pane in self.center.panes() {
 364                    pane.update(cx, |pane, cx| {
 365                        pane.set_zoomed(true, cx);
 366                    })
 367                }
 368                cx.emit(PanelEvent::ZoomIn);
 369                cx.notify();
 370            }
 371            pane::Event::ZoomOut => {
 372                for pane in self.center.panes() {
 373                    pane.update(cx, |pane, cx| {
 374                        pane.set_zoomed(false, cx);
 375                    })
 376                }
 377                cx.emit(PanelEvent::ZoomOut);
 378                cx.notify();
 379            }
 380            pane::Event::AddItem { item } => {
 381                if let Some(workspace) = self.workspace.upgrade() {
 382                    workspace.update(cx, |workspace, cx| {
 383                        item.added_to_pane(workspace, pane.clone(), window, cx)
 384                    })
 385                }
 386                self.serialize(cx);
 387            }
 388            &pane::Event::Split { direction, mode } => {
 389                match mode {
 390                    SplitMode::ClonePane | SplitMode::EmptyPane => {
 391                        let clone = matches!(mode, SplitMode::ClonePane);
 392                        let new_pane = self.new_pane_with_active_terminal(clone, window, cx);
 393                        let pane = pane.clone();
 394                        cx.spawn_in(window, async move |panel, cx| {
 395                            let Some(new_pane) = new_pane.await else {
 396                                return;
 397                            };
 398                            panel
 399                                .update_in(cx, |panel, window, cx| {
 400                                    panel
 401                                        .center
 402                                        .split(&pane, &new_pane, direction, cx)
 403                                        .log_err();
 404                                    window.focus(&new_pane.focus_handle(cx), cx);
 405                                })
 406                                .ok();
 407                        })
 408                        .detach();
 409                    }
 410                    SplitMode::MovePane => {
 411                        let Some(item) =
 412                            pane.update(cx, |pane, cx| pane.take_active_item(window, cx))
 413                        else {
 414                            return;
 415                        };
 416                        let Ok(project) = self
 417                            .workspace
 418                            .update(cx, |workspace, _| workspace.project().clone())
 419                        else {
 420                            return;
 421                        };
 422                        let new_pane =
 423                            new_terminal_pane(self.workspace.clone(), project, false, window, cx);
 424                        new_pane.update(cx, |pane, cx| {
 425                            pane.add_item(item, true, true, None, window, cx);
 426                        });
 427                        self.center.split(&pane, &new_pane, direction, cx).log_err();
 428                        window.focus(&new_pane.focus_handle(cx), cx);
 429                    }
 430                };
 431            }
 432            pane::Event::Focus => {
 433                self.active_pane = pane.clone();
 434            }
 435            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {
 436                self.serialize(cx);
 437            }
 438
 439            _ => {}
 440        }
 441    }
 442
 443    fn new_pane_with_active_terminal(
 444        &mut self,
 445        clone: bool,
 446        window: &mut Window,
 447        cx: &mut Context<Self>,
 448    ) -> Task<Option<Entity<Pane>>> {
 449        let Some(workspace) = self.workspace.upgrade() else {
 450            return Task::ready(None);
 451        };
 452        let workspace = workspace.read(cx);
 453        let database_id = workspace.database_id();
 454        let weak_workspace = self.workspace.clone();
 455        let project = workspace.project().clone();
 456        let active_pane = &self.active_pane;
 457        let terminal_view = if clone {
 458            active_pane
 459                .read(cx)
 460                .active_item()
 461                .and_then(|item| item.downcast::<TerminalView>())
 462        } else {
 463            None
 464        };
 465        let working_directory = if clone {
 466            terminal_view
 467                .as_ref()
 468                .and_then(|terminal_view| {
 469                    terminal_view
 470                        .read(cx)
 471                        .terminal()
 472                        .read(cx)
 473                        .working_directory()
 474                })
 475                .or_else(|| default_working_directory(workspace, cx))
 476        } else {
 477            default_working_directory(workspace, cx)
 478        };
 479
 480        let is_zoomed = if clone {
 481            active_pane.read(cx).is_zoomed()
 482        } else {
 483            false
 484        };
 485        cx.spawn_in(window, async move |panel, cx| {
 486            let terminal = project
 487                .update(cx, |project, cx| match terminal_view {
 488                    Some(view) => project.clone_terminal(
 489                        &view.read(cx).terminal.clone(),
 490                        cx,
 491                        working_directory,
 492                    ),
 493                    None => project.create_terminal_shell(working_directory, cx),
 494                })
 495                .await
 496                .log_err()?;
 497
 498            panel
 499                .update_in(cx, move |terminal_panel, window, cx| {
 500                    let terminal_view = Box::new(cx.new(|cx| {
 501                        TerminalView::new(
 502                            terminal.clone(),
 503                            weak_workspace.clone(),
 504                            database_id,
 505                            project.downgrade(),
 506                            window,
 507                            cx,
 508                        )
 509                    }));
 510                    let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
 511                    terminal_panel.apply_tab_bar_buttons(&pane, cx);
 512                    pane.update(cx, |pane, cx| {
 513                        pane.add_item(terminal_view, true, true, None, window, cx);
 514                    });
 515                    Some(pane)
 516                })
 517                .ok()
 518                .flatten()
 519        })
 520    }
 521
 522    pub fn open_terminal(
 523        workspace: &mut Workspace,
 524        action: &workspace::OpenTerminal,
 525        window: &mut Window,
 526        cx: &mut Context<Workspace>,
 527    ) {
 528        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 529            return;
 530        };
 531
 532        terminal_panel
 533            .update(cx, |panel, cx| {
 534                if action.local {
 535                    panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
 536                } else {
 537                    panel.add_terminal_shell(
 538                        Some(action.working_directory.clone()),
 539                        RevealStrategy::Always,
 540                        window,
 541                        cx,
 542                    )
 543                }
 544            })
 545            .detach_and_log_err(cx);
 546    }
 547
 548    pub fn spawn_task(
 549        &mut self,
 550        task: &SpawnInTerminal,
 551        window: &mut Window,
 552        cx: &mut Context<Self>,
 553    ) -> Task<Result<WeakEntity<Terminal>>> {
 554        let Some(workspace) = self.workspace.upgrade() else {
 555            return Task::ready(Err(anyhow!("failed to read workspace")));
 556        };
 557
 558        let project = workspace.read(cx).project().read(cx);
 559
 560        if project.is_via_collab() {
 561            return Task::ready(Err(anyhow!("cannot spawn tasks as a guest")));
 562        }
 563
 564        let remote_client = project.remote_client();
 565        let is_windows = project.path_style(cx).is_windows();
 566        let remote_shell = remote_client
 567            .as_ref()
 568            .and_then(|remote_client| remote_client.read(cx).shell());
 569
 570        let shell = if let Some(remote_shell) = remote_shell
 571            && task.shell == Shell::System
 572        {
 573            Shell::Program(remote_shell)
 574        } else {
 575            task.shell.clone()
 576        };
 577
 578        let task = prepare_task_for_spawn(task, &shell, is_windows);
 579
 580        if task.allow_concurrent_runs && task.use_new_terminal {
 581            return self.spawn_in_new_terminal(task, window, cx);
 582        }
 583
 584        let mut terminals_for_task = self.terminals_for_task(&task.full_label, cx);
 585        let Some(existing) = terminals_for_task.pop() else {
 586            return self.spawn_in_new_terminal(task, window, cx);
 587        };
 588
 589        let (existing_item_index, task_pane, existing_terminal) = existing;
 590        if task.allow_concurrent_runs {
 591            return self.replace_terminal(
 592                task,
 593                task_pane,
 594                existing_item_index,
 595                existing_terminal,
 596                window,
 597                cx,
 598            );
 599        }
 600
 601        let (tx, rx) = oneshot::channel();
 602
 603        self.deferred_tasks.insert(
 604            task.id.clone(),
 605            cx.spawn_in(window, async move |terminal_panel, cx| {
 606                wait_for_terminals_tasks(terminals_for_task, cx).await;
 607                let task = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 608                    if task.use_new_terminal {
 609                        terminal_panel.spawn_in_new_terminal(task, window, cx)
 610                    } else {
 611                        terminal_panel.replace_terminal(
 612                            task,
 613                            task_pane,
 614                            existing_item_index,
 615                            existing_terminal,
 616                            window,
 617                            cx,
 618                        )
 619                    }
 620                });
 621                if let Ok(task) = task {
 622                    tx.send(task.await).ok();
 623                }
 624            }),
 625        );
 626
 627        cx.spawn(async move |_, _| rx.await?)
 628    }
 629
 630    fn spawn_in_new_terminal(
 631        &mut self,
 632        spawn_task: SpawnInTerminal,
 633        window: &mut Window,
 634        cx: &mut Context<Self>,
 635    ) -> Task<Result<WeakEntity<Terminal>>> {
 636        let reveal = spawn_task.reveal;
 637        let reveal_target = spawn_task.reveal_target;
 638        match reveal_target {
 639            RevealTarget::Center => self
 640                .workspace
 641                .update(cx, |workspace, cx| {
 642                    Self::add_center_terminal(workspace, window, cx, |project, cx| {
 643                        project.create_terminal_task(spawn_task, cx)
 644                    })
 645                })
 646                .unwrap_or_else(|e| Task::ready(Err(e))),
 647            RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
 648        }
 649    }
 650
 651    /// Create a new Terminal in the current working directory or the user's home directory
 652    fn new_terminal(
 653        workspace: &mut Workspace,
 654        action: &workspace::NewTerminal,
 655        window: &mut Window,
 656        cx: &mut Context<Workspace>,
 657    ) {
 658        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 659            return;
 660        };
 661
 662        terminal_panel
 663            .update(cx, |this, cx| {
 664                if action.local {
 665                    this.add_local_terminal_shell(RevealStrategy::Always, window, cx)
 666                } else {
 667                    this.add_terminal_shell(
 668                        default_working_directory(workspace, cx),
 669                        RevealStrategy::Always,
 670                        window,
 671                        cx,
 672                    )
 673                }
 674            })
 675            .detach_and_log_err(cx);
 676    }
 677
 678    fn terminals_for_task(
 679        &self,
 680        label: &str,
 681        cx: &mut App,
 682    ) -> Vec<(usize, Entity<Pane>, Entity<TerminalView>)> {
 683        let Some(workspace) = self.workspace.upgrade() else {
 684            return Vec::new();
 685        };
 686
 687        let pane_terminal_views = |pane: Entity<Pane>| {
 688            pane.read(cx)
 689                .items()
 690                .enumerate()
 691                .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
 692                .filter_map(|(index, terminal_view)| {
 693                    let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
 694                    if &task_state.spawned_task.full_label == label {
 695                        Some((index, terminal_view))
 696                    } else {
 697                        None
 698                    }
 699                })
 700                .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
 701        };
 702
 703        self.center
 704            .panes()
 705            .into_iter()
 706            .cloned()
 707            .flat_map(pane_terminal_views)
 708            .chain(
 709                workspace
 710                    .read(cx)
 711                    .panes()
 712                    .iter()
 713                    .cloned()
 714                    .flat_map(pane_terminal_views),
 715            )
 716            .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
 717            .collect()
 718    }
 719
 720    fn activate_terminal_view(
 721        &self,
 722        pane: &Entity<Pane>,
 723        item_index: usize,
 724        focus: bool,
 725        window: &mut Window,
 726        cx: &mut App,
 727    ) {
 728        pane.update(cx, |pane, cx| {
 729            pane.activate_item(item_index, true, focus, window, cx)
 730        })
 731    }
 732
 733    pub fn add_center_terminal(
 734        workspace: &mut Workspace,
 735        window: &mut Window,
 736        cx: &mut Context<Workspace>,
 737        create_terminal: impl FnOnce(
 738            &mut Project,
 739            &mut Context<Project>,
 740        ) -> Task<Result<Entity<Terminal>>>
 741        + 'static,
 742    ) -> Task<Result<WeakEntity<Terminal>>> {
 743        if !is_enabled_in_workspace(workspace, cx) {
 744            return Task::ready(Err(anyhow!(
 745                "terminal not yet supported for remote projects"
 746            )));
 747        }
 748        let project = workspace.project().downgrade();
 749        cx.spawn_in(window, async move |workspace, cx| {
 750            let terminal = project.update(cx, create_terminal)?.await?;
 751
 752            workspace.update_in(cx, |workspace, window, cx| {
 753                let terminal_view = cx.new(|cx| {
 754                    TerminalView::new(
 755                        terminal.clone(),
 756                        workspace.weak_handle(),
 757                        workspace.database_id(),
 758                        workspace.project().downgrade(),
 759                        window,
 760                        cx,
 761                    )
 762                });
 763                workspace.add_item_to_active_pane(Box::new(terminal_view), None, true, window, cx);
 764            })?;
 765            Ok(terminal.downgrade())
 766        })
 767    }
 768
 769    pub fn add_terminal_task(
 770        &mut self,
 771        task: SpawnInTerminal,
 772        reveal_strategy: RevealStrategy,
 773        window: &mut Window,
 774        cx: &mut Context<Self>,
 775    ) -> Task<Result<WeakEntity<Terminal>>> {
 776        let workspace = self.workspace.clone();
 777        cx.spawn_in(window, async move |terminal_panel, cx| {
 778            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 779                anyhow::bail!("terminal not yet supported for remote projects");
 780            }
 781            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 782                terminal_panel.pending_terminals_to_add += 1;
 783                terminal_panel.active_pane.clone()
 784            })?;
 785            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 786            let terminal = project
 787                .update(cx, |project, cx| project.create_terminal_task(task, cx))
 788                .await?;
 789            let result = workspace.update_in(cx, |workspace, window, cx| {
 790                let terminal_view = Box::new(cx.new(|cx| {
 791                    TerminalView::new(
 792                        terminal.clone(),
 793                        workspace.weak_handle(),
 794                        workspace.database_id(),
 795                        workspace.project().downgrade(),
 796                        window,
 797                        cx,
 798                    )
 799                }));
 800
 801                match reveal_strategy {
 802                    RevealStrategy::Always => {
 803                        workspace.focus_panel::<Self>(window, cx);
 804                    }
 805                    RevealStrategy::NoFocus => {
 806                        workspace.open_panel::<Self>(window, cx);
 807                    }
 808                    RevealStrategy::Never => {}
 809                }
 810
 811                pane.update(cx, |pane, cx| {
 812                    let focus = matches!(reveal_strategy, RevealStrategy::Always);
 813                    pane.add_item(terminal_view, true, focus, None, window, cx);
 814                });
 815
 816                Ok(terminal.downgrade())
 817            })?;
 818            terminal_panel.update(cx, |terminal_panel, cx| {
 819                terminal_panel.pending_terminals_to_add =
 820                    terminal_panel.pending_terminals_to_add.saturating_sub(1);
 821                terminal_panel.serialize(cx)
 822            })?;
 823            result
 824        })
 825    }
 826
 827    fn add_terminal_shell(
 828        &mut self,
 829        cwd: Option<PathBuf>,
 830        reveal_strategy: RevealStrategy,
 831        window: &mut Window,
 832        cx: &mut Context<Self>,
 833    ) -> Task<Result<WeakEntity<Terminal>>> {
 834        self.add_terminal_shell_internal(false, cwd, reveal_strategy, window, cx)
 835    }
 836
 837    fn add_local_terminal_shell(
 838        &mut self,
 839        reveal_strategy: RevealStrategy,
 840        window: &mut Window,
 841        cx: &mut Context<Self>,
 842    ) -> Task<Result<WeakEntity<Terminal>>> {
 843        self.add_terminal_shell_internal(true, None, reveal_strategy, window, cx)
 844    }
 845
 846    fn add_terminal_shell_internal(
 847        &mut self,
 848        force_local: bool,
 849        cwd: Option<PathBuf>,
 850        reveal_strategy: RevealStrategy,
 851        window: &mut Window,
 852        cx: &mut Context<Self>,
 853    ) -> Task<Result<WeakEntity<Terminal>>> {
 854        let workspace = self.workspace.clone();
 855
 856        cx.spawn_in(window, async move |terminal_panel, cx| {
 857            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 858                anyhow::bail!("terminal not yet supported for collaborative projects");
 859            }
 860            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 861                terminal_panel.pending_terminals_to_add += 1;
 862                terminal_panel.active_pane.clone()
 863            })?;
 864            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 865            let terminal = if force_local {
 866                project
 867                    .update(cx, |project, cx| project.create_local_terminal(cx))
 868                    .await
 869            } else {
 870                project
 871                    .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))
 872                    .await
 873            };
 874
 875            match terminal {
 876                Ok(terminal) => {
 877                    let result = workspace.update_in(cx, |workspace, window, cx| {
 878                        let terminal_view = Box::new(cx.new(|cx| {
 879                            TerminalView::new(
 880                                terminal.clone(),
 881                                workspace.weak_handle(),
 882                                workspace.database_id(),
 883                                workspace.project().downgrade(),
 884                                window,
 885                                cx,
 886                            )
 887                        }));
 888
 889                        match reveal_strategy {
 890                            RevealStrategy::Always => {
 891                                workspace.focus_panel::<Self>(window, cx);
 892                            }
 893                            RevealStrategy::NoFocus => {
 894                                workspace.open_panel::<Self>(window, cx);
 895                            }
 896                            RevealStrategy::Never => {}
 897                        }
 898
 899                        pane.update(cx, |pane, cx| {
 900                            let focus = matches!(reveal_strategy, RevealStrategy::Always);
 901                            pane.add_item(terminal_view, true, focus, None, window, cx);
 902                        });
 903
 904                        Ok(terminal.downgrade())
 905                    })?;
 906                    terminal_panel.update(cx, |terminal_panel, cx| {
 907                        terminal_panel.pending_terminals_to_add =
 908                            terminal_panel.pending_terminals_to_add.saturating_sub(1);
 909                        terminal_panel.serialize(cx)
 910                    })?;
 911                    result
 912                }
 913                Err(error) => {
 914                    pane.update_in(cx, |pane, window, cx| {
 915                        let focus = pane.has_focus(window, cx);
 916                        let failed_to_spawn = cx.new(|cx| FailedToSpawnTerminal {
 917                            error: error.to_string(),
 918                            focus_handle: cx.focus_handle(),
 919                        });
 920                        pane.add_item(Box::new(failed_to_spawn), true, focus, None, window, cx);
 921                    })?;
 922                    Err(error)
 923                }
 924            }
 925        })
 926    }
 927
 928    fn serialize(&mut self, cx: &mut Context<Self>) {
 929        let height = self.height;
 930        let width = self.width;
 931        let Some(serialization_key) = self
 932            .workspace
 933            .read_with(cx, |workspace, _| {
 934                TerminalPanel::serialization_key(workspace)
 935            })
 936            .ok()
 937            .flatten()
 938        else {
 939            return;
 940        };
 941        self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
 942            cx.background_executor()
 943                .timer(Duration::from_millis(50))
 944                .await;
 945            let terminal_panel = terminal_panel.upgrade()?;
 946            let items = terminal_panel.update(cx, |terminal_panel, cx| {
 947                SerializedItems::WithSplits(serialize_pane_group(
 948                    &terminal_panel.center,
 949                    &terminal_panel.active_pane,
 950                    cx,
 951                ))
 952            });
 953            cx.background_spawn(
 954                async move {
 955                    KEY_VALUE_STORE
 956                        .write_kvp(
 957                            serialization_key,
 958                            serde_json::to_string(&SerializedTerminalPanel {
 959                                items,
 960                                active_item_id: None,
 961                                height,
 962                                width,
 963                            })?,
 964                        )
 965                        .await?;
 966                    anyhow::Ok(())
 967                }
 968                .log_err(),
 969            )
 970            .await;
 971            Some(())
 972        });
 973    }
 974
 975    fn replace_terminal(
 976        &self,
 977        spawn_task: SpawnInTerminal,
 978        task_pane: Entity<Pane>,
 979        terminal_item_index: usize,
 980        terminal_to_replace: Entity<TerminalView>,
 981        window: &mut Window,
 982        cx: &mut Context<Self>,
 983    ) -> Task<Result<WeakEntity<Terminal>>> {
 984        let reveal = spawn_task.reveal;
 985        let task_workspace = self.workspace.clone();
 986        cx.spawn_in(window, async move |terminal_panel, cx| {
 987            let project = terminal_panel.update(cx, |this, cx| {
 988                this.workspace
 989                    .update(cx, |workspace, _| workspace.project().clone())
 990            })??;
 991            let new_terminal = project
 992                .update(cx, |project, cx| {
 993                    project.create_terminal_task(spawn_task, cx)
 994                })
 995                .await?;
 996            terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
 997                terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
 998            })?;
 999
1000            let reveal_target = terminal_panel.update(cx, |panel, _| {
1001                if panel.center.panes().iter().any(|p| **p == task_pane) {
1002                    RevealTarget::Dock
1003                } else {
1004                    RevealTarget::Center
1005                }
1006            })?;
1007
1008            match reveal {
1009                RevealStrategy::Always => match reveal_target {
1010                    RevealTarget::Center => {
1011                        task_workspace.update_in(cx, |workspace, window, cx| {
1012                            let did_activate = workspace.activate_item(
1013                                &terminal_to_replace,
1014                                true,
1015                                true,
1016                                window,
1017                                cx,
1018                            );
1019
1020                            anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
1021
1022                            anyhow::Ok(())
1023                        })??;
1024                    }
1025                    RevealTarget::Dock => {
1026                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1027                            terminal_panel.activate_terminal_view(
1028                                &task_pane,
1029                                terminal_item_index,
1030                                true,
1031                                window,
1032                                cx,
1033                            )
1034                        })?;
1035
1036                        cx.spawn(async move |cx| {
1037                            task_workspace
1038                                .update_in(cx, |workspace, window, cx| {
1039                                    workspace.focus_panel::<Self>(window, cx)
1040                                })
1041                                .ok()
1042                        })
1043                        .detach();
1044                    }
1045                },
1046                RevealStrategy::NoFocus => match reveal_target {
1047                    RevealTarget::Center => {
1048                        task_workspace.update_in(cx, |workspace, window, cx| {
1049                            workspace.active_pane().focus_handle(cx).focus(window, cx);
1050                        })?;
1051                    }
1052                    RevealTarget::Dock => {
1053                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1054                            terminal_panel.activate_terminal_view(
1055                                &task_pane,
1056                                terminal_item_index,
1057                                false,
1058                                window,
1059                                cx,
1060                            )
1061                        })?;
1062
1063                        cx.spawn(async move |cx| {
1064                            task_workspace
1065                                .update_in(cx, |workspace, window, cx| {
1066                                    workspace.open_panel::<Self>(window, cx)
1067                                })
1068                                .ok()
1069                        })
1070                        .detach();
1071                    }
1072                },
1073                RevealStrategy::Never => {}
1074            }
1075
1076            Ok(new_terminal.downgrade())
1077        })
1078    }
1079
1080    fn has_no_terminals(&self, cx: &App) -> bool {
1081        self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1082    }
1083
1084    pub fn assistant_enabled(&self) -> bool {
1085        self.assistant_enabled
1086    }
1087
1088    fn is_enabled(&self, cx: &App) -> bool {
1089        self.workspace
1090            .upgrade()
1091            .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1092    }
1093
1094    fn activate_pane_in_direction(
1095        &mut self,
1096        direction: SplitDirection,
1097        window: &mut Window,
1098        cx: &mut Context<Self>,
1099    ) {
1100        if let Some(pane) = self
1101            .center
1102            .find_pane_in_direction(&self.active_pane, direction, cx)
1103        {
1104            window.focus(&pane.focus_handle(cx), cx);
1105        } else {
1106            self.workspace
1107                .update(cx, |workspace, cx| {
1108                    workspace.activate_pane_in_direction(direction, window, cx)
1109                })
1110                .ok();
1111        }
1112    }
1113
1114    fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1115        if let Some(to) = self
1116            .center
1117            .find_pane_in_direction(&self.active_pane, direction, cx)
1118            .cloned()
1119        {
1120            self.center.swap(&self.active_pane, &to, cx);
1121            cx.notify();
1122        }
1123    }
1124
1125    fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1126        if self
1127            .center
1128            .move_to_border(&self.active_pane, direction, cx)
1129            .unwrap()
1130        {
1131            cx.notify();
1132        }
1133    }
1134}
1135
1136/// Prepares a `SpawnInTerminal` by computing the command, args, and command_label
1137/// based on the shell configuration. This is a pure function that can be tested
1138/// without spawning actual terminals.
1139pub fn prepare_task_for_spawn(
1140    task: &SpawnInTerminal,
1141    shell: &Shell,
1142    is_windows: bool,
1143) -> SpawnInTerminal {
1144    let builder = ShellBuilder::new(shell, is_windows);
1145    let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
1146    let (command, args) = builder.build_no_quote(task.command.clone(), &task.args);
1147
1148    SpawnInTerminal {
1149        command_label,
1150        command: Some(command),
1151        args,
1152        ..task.clone()
1153    }
1154}
1155
1156fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1157    workspace.project().read(cx).supports_terminal(cx)
1158}
1159
1160pub fn new_terminal_pane(
1161    workspace: WeakEntity<Workspace>,
1162    project: Entity<Project>,
1163    zoomed: bool,
1164    window: &mut Window,
1165    cx: &mut Context<TerminalPanel>,
1166) -> Entity<Pane> {
1167    let is_local = project.read(cx).is_local();
1168    let terminal_panel = cx.entity();
1169    let pane = cx.new(|cx| {
1170        let mut pane = Pane::new(
1171            workspace.clone(),
1172            project.clone(),
1173            Default::default(),
1174            None,
1175            workspace::NewTerminal::default().boxed_clone(),
1176            false,
1177            window,
1178            cx,
1179        );
1180        pane.set_zoomed(zoomed, cx);
1181        pane.set_can_navigate(false, cx);
1182        pane.display_nav_history_buttons(None);
1183        pane.set_should_display_tab_bar(|_, _| true);
1184        pane.set_zoom_out_on_close(false);
1185
1186        let split_closure_terminal_panel = terminal_panel.downgrade();
1187        pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1188            if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1189                let is_current_pane = tab.pane == cx.entity();
1190                let Some(can_drag_away) = split_closure_terminal_panel
1191                    .read_with(cx, |terminal_panel, _| {
1192                        let current_panes = terminal_panel.center.panes();
1193                        !current_panes.contains(&&tab.pane)
1194                            || current_panes.len() > 1
1195                            || (!is_current_pane || pane.items_len() > 1)
1196                    })
1197                    .ok()
1198                else {
1199                    return false;
1200                };
1201                if can_drag_away {
1202                    let item = if is_current_pane {
1203                        pane.item_for_index(tab.ix)
1204                    } else {
1205                        tab.pane.read(cx).item_for_index(tab.ix)
1206                    };
1207                    if let Some(item) = item {
1208                        return item.downcast::<TerminalView>().is_some();
1209                    }
1210                }
1211            }
1212            false
1213        })));
1214
1215        let buffer_search_bar = cx.new(|cx| {
1216            search::BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx)
1217        });
1218        let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1219        pane.toolbar().update(cx, |toolbar, cx| {
1220            toolbar.add_item(buffer_search_bar, window, cx);
1221            toolbar.add_item(breadcrumbs, window, cx);
1222        });
1223
1224        let drop_closure_project = project.downgrade();
1225        let drop_closure_terminal_panel = terminal_panel.downgrade();
1226        pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1227            let Some(project) = drop_closure_project.upgrade() else {
1228                return ControlFlow::Break(());
1229            };
1230            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1231                let this_pane = cx.entity();
1232                let item = if tab.pane == this_pane {
1233                    pane.item_for_index(tab.ix)
1234                } else {
1235                    tab.pane.read(cx).item_for_index(tab.ix)
1236                };
1237                if let Some(item) = item {
1238                    if item.downcast::<TerminalView>().is_some() {
1239                        let source = tab.pane.clone();
1240                        let item_id_to_move = item.item_id();
1241
1242                        // If no split direction, let the regular pane drop handler take care of it
1243                        let Some(split_direction) = pane.drag_split_direction() else {
1244                            return ControlFlow::Continue(());
1245                        };
1246
1247                        // Gather data synchronously before deferring
1248                        let is_zoomed = drop_closure_terminal_panel
1249                            .upgrade()
1250                            .map(|terminal_panel| {
1251                                let terminal_panel = terminal_panel.read(cx);
1252                                if terminal_panel.active_pane == this_pane {
1253                                    pane.is_zoomed()
1254                                } else {
1255                                    terminal_panel.active_pane.read(cx).is_zoomed()
1256                                }
1257                            })
1258                            .unwrap_or(false);
1259
1260                        let workspace = workspace.clone();
1261                        let terminal_panel = drop_closure_terminal_panel.clone();
1262
1263                        // Defer the split operation to avoid re-entrancy panic.
1264                        // The pane may be the one currently being updated, so we cannot
1265                        // call mark_positions (via split) synchronously.
1266                        cx.spawn_in(window, async move |_, cx| {
1267                            cx.update(|window, cx| {
1268                                let Ok(new_pane) =
1269                                    terminal_panel.update(cx, |terminal_panel, cx| {
1270                                        let new_pane = new_terminal_pane(
1271                                            workspace, project, is_zoomed, window, cx,
1272                                        );
1273                                        terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1274                                        terminal_panel.center.split(
1275                                            &this_pane,
1276                                            &new_pane,
1277                                            split_direction,
1278                                            cx,
1279                                        )?;
1280                                        anyhow::Ok(new_pane)
1281                                    })
1282                                else {
1283                                    return;
1284                                };
1285
1286                                let Some(new_pane) = new_pane.log_err() else {
1287                                    return;
1288                                };
1289
1290                                move_item(
1291                                    &source,
1292                                    &new_pane,
1293                                    item_id_to_move,
1294                                    new_pane.read(cx).active_item_index(),
1295                                    true,
1296                                    window,
1297                                    cx,
1298                                );
1299                            })
1300                            .ok();
1301                        })
1302                        .detach();
1303                    } else if let Some(project_path) = item.project_path(cx)
1304                        && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1305                    {
1306                        add_paths_to_terminal(pane, &[entry_path], window, cx);
1307                    }
1308                }
1309            } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1310                let project = project.read(cx);
1311                let paths_to_add = selection
1312                    .items()
1313                    .map(|selected_entry| selected_entry.entry_id)
1314                    .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1315                    .filter_map(|project_path| project.absolute_path(&project_path, cx))
1316                    .collect::<Vec<_>>();
1317                if !paths_to_add.is_empty() {
1318                    add_paths_to_terminal(pane, &paths_to_add, window, cx);
1319                }
1320            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1321                if let Some(entry_path) = project
1322                    .read(cx)
1323                    .path_for_entry(entry_id, cx)
1324                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1325                {
1326                    add_paths_to_terminal(pane, &[entry_path], window, cx);
1327                }
1328            } else if is_local && let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1329                add_paths_to_terminal(pane, paths.paths(), window, cx);
1330            }
1331
1332            ControlFlow::Break(())
1333        });
1334
1335        pane
1336    });
1337
1338    cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1339        .detach();
1340    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1341
1342    pane
1343}
1344
1345async fn wait_for_terminals_tasks(
1346    terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1347    cx: &mut AsyncApp,
1348) {
1349    let pending_tasks = terminals_for_task.iter().map(|(_, _, terminal)| {
1350        terminal.update(cx, |terminal_view, cx| {
1351            terminal_view
1352                .terminal()
1353                .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1354        })
1355    });
1356    join_all(pending_tasks).await;
1357}
1358
1359fn add_paths_to_terminal(
1360    pane: &mut Pane,
1361    paths: &[PathBuf],
1362    window: &mut Window,
1363    cx: &mut Context<Pane>,
1364) {
1365    if let Some(terminal_view) = pane
1366        .active_item()
1367        .and_then(|item| item.downcast::<TerminalView>())
1368    {
1369        window.focus(&terminal_view.focus_handle(cx), cx);
1370        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1371        new_text.push(' ');
1372        terminal_view.update(cx, |terminal_view, cx| {
1373            terminal_view.terminal().update(cx, |terminal, _| {
1374                terminal.paste(&new_text);
1375            });
1376        });
1377    }
1378}
1379
1380struct FailedToSpawnTerminal {
1381    error: String,
1382    focus_handle: FocusHandle,
1383}
1384
1385impl Focusable for FailedToSpawnTerminal {
1386    fn focus_handle(&self, _: &App) -> FocusHandle {
1387        self.focus_handle.clone()
1388    }
1389}
1390
1391impl Render for FailedToSpawnTerminal {
1392    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1393        let popover_menu = PopoverMenu::new("settings-popover")
1394            .trigger(
1395                IconButton::new("icon-button-popover", IconName::ChevronDown)
1396                    .icon_size(IconSize::XSmall),
1397            )
1398            .menu(move |window, cx| {
1399                Some(ContextMenu::build(window, cx, |context_menu, _, _| {
1400                    context_menu
1401                        .action("Open Settings", zed_actions::OpenSettings.boxed_clone())
1402                        .action(
1403                            "Edit settings.json",
1404                            zed_actions::OpenSettingsFile.boxed_clone(),
1405                        )
1406                }))
1407            })
1408            .anchor(Corner::TopRight)
1409            .offset(gpui::Point {
1410                x: px(0.0),
1411                y: px(2.0),
1412            });
1413
1414        v_flex()
1415            .track_focus(&self.focus_handle)
1416            .size_full()
1417            .p_4()
1418            .items_center()
1419            .justify_center()
1420            .bg(cx.theme().colors().editor_background)
1421            .child(
1422                v_flex()
1423                    .max_w_112()
1424                    .items_center()
1425                    .justify_center()
1426                    .text_center()
1427                    .child(Label::new("Failed to spawn terminal"))
1428                    .child(
1429                        Label::new(self.error.to_string())
1430                            .size(LabelSize::Small)
1431                            .color(Color::Muted)
1432                            .mb_4(),
1433                    )
1434                    .child(SplitButton::new(
1435                        ButtonLike::new("open-settings-ui")
1436                            .child(Label::new("Edit Settings").size(LabelSize::Small))
1437                            .on_click(|_, window, cx| {
1438                                window.dispatch_action(zed_actions::OpenSettings.boxed_clone(), cx);
1439                            }),
1440                        popover_menu.into_any_element(),
1441                    )),
1442            )
1443    }
1444}
1445
1446impl EventEmitter<()> for FailedToSpawnTerminal {}
1447
1448impl workspace::Item for FailedToSpawnTerminal {
1449    type Event = ();
1450
1451    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1452        SharedString::new_static("Failed to spawn terminal")
1453    }
1454}
1455
1456impl EventEmitter<PanelEvent> for TerminalPanel {}
1457
1458impl Render for TerminalPanel {
1459    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1460        let mut registrar = DivRegistrar::new(
1461            |panel, _, cx| {
1462                panel
1463                    .active_pane
1464                    .read(cx)
1465                    .toolbar()
1466                    .read(cx)
1467                    .item_of_type::<BufferSearchBar>()
1468            },
1469            cx,
1470        );
1471        BufferSearchBar::register(&mut registrar);
1472        let registrar = registrar.into_div();
1473        self.workspace
1474            .update(cx, |workspace, cx| {
1475                registrar.size_full().child(self.center.render(
1476                    workspace.zoomed_item(),
1477                    &workspace::PaneRenderContext {
1478                        follower_states: &HashMap::default(),
1479                        active_call: workspace.active_call(),
1480                        active_pane: &self.active_pane,
1481                        app_state: workspace.app_state(),
1482                        project: workspace.project(),
1483                        workspace: &workspace.weak_handle(),
1484                    },
1485                    window,
1486                    cx,
1487                ))
1488            })
1489            .ok()
1490            .map(|div| {
1491                div.on_action({
1492                    cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1493                        terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1494                    })
1495                })
1496                .on_action({
1497                    cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1498                        terminal_panel.activate_pane_in_direction(
1499                            SplitDirection::Right,
1500                            window,
1501                            cx,
1502                        );
1503                    })
1504                })
1505                .on_action({
1506                    cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1507                        terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1508                    })
1509                })
1510                .on_action({
1511                    cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1512                        terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1513                    })
1514                })
1515                .on_action(
1516                    cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1517                        let panes = terminal_panel.center.panes();
1518                        if let Some(ix) = panes
1519                            .iter()
1520                            .position(|pane| **pane == terminal_panel.active_pane)
1521                        {
1522                            let next_ix = (ix + 1) % panes.len();
1523                            window.focus(&panes[next_ix].focus_handle(cx), cx);
1524                        }
1525                    }),
1526                )
1527                .on_action(cx.listener(
1528                    |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1529                        let panes = terminal_panel.center.panes();
1530                        if let Some(ix) = panes
1531                            .iter()
1532                            .position(|pane| **pane == terminal_panel.active_pane)
1533                        {
1534                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1535                            window.focus(&panes[prev_ix].focus_handle(cx), cx);
1536                        }
1537                    },
1538                ))
1539                .on_action(
1540                    cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1541                        let panes = terminal_panel.center.panes();
1542                        if let Some(&pane) = panes.get(action.0) {
1543                            window.focus(&pane.read(cx).focus_handle(cx), cx);
1544                        } else {
1545                            let future =
1546                                terminal_panel.new_pane_with_active_terminal(true, window, cx);
1547                            cx.spawn_in(window, async move |terminal_panel, cx| {
1548                                if let Some(new_pane) = future.await {
1549                                    _ = terminal_panel.update_in(
1550                                        cx,
1551                                        |terminal_panel, window, cx| {
1552                                            terminal_panel
1553                                                .center
1554                                                .split(
1555                                                    &terminal_panel.active_pane,
1556                                                    &new_pane,
1557                                                    SplitDirection::Right,
1558                                                    cx,
1559                                                )
1560                                                .log_err();
1561                                            let new_pane = new_pane.read(cx);
1562                                            window.focus(&new_pane.focus_handle(cx), cx);
1563                                        },
1564                                    );
1565                                }
1566                            })
1567                            .detach();
1568                        }
1569                    }),
1570                )
1571                .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1572                    terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1573                }))
1574                .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1575                    terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1576                }))
1577                .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1578                    terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1579                }))
1580                .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1581                    terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1582                }))
1583                .on_action(cx.listener(|terminal_panel, _: &MovePaneLeft, _, cx| {
1584                    terminal_panel.move_pane_to_border(SplitDirection::Left, cx);
1585                }))
1586                .on_action(cx.listener(|terminal_panel, _: &MovePaneRight, _, cx| {
1587                    terminal_panel.move_pane_to_border(SplitDirection::Right, cx);
1588                }))
1589                .on_action(cx.listener(|terminal_panel, _: &MovePaneUp, _, cx| {
1590                    terminal_panel.move_pane_to_border(SplitDirection::Up, cx);
1591                }))
1592                .on_action(cx.listener(|terminal_panel, _: &MovePaneDown, _, cx| {
1593                    terminal_panel.move_pane_to_border(SplitDirection::Down, cx);
1594                }))
1595                .on_action(
1596                    cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1597                        let Some(&target_pane) =
1598                            terminal_panel.center.panes().get(action.destination)
1599                        else {
1600                            return;
1601                        };
1602                        move_active_item(
1603                            &terminal_panel.active_pane,
1604                            target_pane,
1605                            action.focus,
1606                            true,
1607                            window,
1608                            cx,
1609                        );
1610                    }),
1611                )
1612                .on_action(cx.listener(
1613                    |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1614                        let source_pane = &terminal_panel.active_pane;
1615                        if let Some(destination_pane) = terminal_panel
1616                            .center
1617                            .find_pane_in_direction(source_pane, action.direction, cx)
1618                        {
1619                            move_active_item(
1620                                source_pane,
1621                                destination_pane,
1622                                action.focus,
1623                                true,
1624                                window,
1625                                cx,
1626                            );
1627                        };
1628                    },
1629                ))
1630            })
1631            .unwrap_or_else(|| div())
1632    }
1633}
1634
1635impl Focusable for TerminalPanel {
1636    fn focus_handle(&self, cx: &App) -> FocusHandle {
1637        self.active_pane.focus_handle(cx)
1638    }
1639}
1640
1641impl Panel for TerminalPanel {
1642    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1643        match TerminalSettings::get_global(cx).dock {
1644            TerminalDockPosition::Left => DockPosition::Left,
1645            TerminalDockPosition::Bottom => DockPosition::Bottom,
1646            TerminalDockPosition::Right => DockPosition::Right,
1647        }
1648    }
1649
1650    fn position_is_valid(&self, _: DockPosition) -> bool {
1651        true
1652    }
1653
1654    fn set_position(
1655        &mut self,
1656        position: DockPosition,
1657        _window: &mut Window,
1658        cx: &mut Context<Self>,
1659    ) {
1660        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1661            let dock = match position {
1662                DockPosition::Left => TerminalDockPosition::Left,
1663                DockPosition::Bottom => TerminalDockPosition::Bottom,
1664                DockPosition::Right => TerminalDockPosition::Right,
1665            };
1666            settings.terminal.get_or_insert_default().dock = Some(dock);
1667        });
1668    }
1669
1670    fn size(&self, window: &Window, cx: &App) -> Pixels {
1671        let settings = TerminalSettings::get_global(cx);
1672        match self.position(window, cx) {
1673            DockPosition::Left | DockPosition::Right => {
1674                self.width.unwrap_or(settings.default_width)
1675            }
1676            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1677        }
1678    }
1679
1680    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1681        match self.position(window, cx) {
1682            DockPosition::Left | DockPosition::Right => self.width = size,
1683            DockPosition::Bottom => self.height = size,
1684        }
1685        cx.notify();
1686        cx.defer_in(window, |this, _, cx| {
1687            this.serialize(cx);
1688        })
1689    }
1690
1691    fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1692        self.active_pane.read(cx).is_zoomed()
1693    }
1694
1695    fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1696        for pane in self.center.panes() {
1697            pane.update(cx, |pane, cx| {
1698                pane.set_zoomed(zoomed, cx);
1699            })
1700        }
1701        cx.notify();
1702    }
1703
1704    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1705        let old_active = self.active;
1706        self.active = active;
1707        if !active || old_active == active || !self.has_no_terminals(cx) {
1708            return;
1709        }
1710        cx.defer_in(window, |this, window, cx| {
1711            let Ok(kind) = this
1712                .workspace
1713                .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1714            else {
1715                return;
1716            };
1717
1718            this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1719                .detach_and_log_err(cx)
1720        })
1721    }
1722
1723    fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1724        let count = self
1725            .center
1726            .panes()
1727            .into_iter()
1728            .map(|pane| pane.read(cx).items_len())
1729            .sum::<usize>();
1730        if count == 0 {
1731            None
1732        } else {
1733            Some(count.to_string())
1734        }
1735    }
1736
1737    fn persistent_name() -> &'static str {
1738        "TerminalPanel"
1739    }
1740
1741    fn panel_key() -> &'static str {
1742        TERMINAL_PANEL_KEY
1743    }
1744
1745    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1746        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1747            && TerminalSettings::get_global(cx).button
1748        {
1749            Some(IconName::TerminalAlt)
1750        } else {
1751            None
1752        }
1753    }
1754
1755    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1756        Some("Terminal Panel")
1757    }
1758
1759    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1760        Box::new(ToggleFocus)
1761    }
1762
1763    fn pane(&self) -> Option<Entity<Pane>> {
1764        Some(self.active_pane.clone())
1765    }
1766
1767    fn activation_priority(&self) -> u32 {
1768        1
1769    }
1770}
1771
1772struct TerminalProvider(Entity<TerminalPanel>);
1773
1774impl workspace::TerminalProvider for TerminalProvider {
1775    fn spawn(
1776        &self,
1777        task: SpawnInTerminal,
1778        window: &mut Window,
1779        cx: &mut App,
1780    ) -> Task<Option<Result<ExitStatus>>> {
1781        let terminal_panel = self.0.clone();
1782        window.spawn(cx, async move |cx| {
1783            let terminal = terminal_panel
1784                .update_in(cx, |terminal_panel, window, cx| {
1785                    terminal_panel.spawn_task(&task, window, cx)
1786                })
1787                .ok()?
1788                .await;
1789            match terminal {
1790                Ok(terminal) => {
1791                    let exit_status = terminal
1792                        .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1793                        .ok()?
1794                        .await?;
1795                    Some(Ok(exit_status))
1796                }
1797                Err(e) => Some(Err(e)),
1798            }
1799        })
1800    }
1801}
1802
1803struct InlineAssistTabBarButton {
1804    focus_handle: FocusHandle,
1805}
1806
1807impl Render for InlineAssistTabBarButton {
1808    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1809        let focus_handle = self.focus_handle.clone();
1810        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1811            .icon_size(IconSize::Small)
1812            .on_click(cx.listener(|_, _, window, cx| {
1813                window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1814            }))
1815            .tooltip(move |_window, cx| {
1816                Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1817            })
1818    }
1819}
1820
1821#[cfg(test)]
1822mod tests {
1823    use std::num::NonZero;
1824
1825    use super::*;
1826    use gpui::{TestAppContext, UpdateGlobal as _};
1827    use pretty_assertions::assert_eq;
1828    use project::FakeFs;
1829    use settings::SettingsStore;
1830
1831    #[test]
1832    fn test_prepare_empty_task() {
1833        let input = SpawnInTerminal::default();
1834        let shell = Shell::System;
1835
1836        let result = prepare_task_for_spawn(&input, &shell, false);
1837
1838        let expected_shell = util::get_system_shell();
1839        assert_eq!(result.env, HashMap::default());
1840        assert_eq!(result.cwd, None);
1841        assert_eq!(result.shell, Shell::System);
1842        assert_eq!(
1843            result.command,
1844            Some(expected_shell.clone()),
1845            "Empty tasks should spawn a -i shell"
1846        );
1847        assert_eq!(result.args, Vec::<String>::new());
1848        assert_eq!(
1849            result.command_label, expected_shell,
1850            "We show the shell launch for empty commands"
1851        );
1852    }
1853
1854    #[gpui::test]
1855    async fn test_bypass_max_tabs_limit(cx: &mut TestAppContext) {
1856        cx.executor().allow_parking();
1857        init_test(cx);
1858
1859        let fs = FakeFs::new(cx.executor());
1860        let project = Project::test(fs, [], cx).await;
1861        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1862
1863        let (window_handle, terminal_panel) = workspace
1864            .update(cx, |workspace, window, cx| {
1865                let window_handle = window.window_handle();
1866                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1867                (window_handle, terminal_panel)
1868            })
1869            .unwrap();
1870
1871        set_max_tabs(cx, Some(3));
1872
1873        for _ in 0..5 {
1874            let task = window_handle
1875                .update(cx, |_, window, cx| {
1876                    terminal_panel.update(cx, |panel, cx| {
1877                        panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1878                    })
1879                })
1880                .unwrap();
1881            task.await.unwrap();
1882        }
1883
1884        cx.run_until_parked();
1885
1886        let item_count =
1887            terminal_panel.read_with(cx, |panel, cx| panel.active_pane.read(cx).items_len());
1888
1889        assert_eq!(
1890            item_count, 5,
1891            "Terminal panel should bypass max_tabs limit and have all 5 terminals"
1892        );
1893    }
1894
1895    #[cfg(unix)]
1896    #[test]
1897    fn test_prepare_script_like_task() {
1898        let user_command = r#"REPO_URL=$(git remote get-url origin | sed -e \"s/^git@\\(.*\\):\\(.*\\)\\.git$/https:\\/\\/\\1\\/\\2/\"); COMMIT_SHA=$(git log -1 --format=\"%H\" -- \"${ZED_RELATIVE_FILE}\"); echo \"${REPO_URL}/blob/${COMMIT_SHA}/${ZED_RELATIVE_FILE}#L${ZED_ROW}-$(echo $(($(wc -l <<< \"$ZED_SELECTED_TEXT\") + $ZED_ROW - 1)))\" | xclip -selection clipboard"#.to_string();
1899        let expected_cwd = PathBuf::from("/some/work");
1900
1901        let input = SpawnInTerminal {
1902            command: Some(user_command.clone()),
1903            cwd: Some(expected_cwd.clone()),
1904            ..SpawnInTerminal::default()
1905        };
1906        let shell = Shell::System;
1907
1908        let result = prepare_task_for_spawn(&input, &shell, false);
1909
1910        let system_shell = util::get_system_shell();
1911        assert_eq!(result.env, HashMap::default());
1912        assert_eq!(result.cwd, Some(expected_cwd));
1913        assert_eq!(result.shell, Shell::System);
1914        assert_eq!(result.command, Some(system_shell.clone()));
1915        assert_eq!(
1916            result.args,
1917            vec!["-i".to_string(), "-c".to_string(), user_command.clone()],
1918            "User command should have been moved into the arguments, as we're spawning a new -i shell",
1919        );
1920        assert_eq!(
1921            result.command_label,
1922            format!(
1923                "{system_shell} {interactive}-c '{user_command}'",
1924                interactive = if cfg!(windows) { "" } else { "-i " }
1925            ),
1926            "We want to show to the user the entire command spawned"
1927        );
1928    }
1929
1930    #[gpui::test]
1931    async fn renders_error_if_default_shell_fails(cx: &mut TestAppContext) {
1932        cx.executor().allow_parking();
1933        init_test(cx);
1934
1935        cx.update(|cx| {
1936            SettingsStore::update_global(cx, |store, cx| {
1937                store.update_user_settings(cx, |settings| {
1938                    settings.terminal.get_or_insert_default().project.shell =
1939                        Some(settings::Shell::Program("__nonexistent_shell__".to_owned()));
1940                });
1941            });
1942        });
1943
1944        let fs = FakeFs::new(cx.executor());
1945        let project = Project::test(fs, [], cx).await;
1946        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1947
1948        let (window_handle, terminal_panel) = workspace
1949            .update(cx, |workspace, window, cx| {
1950                let window_handle = window.window_handle();
1951                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1952                (window_handle, terminal_panel)
1953            })
1954            .unwrap();
1955
1956        window_handle
1957            .update(cx, |_, window, cx| {
1958                terminal_panel.update(cx, |terminal_panel, cx| {
1959                    terminal_panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1960                })
1961            })
1962            .unwrap()
1963            .await
1964            .unwrap_err();
1965
1966        window_handle
1967            .update(cx, |_, _, cx| {
1968                terminal_panel.update(cx, |terminal_panel, cx| {
1969                    assert!(
1970                        terminal_panel
1971                            .active_pane
1972                            .read(cx)
1973                            .items()
1974                            .any(|item| item.downcast::<FailedToSpawnTerminal>().is_some()),
1975                        "should spawn `FailedToSpawnTerminal` pane"
1976                    );
1977                })
1978            })
1979            .unwrap();
1980    }
1981
1982    #[gpui::test]
1983    async fn test_local_terminal_in_local_project(cx: &mut TestAppContext) {
1984        cx.executor().allow_parking();
1985        init_test(cx);
1986
1987        let fs = FakeFs::new(cx.executor());
1988        let project = Project::test(fs, [], cx).await;
1989        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1990
1991        let (window_handle, terminal_panel) = workspace
1992            .update(cx, |workspace, window, cx| {
1993                let window_handle = window.window_handle();
1994                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1995                (window_handle, terminal_panel)
1996            })
1997            .unwrap();
1998
1999        let result = window_handle
2000            .update(cx, |_, window, cx| {
2001                terminal_panel.update(cx, |terminal_panel, cx| {
2002                    terminal_panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
2003                })
2004            })
2005            .unwrap()
2006            .await;
2007
2008        assert!(
2009            result.is_ok(),
2010            "local terminal should successfully create in local project"
2011        );
2012    }
2013
2014    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
2015        cx.update_global(|store: &mut SettingsStore, cx| {
2016            store.update_user_settings(cx, |settings| {
2017                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
2018            });
2019        });
2020    }
2021
2022    pub fn init_test(cx: &mut TestAppContext) {
2023        cx.update(|cx| {
2024            let store = SettingsStore::test(cx);
2025            cx.set_global(store);
2026            theme::init(theme::LoadThemes::JustBase, cx);
2027            editor::init(cx);
2028            crate::init(cx);
2029        });
2030    }
2031}