remote_servers.rs

   1use crate::{
   2    dev_container::start_dev_container,
   3    remote_connections::{
   4        Connection, RemoteConnectionModal, RemoteConnectionPrompt, SshConnection,
   5        SshConnectionHeader, SshSettings, connect, determine_paths_with_positions,
   6        open_remote_project,
   7    },
   8    ssh_config::parse_ssh_config_hosts,
   9};
  10use editor::Editor;
  11use file_finder::OpenPathDelegate;
  12use futures::{FutureExt, channel::oneshot, future::Shared, select};
  13use gpui::{
  14    AnyElement, App, ClickEvent, ClipboardItem, Context, DismissEvent, Entity, EventEmitter,
  15    FocusHandle, Focusable, PromptLevel, ScrollHandle, Subscription, Task, WeakEntity, Window,
  16    canvas,
  17};
  18use language::Point;
  19use log::info;
  20use paths::{global_ssh_config_file, user_ssh_config_file};
  21use picker::Picker;
  22use project::{Fs, Project};
  23use remote::{
  24    RemoteClient, RemoteConnectionOptions, SshConnectionOptions, WslConnectionOptions,
  25    remote_client::ConnectionIdentifier,
  26};
  27use settings::{
  28    RemoteProject, RemoteSettingsContent, Settings as _, SettingsStore, update_settings_file,
  29    watch_config_file,
  30};
  31use smol::stream::StreamExt as _;
  32use std::{
  33    borrow::Cow,
  34    collections::BTreeSet,
  35    path::PathBuf,
  36    rc::Rc,
  37    sync::{
  38        Arc,
  39        atomic::{self, AtomicUsize},
  40    },
  41};
  42use ui::{
  43    CommonAnimationExt, IconButtonShape, KeyBinding, List, ListItem, ListSeparator, Modal,
  44    ModalHeader, Navigable, NavigableEntry, Section, Tooltip, WithScrollbar, prelude::*,
  45};
  46use util::{
  47    ResultExt,
  48    paths::{PathStyle, RemotePathBuf},
  49    rel_path::RelPath,
  50};
  51use workspace::{
  52    ModalView, OpenOptions, Toast, Workspace,
  53    notifications::{DetachAndPromptErr, NotificationId},
  54    open_remote_project_with_existing_connection,
  55};
  56
  57pub struct RemoteServerProjects {
  58    mode: Mode,
  59    focus_handle: FocusHandle,
  60    workspace: WeakEntity<Workspace>,
  61    retained_connections: Vec<Entity<RemoteClient>>,
  62    ssh_config_updates: Task<()>,
  63    ssh_config_servers: BTreeSet<SharedString>,
  64    create_new_window: bool,
  65    _subscription: Subscription,
  66}
  67
  68struct CreateRemoteServer {
  69    address_editor: Entity<Editor>,
  70    address_error: Option<SharedString>,
  71    ssh_prompt: Option<Entity<RemoteConnectionPrompt>>,
  72    _creating: Option<Task<Option<()>>>,
  73}
  74
  75impl CreateRemoteServer {
  76    fn new(window: &mut Window, cx: &mut App) -> Self {
  77        let address_editor = cx.new(|cx| Editor::single_line(window, cx));
  78        address_editor.update(cx, |this, cx| {
  79            this.focus_handle(cx).focus(window, cx);
  80        });
  81        Self {
  82            address_editor,
  83            address_error: None,
  84            ssh_prompt: None,
  85            _creating: None,
  86        }
  87    }
  88}
  89
  90#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
  91enum DevContainerCreationProgress {
  92    Initial,
  93    Creating,
  94    Error(String),
  95}
  96
  97#[derive(Clone)]
  98struct CreateRemoteDevContainer {
  99    // 3 Navigable Options
 100    // - Create from devcontainer.json
 101    // - Edit devcontainer.json
 102    // - Go back
 103    entries: [NavigableEntry; 3],
 104    progress: DevContainerCreationProgress,
 105}
 106
 107impl CreateRemoteDevContainer {
 108    fn new(window: &mut Window, cx: &mut Context<RemoteServerProjects>) -> Self {
 109        let entries = std::array::from_fn(|_| NavigableEntry::focusable(cx));
 110        entries[0].focus_handle.focus(window, cx);
 111        Self {
 112            entries,
 113            progress: DevContainerCreationProgress::Initial,
 114        }
 115    }
 116
 117    fn progress(&mut self, progress: DevContainerCreationProgress) -> Self {
 118        self.progress = progress;
 119        self.clone()
 120    }
 121}
 122
 123#[cfg(target_os = "windows")]
 124struct AddWslDistro {
 125    picker: Entity<Picker<crate::wsl_picker::WslPickerDelegate>>,
 126    connection_prompt: Option<Entity<RemoteConnectionPrompt>>,
 127    _creating: Option<Task<()>>,
 128}
 129
 130#[cfg(target_os = "windows")]
 131impl AddWslDistro {
 132    fn new(window: &mut Window, cx: &mut Context<RemoteServerProjects>) -> Self {
 133        use crate::wsl_picker::{WslDistroSelected, WslPickerDelegate, WslPickerDismissed};
 134
 135        let delegate = WslPickerDelegate::new();
 136        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx).modal(false));
 137
 138        cx.subscribe_in(
 139            &picker,
 140            window,
 141            |this, _, _: &WslDistroSelected, window, cx| {
 142                this.confirm(&menu::Confirm, window, cx);
 143            },
 144        )
 145        .detach();
 146
 147        cx.subscribe_in(
 148            &picker,
 149            window,
 150            |this, _, _: &WslPickerDismissed, window, cx| {
 151                this.cancel(&menu::Cancel, window, cx);
 152            },
 153        )
 154        .detach();
 155
 156        AddWslDistro {
 157            picker,
 158            connection_prompt: None,
 159            _creating: None,
 160        }
 161    }
 162}
 163
 164enum ProjectPickerData {
 165    Ssh {
 166        connection_string: SharedString,
 167        nickname: Option<SharedString>,
 168    },
 169    Wsl {
 170        distro_name: SharedString,
 171    },
 172}
 173
 174struct ProjectPicker {
 175    data: ProjectPickerData,
 176    picker: Entity<Picker<OpenPathDelegate>>,
 177    _path_task: Shared<Task<Option<()>>>,
 178}
 179
 180struct EditNicknameState {
 181    index: SshServerIndex,
 182    editor: Entity<Editor>,
 183}
 184
 185impl EditNicknameState {
 186    fn new(index: SshServerIndex, window: &mut Window, cx: &mut App) -> Self {
 187        let this = Self {
 188            index,
 189            editor: cx.new(|cx| Editor::single_line(window, cx)),
 190        };
 191        let starting_text = SshSettings::get_global(cx)
 192            .ssh_connections()
 193            .nth(index.0)
 194            .and_then(|state| state.nickname)
 195            .filter(|text| !text.is_empty());
 196        this.editor.update(cx, |this, cx| {
 197            this.set_placeholder_text("Add a nickname for this server", window, cx);
 198            if let Some(starting_text) = starting_text {
 199                this.set_text(starting_text, window, cx);
 200            }
 201        });
 202        this.editor.focus_handle(cx).focus(window, cx);
 203        this
 204    }
 205}
 206
 207impl Focusable for ProjectPicker {
 208    fn focus_handle(&self, cx: &App) -> FocusHandle {
 209        self.picker.focus_handle(cx)
 210    }
 211}
 212
 213impl ProjectPicker {
 214    fn new(
 215        create_new_window: bool,
 216        index: ServerIndex,
 217        connection: RemoteConnectionOptions,
 218        project: Entity<Project>,
 219        home_dir: RemotePathBuf,
 220        workspace: WeakEntity<Workspace>,
 221        window: &mut Window,
 222        cx: &mut Context<RemoteServerProjects>,
 223    ) -> Entity<Self> {
 224        let (tx, rx) = oneshot::channel();
 225        let lister = project::DirectoryLister::Project(project.clone());
 226        let delegate = file_finder::OpenPathDelegate::new(tx, lister, false, cx);
 227
 228        let picker = cx.new(|cx| {
 229            let picker = Picker::uniform_list(delegate, window, cx)
 230                .width(rems(34.))
 231                .modal(false);
 232            picker.set_query(home_dir.to_string(), window, cx);
 233            picker
 234        });
 235
 236        let data = match &connection {
 237            RemoteConnectionOptions::Ssh(connection) => ProjectPickerData::Ssh {
 238                connection_string: connection.connection_string().into(),
 239                nickname: connection.nickname.clone().map(|nick| nick.into()),
 240            },
 241            RemoteConnectionOptions::Wsl(connection) => ProjectPickerData::Wsl {
 242                distro_name: connection.distro_name.clone().into(),
 243            },
 244            RemoteConnectionOptions::Docker(_) => ProjectPickerData::Ssh {
 245                // Not implemented as a project picker at this time
 246                connection_string: "".into(),
 247                nickname: None,
 248            },
 249        };
 250        let _path_task = cx
 251            .spawn_in(window, {
 252                let workspace = workspace;
 253                async move |this, cx| {
 254                    let Ok(Some(paths)) = rx.await else {
 255                        workspace
 256                            .update_in(cx, |workspace, window, cx| {
 257                                let fs = workspace.project().read(cx).fs().clone();
 258                                let weak = cx.entity().downgrade();
 259                                workspace.toggle_modal(window, cx, |window, cx| {
 260                                    RemoteServerProjects::new(
 261                                        create_new_window,
 262                                        fs,
 263                                        window,
 264                                        weak,
 265                                        cx,
 266                                    )
 267                                });
 268                            })
 269                            .log_err()?;
 270                        return None;
 271                    };
 272
 273                    let app_state = workspace
 274                        .read_with(cx, |workspace, _| workspace.app_state().clone())
 275                        .ok()?;
 276
 277                    let remote_connection = project
 278                        .read_with(cx, |project, cx| {
 279                            project.remote_client()?.read(cx).connection()
 280                        })
 281                        .ok()??;
 282
 283                    let (paths, paths_with_positions) =
 284                        determine_paths_with_positions(&remote_connection, paths).await;
 285
 286                    cx.update(|_, cx| {
 287                        let fs = app_state.fs.clone();
 288                        update_settings_file(fs, cx, {
 289                            let paths = paths
 290                                .iter()
 291                                .map(|path| path.to_string_lossy().into_owned())
 292                                .collect();
 293                            move |settings, _| match index {
 294                                ServerIndex::Ssh(index) => {
 295                                    if let Some(server) = settings
 296                                        .remote
 297                                        .ssh_connections
 298                                        .as_mut()
 299                                        .and_then(|connections| connections.get_mut(index.0))
 300                                    {
 301                                        server.projects.insert(RemoteProject { paths });
 302                                    };
 303                                }
 304                                ServerIndex::Wsl(index) => {
 305                                    if let Some(server) = settings
 306                                        .remote
 307                                        .wsl_connections
 308                                        .as_mut()
 309                                        .and_then(|connections| connections.get_mut(index.0))
 310                                    {
 311                                        server.projects.insert(RemoteProject { paths });
 312                                    };
 313                                }
 314                            }
 315                        });
 316                    })
 317                    .log_err();
 318
 319                    let options = cx
 320                        .update(|_, cx| (app_state.build_window_options)(None, cx))
 321                        .log_err()?;
 322                    let window = cx
 323                        .open_window(options, |window, cx| {
 324                            cx.new(|cx| {
 325                                telemetry::event!("SSH Project Created");
 326                                Workspace::new(None, project.clone(), app_state.clone(), window, cx)
 327                            })
 328                        })
 329                        .log_err()?;
 330
 331                    let items = open_remote_project_with_existing_connection(
 332                        connection, project, paths, app_state, window, cx,
 333                    )
 334                    .await
 335                    .log_err();
 336
 337                    if let Some(items) = items {
 338                        for (item, path) in items.into_iter().zip(paths_with_positions) {
 339                            let Some(item) = item else {
 340                                continue;
 341                            };
 342                            let Some(row) = path.row else {
 343                                continue;
 344                            };
 345                            if let Some(active_editor) = item.downcast::<Editor>() {
 346                                window
 347                                    .update(cx, |_, window, cx| {
 348                                        active_editor.update(cx, |editor, cx| {
 349                                            let row = row.saturating_sub(1);
 350                                            let col = path.column.unwrap_or(0).saturating_sub(1);
 351                                            editor.go_to_singleton_buffer_point(
 352                                                Point::new(row, col),
 353                                                window,
 354                                                cx,
 355                                            );
 356                                        });
 357                                    })
 358                                    .ok();
 359                            }
 360                        }
 361                    }
 362
 363                    this.update(cx, |_, cx| {
 364                        cx.emit(DismissEvent);
 365                    })
 366                    .ok();
 367                    Some(())
 368                }
 369            })
 370            .shared();
 371        cx.new(|_| Self {
 372            _path_task,
 373            picker,
 374            data,
 375        })
 376    }
 377}
 378
 379impl gpui::Render for ProjectPicker {
 380    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 381        v_flex()
 382            .child(match &self.data {
 383                ProjectPickerData::Ssh {
 384                    connection_string,
 385                    nickname,
 386                } => SshConnectionHeader {
 387                    connection_string: connection_string.clone(),
 388                    paths: Default::default(),
 389                    nickname: nickname.clone(),
 390                    is_wsl: false,
 391                    is_devcontainer: false,
 392                }
 393                .render(window, cx),
 394                ProjectPickerData::Wsl { distro_name } => SshConnectionHeader {
 395                    connection_string: distro_name.clone(),
 396                    paths: Default::default(),
 397                    nickname: None,
 398                    is_wsl: true,
 399                    is_devcontainer: false,
 400                }
 401                .render(window, cx),
 402            })
 403            .child(
 404                div()
 405                    .border_t_1()
 406                    .border_color(cx.theme().colors().border_variant)
 407                    .child(self.picker.clone()),
 408            )
 409    }
 410}
 411
 412#[repr(transparent)]
 413#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
 414struct SshServerIndex(usize);
 415impl std::fmt::Display for SshServerIndex {
 416    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 417        self.0.fmt(f)
 418    }
 419}
 420
 421#[repr(transparent)]
 422#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
 423struct WslServerIndex(usize);
 424impl std::fmt::Display for WslServerIndex {
 425    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 426        self.0.fmt(f)
 427    }
 428}
 429
 430#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
 431enum ServerIndex {
 432    Ssh(SshServerIndex),
 433    Wsl(WslServerIndex),
 434}
 435impl From<SshServerIndex> for ServerIndex {
 436    fn from(index: SshServerIndex) -> Self {
 437        Self::Ssh(index)
 438    }
 439}
 440impl From<WslServerIndex> for ServerIndex {
 441    fn from(index: WslServerIndex) -> Self {
 442        Self::Wsl(index)
 443    }
 444}
 445
 446#[derive(Clone)]
 447enum RemoteEntry {
 448    Project {
 449        open_folder: NavigableEntry,
 450        projects: Vec<(NavigableEntry, RemoteProject)>,
 451        configure: NavigableEntry,
 452        connection: Connection,
 453        index: ServerIndex,
 454    },
 455    SshConfig {
 456        open_folder: NavigableEntry,
 457        host: SharedString,
 458    },
 459}
 460
 461impl RemoteEntry {
 462    fn is_from_zed(&self) -> bool {
 463        matches!(self, Self::Project { .. })
 464    }
 465
 466    fn connection(&self) -> Cow<'_, Connection> {
 467        match self {
 468            Self::Project { connection, .. } => Cow::Borrowed(connection),
 469            Self::SshConfig { host, .. } => Cow::Owned(
 470                SshConnection {
 471                    host: host.clone(),
 472                    ..SshConnection::default()
 473                }
 474                .into(),
 475            ),
 476        }
 477    }
 478}
 479
 480#[derive(Clone)]
 481struct DefaultState {
 482    scroll_handle: ScrollHandle,
 483    add_new_server: NavigableEntry,
 484    add_new_devcontainer: NavigableEntry,
 485    add_new_wsl: NavigableEntry,
 486    servers: Vec<RemoteEntry>,
 487}
 488
 489impl DefaultState {
 490    fn new(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self {
 491        let handle = ScrollHandle::new();
 492        let add_new_server = NavigableEntry::new(&handle, cx);
 493        let add_new_devcontainer = NavigableEntry::new(&handle, cx);
 494        let add_new_wsl = NavigableEntry::new(&handle, cx);
 495
 496        let ssh_settings = SshSettings::get_global(cx);
 497        let read_ssh_config = ssh_settings.read_ssh_config;
 498
 499        let ssh_servers = ssh_settings
 500            .ssh_connections()
 501            .enumerate()
 502            .map(|(index, connection)| {
 503                let open_folder = NavigableEntry::new(&handle, cx);
 504                let configure = NavigableEntry::new(&handle, cx);
 505                let projects = connection
 506                    .projects
 507                    .iter()
 508                    .map(|project| (NavigableEntry::new(&handle, cx), project.clone()))
 509                    .collect();
 510                RemoteEntry::Project {
 511                    open_folder,
 512                    configure,
 513                    projects,
 514                    index: ServerIndex::Ssh(SshServerIndex(index)),
 515                    connection: connection.into(),
 516                }
 517            });
 518
 519        let wsl_servers = ssh_settings
 520            .wsl_connections()
 521            .enumerate()
 522            .map(|(index, connection)| {
 523                let open_folder = NavigableEntry::new(&handle, cx);
 524                let configure = NavigableEntry::new(&handle, cx);
 525                let projects = connection
 526                    .projects
 527                    .iter()
 528                    .map(|project| (NavigableEntry::new(&handle, cx), project.clone()))
 529                    .collect();
 530                RemoteEntry::Project {
 531                    open_folder,
 532                    configure,
 533                    projects,
 534                    index: ServerIndex::Wsl(WslServerIndex(index)),
 535                    connection: connection.into(),
 536                }
 537            });
 538
 539        let mut servers = ssh_servers.chain(wsl_servers).collect::<Vec<RemoteEntry>>();
 540
 541        if read_ssh_config {
 542            let mut extra_servers_from_config = ssh_config_servers.clone();
 543            for server in &servers {
 544                if let RemoteEntry::Project {
 545                    connection: Connection::Ssh(ssh_options),
 546                    ..
 547                } = server
 548                {
 549                    extra_servers_from_config.remove(&SharedString::new(ssh_options.host.clone()));
 550                }
 551            }
 552            servers.extend(extra_servers_from_config.into_iter().map(|host| {
 553                RemoteEntry::SshConfig {
 554                    open_folder: NavigableEntry::new(&handle, cx),
 555                    host,
 556                }
 557            }));
 558        }
 559
 560        Self {
 561            scroll_handle: handle,
 562            add_new_server,
 563            add_new_devcontainer,
 564            add_new_wsl,
 565            servers,
 566        }
 567    }
 568}
 569
 570#[derive(Clone)]
 571enum ViewServerOptionsState {
 572    Ssh {
 573        connection: SshConnectionOptions,
 574        server_index: SshServerIndex,
 575        entries: [NavigableEntry; 4],
 576    },
 577    Wsl {
 578        connection: WslConnectionOptions,
 579        server_index: WslServerIndex,
 580        entries: [NavigableEntry; 2],
 581    },
 582}
 583
 584impl ViewServerOptionsState {
 585    fn entries(&self) -> &[NavigableEntry] {
 586        match self {
 587            Self::Ssh { entries, .. } => entries,
 588            Self::Wsl { entries, .. } => entries,
 589        }
 590    }
 591}
 592
 593enum Mode {
 594    Default(DefaultState),
 595    ViewServerOptions(ViewServerOptionsState),
 596    EditNickname(EditNicknameState),
 597    ProjectPicker(Entity<ProjectPicker>),
 598    CreateRemoteServer(CreateRemoteServer),
 599    CreateRemoteDevContainer(CreateRemoteDevContainer),
 600    #[cfg(target_os = "windows")]
 601    AddWslDistro(AddWslDistro),
 602}
 603
 604impl Mode {
 605    fn default_mode(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self {
 606        Self::Default(DefaultState::new(ssh_config_servers, cx))
 607    }
 608}
 609
 610impl RemoteServerProjects {
 611    #[cfg(target_os = "windows")]
 612    pub fn wsl(
 613        create_new_window: bool,
 614        fs: Arc<dyn Fs>,
 615        window: &mut Window,
 616        workspace: WeakEntity<Workspace>,
 617        cx: &mut Context<Self>,
 618    ) -> Self {
 619        Self::new_inner(
 620            Mode::AddWslDistro(AddWslDistro::new(window, cx)),
 621            create_new_window,
 622            fs,
 623            window,
 624            workspace,
 625            cx,
 626        )
 627    }
 628
 629    pub fn new(
 630        create_new_window: bool,
 631        fs: Arc<dyn Fs>,
 632        window: &mut Window,
 633        workspace: WeakEntity<Workspace>,
 634        cx: &mut Context<Self>,
 635    ) -> Self {
 636        Self::new_inner(
 637            Mode::default_mode(&BTreeSet::new(), cx),
 638            create_new_window,
 639            fs,
 640            window,
 641            workspace,
 642            cx,
 643        )
 644    }
 645
 646    /// Creates a new RemoteServerProjects modal that opens directly in dev container creation mode.
 647    /// Used when suggesting dev container connection from toast notification.
 648    pub fn new_dev_container(
 649        fs: Arc<dyn Fs>,
 650        window: &mut Window,
 651        workspace: WeakEntity<Workspace>,
 652        cx: &mut Context<Self>,
 653    ) -> Self {
 654        Self::new_inner(
 655            Mode::CreateRemoteDevContainer(
 656                CreateRemoteDevContainer::new(window, cx)
 657                    .progress(DevContainerCreationProgress::Creating),
 658            ),
 659            false,
 660            fs,
 661            window,
 662            workspace,
 663            cx,
 664        )
 665    }
 666
 667    pub fn popover(
 668        fs: Arc<dyn Fs>,
 669        workspace: WeakEntity<Workspace>,
 670        create_new_window: bool,
 671        window: &mut Window,
 672        cx: &mut App,
 673    ) -> Entity<Self> {
 674        cx.new(|cx| {
 675            let server = Self::new(create_new_window, fs, window, workspace, cx);
 676            server.focus_handle(cx).focus(window, cx);
 677            server
 678        })
 679    }
 680
 681    fn new_inner(
 682        mode: Mode,
 683        create_new_window: bool,
 684        fs: Arc<dyn Fs>,
 685        window: &mut Window,
 686        workspace: WeakEntity<Workspace>,
 687        cx: &mut Context<Self>,
 688    ) -> Self {
 689        let focus_handle = cx.focus_handle();
 690        let mut read_ssh_config = SshSettings::get_global(cx).read_ssh_config;
 691        let ssh_config_updates = if read_ssh_config {
 692            spawn_ssh_config_watch(fs.clone(), cx)
 693        } else {
 694            Task::ready(())
 695        };
 696
 697        let mut base_style = window.text_style();
 698        base_style.refine(&gpui::TextStyleRefinement {
 699            color: Some(cx.theme().colors().editor_foreground),
 700            ..Default::default()
 701        });
 702
 703        let _subscription =
 704            cx.observe_global_in::<SettingsStore>(window, move |recent_projects, _, cx| {
 705                let new_read_ssh_config = SshSettings::get_global(cx).read_ssh_config;
 706                if read_ssh_config != new_read_ssh_config {
 707                    read_ssh_config = new_read_ssh_config;
 708                    if read_ssh_config {
 709                        recent_projects.ssh_config_updates = spawn_ssh_config_watch(fs.clone(), cx);
 710                    } else {
 711                        recent_projects.ssh_config_servers.clear();
 712                        recent_projects.ssh_config_updates = Task::ready(());
 713                    }
 714                }
 715            });
 716
 717        Self {
 718            mode,
 719            focus_handle,
 720            workspace,
 721            retained_connections: Vec::new(),
 722            ssh_config_updates,
 723            ssh_config_servers: BTreeSet::new(),
 724            create_new_window,
 725            _subscription,
 726        }
 727    }
 728
 729    fn project_picker(
 730        create_new_window: bool,
 731        index: ServerIndex,
 732        connection_options: remote::RemoteConnectionOptions,
 733        project: Entity<Project>,
 734        home_dir: RemotePathBuf,
 735        window: &mut Window,
 736        cx: &mut Context<Self>,
 737        workspace: WeakEntity<Workspace>,
 738    ) -> Self {
 739        let fs = project.read(cx).fs().clone();
 740        let mut this = Self::new(create_new_window, fs, window, workspace.clone(), cx);
 741        this.mode = Mode::ProjectPicker(ProjectPicker::new(
 742            create_new_window,
 743            index,
 744            connection_options,
 745            project,
 746            home_dir,
 747            workspace,
 748            window,
 749            cx,
 750        ));
 751        cx.notify();
 752
 753        this
 754    }
 755
 756    fn create_ssh_server(
 757        &mut self,
 758        editor: Entity<Editor>,
 759        window: &mut Window,
 760        cx: &mut Context<Self>,
 761    ) {
 762        let input = get_text(&editor, cx);
 763        if input.is_empty() {
 764            return;
 765        }
 766
 767        let connection_options = match SshConnectionOptions::parse_command_line(&input) {
 768            Ok(c) => c,
 769            Err(e) => {
 770                self.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 771                    address_editor: editor,
 772                    address_error: Some(format!("could not parse: {:?}", e).into()),
 773                    ssh_prompt: None,
 774                    _creating: None,
 775                });
 776                return;
 777            }
 778        };
 779        let ssh_prompt = cx.new(|cx| {
 780            RemoteConnectionPrompt::new(
 781                connection_options.connection_string(),
 782                connection_options.nickname.clone(),
 783                false,
 784                false,
 785                window,
 786                cx,
 787            )
 788        });
 789
 790        let connection = connect(
 791            ConnectionIdentifier::setup(),
 792            RemoteConnectionOptions::Ssh(connection_options.clone()),
 793            ssh_prompt.clone(),
 794            window,
 795            cx,
 796        )
 797        .prompt_err("Failed to connect", window, cx, |_, _, _| None);
 798
 799        let address_editor = editor.clone();
 800        let creating = cx.spawn_in(window, async move |this, cx| {
 801            match connection.await {
 802                Some(Some(client)) => this
 803                    .update_in(cx, |this, window, cx| {
 804                        info!("ssh server created");
 805                        telemetry::event!("SSH Server Created");
 806                        this.retained_connections.push(client);
 807                        this.add_ssh_server(connection_options, cx);
 808                        this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
 809                        this.focus_handle(cx).focus(window, cx);
 810                        cx.notify()
 811                    })
 812                    .log_err(),
 813                _ => this
 814                    .update(cx, |this, cx| {
 815                        address_editor.update(cx, |this, _| {
 816                            this.set_read_only(false);
 817                        });
 818                        this.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 819                            address_editor,
 820                            address_error: None,
 821                            ssh_prompt: None,
 822                            _creating: None,
 823                        });
 824                        cx.notify()
 825                    })
 826                    .log_err(),
 827            };
 828            None
 829        });
 830
 831        editor.update(cx, |this, _| {
 832            this.set_read_only(true);
 833        });
 834        self.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 835            address_editor: editor,
 836            address_error: None,
 837            ssh_prompt: Some(ssh_prompt),
 838            _creating: Some(creating),
 839        });
 840    }
 841
 842    #[cfg(target_os = "windows")]
 843    fn connect_wsl_distro(
 844        &mut self,
 845        picker: Entity<Picker<crate::wsl_picker::WslPickerDelegate>>,
 846        distro: String,
 847        window: &mut Window,
 848        cx: &mut Context<Self>,
 849    ) {
 850        let connection_options = WslConnectionOptions {
 851            distro_name: distro,
 852            user: None,
 853        };
 854
 855        let prompt = cx.new(|cx| {
 856            RemoteConnectionPrompt::new(
 857                connection_options.distro_name.clone(),
 858                None,
 859                true,
 860                false,
 861                window,
 862                cx,
 863            )
 864        });
 865        let connection = connect(
 866            ConnectionIdentifier::setup(),
 867            connection_options.clone().into(),
 868            prompt.clone(),
 869            window,
 870            cx,
 871        )
 872        .prompt_err("Failed to connect", window, cx, |_, _, _| None);
 873
 874        let wsl_picker = picker.clone();
 875        let creating = cx.spawn_in(window, async move |this, cx| {
 876            match connection.await {
 877                Some(Some(client)) => this.update_in(cx, |this, window, cx| {
 878                    telemetry::event!("WSL Distro Added");
 879                    this.retained_connections.push(client);
 880                    let Some(fs) = this
 881                        .workspace
 882                        .read_with(cx, |workspace, cx| {
 883                            workspace.project().read(cx).fs().clone()
 884                        })
 885                        .log_err()
 886                    else {
 887                        return;
 888                    };
 889
 890                    crate::add_wsl_distro(fs, &connection_options, cx);
 891                    this.mode = Mode::default_mode(&BTreeSet::new(), cx);
 892                    this.focus_handle(cx).focus(window, cx);
 893                    cx.notify();
 894                }),
 895                _ => this.update(cx, |this, cx| {
 896                    this.mode = Mode::AddWslDistro(AddWslDistro {
 897                        picker: wsl_picker,
 898                        connection_prompt: None,
 899                        _creating: None,
 900                    });
 901                    cx.notify();
 902                }),
 903            }
 904            .log_err();
 905        });
 906
 907        self.mode = Mode::AddWslDistro(AddWslDistro {
 908            picker,
 909            connection_prompt: Some(prompt),
 910            _creating: Some(creating),
 911        });
 912    }
 913
 914    fn view_server_options(
 915        &mut self,
 916        (server_index, connection): (ServerIndex, RemoteConnectionOptions),
 917        window: &mut Window,
 918        cx: &mut Context<Self>,
 919    ) {
 920        self.mode = Mode::ViewServerOptions(match (server_index, connection) {
 921            (ServerIndex::Ssh(server_index), RemoteConnectionOptions::Ssh(connection)) => {
 922                ViewServerOptionsState::Ssh {
 923                    connection,
 924                    server_index,
 925                    entries: std::array::from_fn(|_| NavigableEntry::focusable(cx)),
 926                }
 927            }
 928            (ServerIndex::Wsl(server_index), RemoteConnectionOptions::Wsl(connection)) => {
 929                ViewServerOptionsState::Wsl {
 930                    connection,
 931                    server_index,
 932                    entries: std::array::from_fn(|_| NavigableEntry::focusable(cx)),
 933                }
 934            }
 935            _ => {
 936                log::error!("server index and connection options mismatch");
 937                self.mode = Mode::default_mode(&BTreeSet::default(), cx);
 938                return;
 939            }
 940        });
 941        self.focus_handle(cx).focus(window, cx);
 942        cx.notify();
 943    }
 944
 945    fn view_in_progress_dev_container(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 946        self.mode = Mode::CreateRemoteDevContainer(
 947            CreateRemoteDevContainer::new(window, cx)
 948                .progress(DevContainerCreationProgress::Creating),
 949        );
 950        self.focus_handle(cx).focus(window, cx);
 951        cx.notify();
 952    }
 953
 954    fn create_remote_project(
 955        &mut self,
 956        index: ServerIndex,
 957        connection_options: RemoteConnectionOptions,
 958        window: &mut Window,
 959        cx: &mut Context<Self>,
 960    ) {
 961        let Some(workspace) = self.workspace.upgrade() else {
 962            return;
 963        };
 964
 965        let create_new_window = self.create_new_window;
 966        workspace.update(cx, |_, cx| {
 967            cx.defer_in(window, move |workspace, window, cx| {
 968                let app_state = workspace.app_state().clone();
 969                workspace.toggle_modal(window, cx, |window, cx| {
 970                    RemoteConnectionModal::new(&connection_options, Vec::new(), window, cx)
 971                });
 972                let prompt = workspace
 973                    .active_modal::<RemoteConnectionModal>(cx)
 974                    .unwrap()
 975                    .read(cx)
 976                    .prompt
 977                    .clone();
 978
 979                let connect = connect(
 980                    ConnectionIdentifier::setup(),
 981                    connection_options.clone(),
 982                    prompt,
 983                    window,
 984                    cx,
 985                )
 986                .prompt_err("Failed to connect", window, cx, |_, _, _| None);
 987
 988                cx.spawn_in(window, async move |workspace, cx| {
 989                    let session = connect.await;
 990
 991                    workspace.update(cx, |workspace, cx| {
 992                        if let Some(prompt) = workspace.active_modal::<RemoteConnectionModal>(cx) {
 993                            prompt.update(cx, |prompt, cx| prompt.finished(cx))
 994                        }
 995                    })?;
 996
 997                    let Some(Some(session)) = session else {
 998                        return workspace.update_in(cx, |workspace, window, cx| {
 999                            let weak = cx.entity().downgrade();
1000                            let fs = workspace.project().read(cx).fs().clone();
1001                            workspace.toggle_modal(window, cx, |window, cx| {
1002                                RemoteServerProjects::new(create_new_window, fs, window, weak, cx)
1003                            });
1004                        });
1005                    };
1006
1007                    let (path_style, project) = cx.update(|_, cx| {
1008                        (
1009                            session.read(cx).path_style(),
1010                            project::Project::remote(
1011                                session,
1012                                app_state.client.clone(),
1013                                app_state.node_runtime.clone(),
1014                                app_state.user_store.clone(),
1015                                app_state.languages.clone(),
1016                                app_state.fs.clone(),
1017                                true,
1018                                cx,
1019                            ),
1020                        )
1021                    })?;
1022
1023                    let home_dir = project
1024                        .read_with(cx, |project, cx| project.resolve_abs_path("~", cx))?
1025                        .await
1026                        .and_then(|path| path.into_abs_path())
1027                        .map(|path| RemotePathBuf::new(path, path_style))
1028                        .unwrap_or_else(|| match path_style {
1029                            PathStyle::Posix => RemotePathBuf::from_str("/", PathStyle::Posix),
1030                            PathStyle::Windows => {
1031                                RemotePathBuf::from_str("C:\\", PathStyle::Windows)
1032                            }
1033                        });
1034
1035                    workspace
1036                        .update_in(cx, |workspace, window, cx| {
1037                            let weak = cx.entity().downgrade();
1038                            workspace.toggle_modal(window, cx, |window, cx| {
1039                                RemoteServerProjects::project_picker(
1040                                    create_new_window,
1041                                    index,
1042                                    connection_options,
1043                                    project,
1044                                    home_dir,
1045                                    window,
1046                                    cx,
1047                                    weak,
1048                                )
1049                            });
1050                        })
1051                        .ok();
1052                    Ok(())
1053                })
1054                .detach();
1055            })
1056        })
1057    }
1058
1059    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
1060        match &self.mode {
1061            Mode::Default(_) | Mode::ViewServerOptions(_) => {}
1062            Mode::ProjectPicker(_) => {}
1063            Mode::CreateRemoteServer(state) => {
1064                if let Some(prompt) = state.ssh_prompt.as_ref() {
1065                    prompt.update(cx, |prompt, cx| {
1066                        prompt.confirm(window, cx);
1067                    });
1068                    return;
1069                }
1070
1071                self.create_ssh_server(state.address_editor.clone(), window, cx);
1072            }
1073            Mode::CreateRemoteDevContainer(_) => {}
1074            Mode::EditNickname(state) => {
1075                let text = Some(state.editor.read(cx).text(cx)).filter(|text| !text.is_empty());
1076                let index = state.index;
1077                self.update_settings_file(cx, move |setting, _| {
1078                    if let Some(connections) = setting.ssh_connections.as_mut()
1079                        && let Some(connection) = connections.get_mut(index.0)
1080                    {
1081                        connection.nickname = text;
1082                    }
1083                });
1084                self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
1085                self.focus_handle.focus(window, cx);
1086            }
1087            #[cfg(target_os = "windows")]
1088            Mode::AddWslDistro(state) => {
1089                let delegate = &state.picker.read(cx).delegate;
1090                let distro = delegate.selected_distro().unwrap();
1091                self.connect_wsl_distro(state.picker.clone(), distro, window, cx);
1092            }
1093        }
1094    }
1095
1096    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
1097        match &self.mode {
1098            Mode::Default(_) => cx.emit(DismissEvent),
1099            Mode::CreateRemoteServer(state) if state.ssh_prompt.is_some() => {
1100                let new_state = CreateRemoteServer::new(window, cx);
1101                let old_prompt = state.address_editor.read(cx).text(cx);
1102                new_state.address_editor.update(cx, |this, cx| {
1103                    this.set_text(old_prompt, window, cx);
1104                });
1105
1106                self.mode = Mode::CreateRemoteServer(new_state);
1107                cx.notify();
1108            }
1109            _ => {
1110                self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
1111                self.focus_handle(cx).focus(window, cx);
1112                cx.notify();
1113            }
1114        }
1115    }
1116
1117    fn render_remote_connection(
1118        &mut self,
1119        ix: usize,
1120        remote_server: RemoteEntry,
1121        window: &mut Window,
1122        cx: &mut Context<Self>,
1123    ) -> impl IntoElement {
1124        let connection = remote_server.connection().into_owned();
1125
1126        let (main_label, aux_label, is_wsl) = match &connection {
1127            Connection::Ssh(connection) => {
1128                if let Some(nickname) = connection.nickname.clone() {
1129                    let aux_label = SharedString::from(format!("({})", connection.host));
1130                    (nickname.into(), Some(aux_label), false)
1131                } else {
1132                    (connection.host.clone(), None, false)
1133                }
1134            }
1135            Connection::Wsl(wsl_connection_options) => {
1136                (wsl_connection_options.distro_name.clone(), None, true)
1137            }
1138            Connection::DevContainer(dev_container_options) => {
1139                (dev_container_options.name.clone(), None, false)
1140            }
1141        };
1142        v_flex()
1143            .w_full()
1144            .child(ListSeparator)
1145            .child(
1146                h_flex()
1147                    .group("ssh-server")
1148                    .w_full()
1149                    .pt_0p5()
1150                    .px_3()
1151                    .gap_1()
1152                    .overflow_hidden()
1153                    .child(
1154                        h_flex()
1155                            .gap_1()
1156                            .max_w_96()
1157                            .overflow_hidden()
1158                            .text_ellipsis()
1159                            .when(is_wsl, |this| {
1160                                this.child(
1161                                    Label::new("WSL:")
1162                                        .size(LabelSize::Small)
1163                                        .color(Color::Muted),
1164                                )
1165                            })
1166                            .child(
1167                                Label::new(main_label)
1168                                    .size(LabelSize::Small)
1169                                    .color(Color::Muted),
1170                            ),
1171                    )
1172                    .children(
1173                        aux_label.map(|label| {
1174                            Label::new(label).size(LabelSize::Small).color(Color::Muted)
1175                        }),
1176                    ),
1177            )
1178            .child(match &remote_server {
1179                RemoteEntry::Project {
1180                    open_folder,
1181                    projects,
1182                    configure,
1183                    connection,
1184                    index,
1185                } => {
1186                    let index = *index;
1187                    List::new()
1188                        .empty_message("No projects.")
1189                        .children(projects.iter().enumerate().map(|(pix, p)| {
1190                            v_flex().gap_0p5().child(self.render_remote_project(
1191                                index,
1192                                remote_server.clone(),
1193                                pix,
1194                                p,
1195                                window,
1196                                cx,
1197                            ))
1198                        }))
1199                        .child(
1200                            h_flex()
1201                                .id(("new-remote-project-container", ix))
1202                                .track_focus(&open_folder.focus_handle)
1203                                .anchor_scroll(open_folder.scroll_anchor.clone())
1204                                .on_action(cx.listener({
1205                                    let connection = connection.clone();
1206                                    move |this, _: &menu::Confirm, window, cx| {
1207                                        this.create_remote_project(
1208                                            index,
1209                                            connection.clone().into(),
1210                                            window,
1211                                            cx,
1212                                        );
1213                                    }
1214                                }))
1215                                .child(
1216                                    ListItem::new(("new-remote-project", ix))
1217                                        .toggle_state(
1218                                            open_folder.focus_handle.contains_focused(window, cx),
1219                                        )
1220                                        .inset(true)
1221                                        .spacing(ui::ListItemSpacing::Sparse)
1222                                        .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
1223                                        .child(Label::new("Open Folder"))
1224                                        .on_click(cx.listener({
1225                                            let connection = connection.clone();
1226                                            move |this, _, window, cx| {
1227                                                this.create_remote_project(
1228                                                    index,
1229                                                    connection.clone().into(),
1230                                                    window,
1231                                                    cx,
1232                                                );
1233                                            }
1234                                        })),
1235                                ),
1236                        )
1237                        .child(
1238                            h_flex()
1239                                .id(("server-options-container", ix))
1240                                .track_focus(&configure.focus_handle)
1241                                .anchor_scroll(configure.scroll_anchor.clone())
1242                                .on_action(cx.listener({
1243                                    let connection = connection.clone();
1244                                    move |this, _: &menu::Confirm, window, cx| {
1245                                        this.view_server_options(
1246                                            (index, connection.clone().into()),
1247                                            window,
1248                                            cx,
1249                                        );
1250                                    }
1251                                }))
1252                                .child(
1253                                    ListItem::new(("server-options", ix))
1254                                        .toggle_state(
1255                                            configure.focus_handle.contains_focused(window, cx),
1256                                        )
1257                                        .inset(true)
1258                                        .spacing(ui::ListItemSpacing::Sparse)
1259                                        .start_slot(
1260                                            Icon::new(IconName::Settings).color(Color::Muted),
1261                                        )
1262                                        .child(Label::new("View Server Options"))
1263                                        .on_click(cx.listener({
1264                                            let ssh_connection = connection.clone();
1265                                            move |this, _, window, cx| {
1266                                                this.view_server_options(
1267                                                    (index, ssh_connection.clone().into()),
1268                                                    window,
1269                                                    cx,
1270                                                );
1271                                            }
1272                                        })),
1273                                ),
1274                        )
1275                }
1276                RemoteEntry::SshConfig { open_folder, host } => List::new().child(
1277                    h_flex()
1278                        .id(("new-remote-project-container", ix))
1279                        .track_focus(&open_folder.focus_handle)
1280                        .anchor_scroll(open_folder.scroll_anchor.clone())
1281                        .on_action(cx.listener({
1282                            let connection = connection.clone();
1283                            let host = host.clone();
1284                            move |this, _: &menu::Confirm, window, cx| {
1285                                let new_ix = this.create_host_from_ssh_config(&host, cx);
1286                                this.create_remote_project(
1287                                    new_ix.into(),
1288                                    connection.clone().into(),
1289                                    window,
1290                                    cx,
1291                                );
1292                            }
1293                        }))
1294                        .child(
1295                            ListItem::new(("new-remote-project", ix))
1296                                .toggle_state(open_folder.focus_handle.contains_focused(window, cx))
1297                                .inset(true)
1298                                .spacing(ui::ListItemSpacing::Sparse)
1299                                .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
1300                                .child(Label::new("Open Folder"))
1301                                .on_click(cx.listener({
1302                                    let host = host.clone();
1303                                    move |this, _, window, cx| {
1304                                        let new_ix = this.create_host_from_ssh_config(&host, cx);
1305                                        this.create_remote_project(
1306                                            new_ix.into(),
1307                                            connection.clone().into(),
1308                                            window,
1309                                            cx,
1310                                        );
1311                                    }
1312                                })),
1313                        ),
1314                ),
1315            })
1316    }
1317
1318    fn render_remote_project(
1319        &mut self,
1320        server_ix: ServerIndex,
1321        server: RemoteEntry,
1322        ix: usize,
1323        (navigation, project): &(NavigableEntry, RemoteProject),
1324        window: &mut Window,
1325        cx: &mut Context<Self>,
1326    ) -> impl IntoElement {
1327        let create_new_window = self.create_new_window;
1328        let is_from_zed = server.is_from_zed();
1329        let element_id_base = SharedString::from(format!(
1330            "remote-project-{}",
1331            match server_ix {
1332                ServerIndex::Ssh(index) => format!("ssh-{index}"),
1333                ServerIndex::Wsl(index) => format!("wsl-{index}"),
1334            }
1335        ));
1336        let container_element_id_base =
1337            SharedString::from(format!("remote-project-container-{element_id_base}"));
1338
1339        let callback = Rc::new({
1340            let project = project.clone();
1341            move |remote_server_projects: &mut Self,
1342                  secondary_confirm: bool,
1343                  window: &mut Window,
1344                  cx: &mut Context<Self>| {
1345                let Some(app_state) = remote_server_projects
1346                    .workspace
1347                    .read_with(cx, |workspace, _| workspace.app_state().clone())
1348                    .log_err()
1349                else {
1350                    return;
1351                };
1352                let project = project.clone();
1353                let server = server.connection().into_owned();
1354                cx.emit(DismissEvent);
1355
1356                let replace_window = match (create_new_window, secondary_confirm) {
1357                    (true, false) | (false, true) => None,
1358                    (true, true) | (false, false) => window.window_handle().downcast::<Workspace>(),
1359                };
1360
1361                cx.spawn_in(window, async move |_, cx| {
1362                    let result = open_remote_project(
1363                        server.into(),
1364                        project.paths.into_iter().map(PathBuf::from).collect(),
1365                        app_state,
1366                        OpenOptions {
1367                            replace_window,
1368                            ..OpenOptions::default()
1369                        },
1370                        cx,
1371                    )
1372                    .await;
1373                    if let Err(e) = result {
1374                        log::error!("Failed to connect: {e:#}");
1375                        cx.prompt(
1376                            gpui::PromptLevel::Critical,
1377                            "Failed to connect",
1378                            Some(&e.to_string()),
1379                            &["Ok"],
1380                        )
1381                        .await
1382                        .ok();
1383                    }
1384                })
1385                .detach();
1386            }
1387        });
1388
1389        div()
1390            .id((container_element_id_base, ix))
1391            .track_focus(&navigation.focus_handle)
1392            .anchor_scroll(navigation.scroll_anchor.clone())
1393            .on_action(cx.listener({
1394                let callback = callback.clone();
1395                move |this, _: &menu::Confirm, window, cx| {
1396                    callback(this, false, window, cx);
1397                }
1398            }))
1399            .on_action(cx.listener({
1400                let callback = callback.clone();
1401                move |this, _: &menu::SecondaryConfirm, window, cx| {
1402                    callback(this, true, window, cx);
1403                }
1404            }))
1405            .child(
1406                ListItem::new((element_id_base, ix))
1407                    .toggle_state(navigation.focus_handle.contains_focused(window, cx))
1408                    .inset(true)
1409                    .spacing(ui::ListItemSpacing::Sparse)
1410                    .start_slot(
1411                        Icon::new(IconName::Folder)
1412                            .color(Color::Muted)
1413                            .size(IconSize::Small),
1414                    )
1415                    .child(Label::new(project.paths.join(", ")))
1416                    .on_click(cx.listener(move |this, e: &ClickEvent, window, cx| {
1417                        let secondary_confirm = e.modifiers().platform;
1418                        callback(this, secondary_confirm, window, cx)
1419                    }))
1420                    .when(is_from_zed, |server_list_item| {
1421                        server_list_item.end_hover_slot::<AnyElement>(Some(
1422                            div()
1423                                .mr_2()
1424                                .child({
1425                                    let project = project.clone();
1426                                    // Right-margin to offset it from the Scrollbar
1427                                    IconButton::new("remove-remote-project", IconName::Trash)
1428                                        .icon_size(IconSize::Small)
1429                                        .shape(IconButtonShape::Square)
1430                                        .size(ButtonSize::Large)
1431                                        .tooltip(Tooltip::text("Delete Remote Project"))
1432                                        .on_click(cx.listener(move |this, _, _, cx| {
1433                                            this.delete_remote_project(server_ix, &project, cx)
1434                                        }))
1435                                })
1436                                .into_any_element(),
1437                        ))
1438                    }),
1439            )
1440    }
1441
1442    fn update_settings_file(
1443        &mut self,
1444        cx: &mut Context<Self>,
1445        f: impl FnOnce(&mut RemoteSettingsContent, &App) + Send + Sync + 'static,
1446    ) {
1447        let Some(fs) = self
1448            .workspace
1449            .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
1450            .log_err()
1451        else {
1452            return;
1453        };
1454        update_settings_file(fs, cx, move |setting, cx| f(&mut setting.remote, cx));
1455    }
1456
1457    fn delete_ssh_server(&mut self, server: SshServerIndex, cx: &mut Context<Self>) {
1458        self.update_settings_file(cx, move |setting, _| {
1459            if let Some(connections) = setting.ssh_connections.as_mut() {
1460                connections.remove(server.0);
1461            }
1462        });
1463    }
1464
1465    fn delete_remote_project(
1466        &mut self,
1467        server: ServerIndex,
1468        project: &RemoteProject,
1469        cx: &mut Context<Self>,
1470    ) {
1471        match server {
1472            ServerIndex::Ssh(server) => {
1473                self.delete_ssh_project(server, project, cx);
1474            }
1475            ServerIndex::Wsl(server) => {
1476                self.delete_wsl_project(server, project, cx);
1477            }
1478        }
1479    }
1480
1481    fn delete_ssh_project(
1482        &mut self,
1483        server: SshServerIndex,
1484        project: &RemoteProject,
1485        cx: &mut Context<Self>,
1486    ) {
1487        let project = project.clone();
1488        self.update_settings_file(cx, move |setting, _| {
1489            if let Some(server) = setting
1490                .ssh_connections
1491                .as_mut()
1492                .and_then(|connections| connections.get_mut(server.0))
1493            {
1494                server.projects.remove(&project);
1495            }
1496        });
1497    }
1498
1499    fn delete_wsl_project(
1500        &mut self,
1501        server: WslServerIndex,
1502        project: &RemoteProject,
1503        cx: &mut Context<Self>,
1504    ) {
1505        let project = project.clone();
1506        self.update_settings_file(cx, move |setting, _| {
1507            if let Some(server) = setting
1508                .wsl_connections
1509                .as_mut()
1510                .and_then(|connections| connections.get_mut(server.0))
1511            {
1512                server.projects.remove(&project);
1513            }
1514        });
1515    }
1516
1517    fn delete_wsl_distro(&mut self, server: WslServerIndex, cx: &mut Context<Self>) {
1518        self.update_settings_file(cx, move |setting, _| {
1519            if let Some(connections) = setting.wsl_connections.as_mut() {
1520                connections.remove(server.0);
1521            }
1522        });
1523    }
1524
1525    fn add_ssh_server(
1526        &mut self,
1527        connection_options: remote::SshConnectionOptions,
1528        cx: &mut Context<Self>,
1529    ) {
1530        self.update_settings_file(cx, move |setting, _| {
1531            setting
1532                .ssh_connections
1533                .get_or_insert(Default::default())
1534                .push(SshConnection {
1535                    host: SharedString::from(connection_options.host.to_string()),
1536                    username: connection_options.username,
1537                    port: connection_options.port,
1538                    projects: BTreeSet::new(),
1539                    nickname: None,
1540                    args: connection_options.args.unwrap_or_default(),
1541                    upload_binary_over_ssh: None,
1542                    port_forwards: connection_options.port_forwards,
1543                    connection_timeout: connection_options.connection_timeout,
1544                })
1545        });
1546    }
1547
1548    fn edit_in_dev_container_json(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1549        let Some(workspace) = self.workspace.upgrade() else {
1550            cx.emit(DismissEvent);
1551            cx.notify();
1552            return;
1553        };
1554
1555        workspace.update(cx, |workspace, cx| {
1556            let project = workspace.project().clone();
1557
1558            let worktree = project
1559                .read(cx)
1560                .visible_worktrees(cx)
1561                .find_map(|tree| tree.read(cx).root_entry()?.is_dir().then_some(tree));
1562
1563            if let Some(worktree) = worktree {
1564                let tree_id = worktree.read(cx).id();
1565                let devcontainer_path = RelPath::unix(".devcontainer/devcontainer.json").unwrap();
1566                cx.spawn_in(window, async move |workspace, cx| {
1567                    workspace
1568                        .update_in(cx, |workspace, window, cx| {
1569                            workspace.open_path(
1570                                (tree_id, devcontainer_path),
1571                                None,
1572                                true,
1573                                window,
1574                                cx,
1575                            )
1576                        })?
1577                        .await
1578                })
1579                .detach();
1580            } else {
1581                return;
1582            }
1583        });
1584        cx.emit(DismissEvent);
1585        cx.notify();
1586    }
1587
1588    fn open_dev_container(&self, window: &mut Window, cx: &mut Context<Self>) {
1589        let Some(app_state) = self
1590            .workspace
1591            .read_with(cx, |workspace, _| workspace.app_state().clone())
1592            .log_err()
1593        else {
1594            return;
1595        };
1596
1597        let replace_window = window.window_handle().downcast::<Workspace>();
1598
1599        cx.spawn_in(window, async move |entity, cx| {
1600            let (connection, starting_dir) =
1601                match start_dev_container(cx, app_state.node_runtime.clone()).await {
1602                    Ok((c, s)) => (c, s),
1603                    Err(e) => {
1604                        log::error!("Failed to start dev container: {:?}", e);
1605                        entity
1606                            .update_in(cx, |remote_server_projects, window, cx| {
1607                                remote_server_projects.mode = Mode::CreateRemoteDevContainer(
1608                                    CreateRemoteDevContainer::new(window, cx).progress(
1609                                        DevContainerCreationProgress::Error(format!("{:?}", e)),
1610                                    ),
1611                                );
1612                            })
1613                            .log_err();
1614                        return;
1615                    }
1616                };
1617            entity
1618                .update(cx, |_, cx| {
1619                    cx.emit(DismissEvent);
1620                })
1621                .log_err();
1622
1623            let result = open_remote_project(
1624                connection.into(),
1625                vec![starting_dir].into_iter().map(PathBuf::from).collect(),
1626                app_state,
1627                OpenOptions {
1628                    replace_window,
1629                    ..OpenOptions::default()
1630                },
1631                cx,
1632            )
1633            .await;
1634            if let Err(e) = result {
1635                log::error!("Failed to connect: {e:#}");
1636                cx.prompt(
1637                    gpui::PromptLevel::Critical,
1638                    "Failed to connect",
1639                    Some(&e.to_string()),
1640                    &["Ok"],
1641                )
1642                .await
1643                .ok();
1644            }
1645        })
1646        .detach();
1647    }
1648
1649    fn render_create_dev_container(
1650        &self,
1651        state: &CreateRemoteDevContainer,
1652        window: &mut Window,
1653        cx: &mut Context<Self>,
1654    ) -> impl IntoElement {
1655        match &state.progress {
1656            DevContainerCreationProgress::Error(message) => {
1657                self.focus_handle(cx).focus(window, cx);
1658                return div()
1659                    .track_focus(&self.focus_handle(cx))
1660                    .size_full()
1661                    .child(
1662                        v_flex()
1663                            .py_1()
1664                            .child(
1665                                ListItem::new("Error")
1666                                    .inset(true)
1667                                    .selectable(false)
1668                                    .spacing(ui::ListItemSpacing::Sparse)
1669                                    .start_slot(Icon::new(IconName::XCircle).color(Color::Error))
1670                                    .child(Label::new("Error Creating Dev Container:"))
1671                                    .child(Label::new(message).buffer_font(cx)),
1672                            )
1673                            .child(ListSeparator)
1674                            .child(
1675                                div()
1676                                    .id("devcontainer-go-back")
1677                                    .track_focus(&state.entries[0].focus_handle)
1678                                    .on_action(cx.listener(
1679                                        |this, _: &menu::Confirm, window, cx| {
1680                                            this.mode =
1681                                                Mode::default_mode(&this.ssh_config_servers, cx);
1682                                            cx.focus_self(window);
1683                                            cx.notify();
1684                                        },
1685                                    ))
1686                                    .child(
1687                                        ListItem::new("li-devcontainer-go-back")
1688                                            .toggle_state(
1689                                                state.entries[0]
1690                                                    .focus_handle
1691                                                    .contains_focused(window, cx),
1692                                            )
1693                                            .inset(true)
1694                                            .spacing(ui::ListItemSpacing::Sparse)
1695                                            .start_slot(
1696                                                Icon::new(IconName::ArrowLeft).color(Color::Muted),
1697                                            )
1698                                            .child(Label::new("Go Back"))
1699                                            .end_slot(
1700                                                KeyBinding::for_action_in(
1701                                                    &menu::Cancel,
1702                                                    &self.focus_handle,
1703                                                    cx,
1704                                                )
1705                                                .size(rems_from_px(12.)),
1706                                            )
1707                                            .on_click(cx.listener(|this, _, window, cx| {
1708                                                let state =
1709                                                    CreateRemoteDevContainer::new(window, cx);
1710                                                this.mode = Mode::CreateRemoteDevContainer(state);
1711
1712                                                cx.notify();
1713                                            })),
1714                                    ),
1715                            ),
1716                    )
1717                    .into_any_element();
1718            }
1719            _ => {}
1720        };
1721
1722        let mut view = Navigable::new(
1723            div()
1724                .track_focus(&self.focus_handle(cx))
1725                .size_full()
1726                .child(
1727                    v_flex()
1728                        .pb_1()
1729                        .child(
1730                            ModalHeader::new()
1731                                .child(Headline::new("Dev Containers").size(HeadlineSize::XSmall)),
1732                        )
1733                        .child(ListSeparator)
1734                        .child(
1735                            div()
1736                                .id("confirm-create-from-devcontainer-json")
1737                                .track_focus(&state.entries[0].focus_handle)
1738                                .on_action(cx.listener({
1739                                    move |this, _: &menu::Confirm, window, cx| {
1740                                        this.open_dev_container(window, cx);
1741                                        this.view_in_progress_dev_container(window, cx);
1742                                    }
1743                                }))
1744                                .map(|this| {
1745                                    if state.progress == DevContainerCreationProgress::Creating {
1746                                        this.child(
1747                                            ListItem::new("creating")
1748                                                .inset(true)
1749                                                .spacing(ui::ListItemSpacing::Sparse)
1750                                                .disabled(true)
1751                                                .start_slot(
1752                                                    Icon::new(IconName::ArrowCircle)
1753                                                        .color(Color::Muted)
1754                                                        .with_rotate_animation(2),
1755                                                )
1756                                                .child(
1757                                                    h_flex()
1758                                                        .opacity(0.6)
1759                                                        .gap_1()
1760                                                        .child(Label::new("Creating From"))
1761                                                        .child(
1762                                                            Label::new("devcontainer.json")
1763                                                                .buffer_font(cx),
1764                                                        )
1765                                                        .child(LoadingLabel::new("")),
1766                                                ),
1767                                        )
1768                                    } else {
1769                                        this.child(
1770                                            ListItem::new(
1771                                                "li-confirm-create-from-devcontainer-json",
1772                                            )
1773                                            .toggle_state(
1774                                                state.entries[0]
1775                                                    .focus_handle
1776                                                    .contains_focused(window, cx),
1777                                            )
1778                                            .inset(true)
1779                                            .spacing(ui::ListItemSpacing::Sparse)
1780                                            .start_slot(
1781                                                Icon::new(IconName::Plus).color(Color::Muted),
1782                                            )
1783                                            .child(
1784                                                h_flex()
1785                                                    .gap_1()
1786                                                    .child(Label::new("Open or Create New From"))
1787                                                    .child(
1788                                                        Label::new("devcontainer.json")
1789                                                            .buffer_font(cx),
1790                                                    ),
1791                                            )
1792                                            .on_click(
1793                                                cx.listener({
1794                                                    move |this, _, window, cx| {
1795                                                        this.open_dev_container(window, cx);
1796                                                        this.view_in_progress_dev_container(
1797                                                            window, cx,
1798                                                        );
1799                                                        cx.notify();
1800                                                    }
1801                                                }),
1802                                            ),
1803                                        )
1804                                    }
1805                                }),
1806                        )
1807                        .child(
1808                            div()
1809                                .id("edit-devcontainer-json")
1810                                .track_focus(&state.entries[1].focus_handle)
1811                                .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
1812                                    this.edit_in_dev_container_json(window, cx);
1813                                }))
1814                                .child(
1815                                    ListItem::new("li-edit-devcontainer-json")
1816                                        .toggle_state(
1817                                            state.entries[1]
1818                                                .focus_handle
1819                                                .contains_focused(window, cx),
1820                                        )
1821                                        .inset(true)
1822                                        .spacing(ui::ListItemSpacing::Sparse)
1823                                        .start_slot(Icon::new(IconName::Pencil).color(Color::Muted))
1824                                        .child(
1825                                            h_flex().gap_1().child(Label::new("Edit")).child(
1826                                                Label::new("devcontainer.json").buffer_font(cx),
1827                                            ),
1828                                        )
1829                                        .on_click(cx.listener(move |this, _, window, cx| {
1830                                            this.edit_in_dev_container_json(window, cx);
1831                                        })),
1832                                ),
1833                        )
1834                        .child(ListSeparator)
1835                        .child(
1836                            div()
1837                                .id("devcontainer-go-back")
1838                                .track_focus(&state.entries[2].focus_handle)
1839                                .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
1840                                    this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
1841                                    cx.focus_self(window);
1842                                    cx.notify();
1843                                }))
1844                                .child(
1845                                    ListItem::new("li-devcontainer-go-back")
1846                                        .toggle_state(
1847                                            state.entries[2]
1848                                                .focus_handle
1849                                                .contains_focused(window, cx),
1850                                        )
1851                                        .inset(true)
1852                                        .spacing(ui::ListItemSpacing::Sparse)
1853                                        .start_slot(
1854                                            Icon::new(IconName::ArrowLeft).color(Color::Muted),
1855                                        )
1856                                        .child(Label::new("Go Back"))
1857                                        .end_slot(
1858                                            KeyBinding::for_action_in(
1859                                                &menu::Cancel,
1860                                                &self.focus_handle,
1861                                                cx,
1862                                            )
1863                                            .size(rems_from_px(12.)),
1864                                        )
1865                                        .on_click(cx.listener(|this, _, window, cx| {
1866                                            this.mode =
1867                                                Mode::default_mode(&this.ssh_config_servers, cx);
1868                                            cx.focus_self(window);
1869                                            cx.notify()
1870                                        })),
1871                                ),
1872                        ),
1873                )
1874                .into_any_element(),
1875        );
1876
1877        view = view.entry(state.entries[0].clone());
1878        view = view.entry(state.entries[1].clone());
1879        view = view.entry(state.entries[2].clone());
1880
1881        view.render(window, cx).into_any_element()
1882    }
1883
1884    fn render_create_remote_server(
1885        &self,
1886        state: &CreateRemoteServer,
1887        window: &mut Window,
1888        cx: &mut Context<Self>,
1889    ) -> impl IntoElement {
1890        let ssh_prompt = state.ssh_prompt.clone();
1891
1892        state.address_editor.update(cx, |editor, cx| {
1893            if editor.text(cx).is_empty() {
1894                editor.set_placeholder_text("ssh user@example -p 2222", window, cx);
1895            }
1896        });
1897
1898        let theme = cx.theme();
1899
1900        v_flex()
1901            .track_focus(&self.focus_handle(cx))
1902            .id("create-remote-server")
1903            .overflow_hidden()
1904            .size_full()
1905            .flex_1()
1906            .child(
1907                div()
1908                    .p_2()
1909                    .border_b_1()
1910                    .border_color(theme.colors().border_variant)
1911                    .child(state.address_editor.clone()),
1912            )
1913            .child(
1914                h_flex()
1915                    .bg(theme.colors().editor_background)
1916                    .rounded_b_sm()
1917                    .w_full()
1918                    .map(|this| {
1919                        if let Some(ssh_prompt) = ssh_prompt {
1920                            this.child(h_flex().w_full().child(ssh_prompt))
1921                        } else if let Some(address_error) = &state.address_error {
1922                            this.child(
1923                                h_flex().p_2().w_full().gap_2().child(
1924                                    Label::new(address_error.clone())
1925                                        .size(LabelSize::Small)
1926                                        .color(Color::Error),
1927                                ),
1928                            )
1929                        } else {
1930                            this.child(
1931                                h_flex()
1932                                    .p_2()
1933                                    .w_full()
1934                                    .gap_1()
1935                                    .child(
1936                                        Label::new(
1937                                            "Enter the command you use to SSH into this server.",
1938                                        )
1939                                        .color(Color::Muted)
1940                                        .size(LabelSize::Small),
1941                                    )
1942                                    .child(
1943                                        Button::new("learn-more", "Learn More")
1944                                            .label_size(LabelSize::Small)
1945                                            .icon(IconName::ArrowUpRight)
1946                                            .icon_size(IconSize::XSmall)
1947                                            .on_click(|_, _, cx| {
1948                                                cx.open_url(
1949                                                    "https://zed.dev/docs/remote-development",
1950                                                );
1951                                            }),
1952                                    ),
1953                            )
1954                        }
1955                    }),
1956            )
1957    }
1958
1959    #[cfg(target_os = "windows")]
1960    fn render_add_wsl_distro(
1961        &self,
1962        state: &AddWslDistro,
1963        window: &mut Window,
1964        cx: &mut Context<Self>,
1965    ) -> impl IntoElement {
1966        let connection_prompt = state.connection_prompt.clone();
1967
1968        state.picker.update(cx, |picker, cx| {
1969            picker.focus_handle(cx).focus(window, cx);
1970        });
1971
1972        v_flex()
1973            .id("add-wsl-distro")
1974            .overflow_hidden()
1975            .size_full()
1976            .flex_1()
1977            .map(|this| {
1978                if let Some(connection_prompt) = connection_prompt {
1979                    this.child(connection_prompt)
1980                } else {
1981                    this.child(state.picker.clone())
1982                }
1983            })
1984    }
1985
1986    fn render_view_options(
1987        &mut self,
1988        options: ViewServerOptionsState,
1989        window: &mut Window,
1990        cx: &mut Context<Self>,
1991    ) -> impl IntoElement {
1992        let last_entry = options.entries().last().unwrap();
1993
1994        let mut view = Navigable::new(
1995            div()
1996                .track_focus(&self.focus_handle(cx))
1997                .size_full()
1998                .child(match &options {
1999                    ViewServerOptionsState::Ssh { connection, .. } => SshConnectionHeader {
2000                        connection_string: connection.host.to_string().into(),
2001                        paths: Default::default(),
2002                        nickname: connection.nickname.clone().map(|s| s.into()),
2003                        is_wsl: false,
2004                        is_devcontainer: false,
2005                    }
2006                    .render(window, cx)
2007                    .into_any_element(),
2008                    ViewServerOptionsState::Wsl { connection, .. } => SshConnectionHeader {
2009                        connection_string: connection.distro_name.clone().into(),
2010                        paths: Default::default(),
2011                        nickname: None,
2012                        is_wsl: true,
2013                        is_devcontainer: false,
2014                    }
2015                    .render(window, cx)
2016                    .into_any_element(),
2017                })
2018                .child(
2019                    v_flex()
2020                        .pb_1()
2021                        .child(ListSeparator)
2022                        .map(|this| match &options {
2023                            ViewServerOptionsState::Ssh {
2024                                connection,
2025                                entries,
2026                                server_index,
2027                            } => this.child(self.render_edit_ssh(
2028                                connection,
2029                                *server_index,
2030                                entries,
2031                                window,
2032                                cx,
2033                            )),
2034                            ViewServerOptionsState::Wsl {
2035                                connection,
2036                                entries,
2037                                server_index,
2038                            } => this.child(self.render_edit_wsl(
2039                                connection,
2040                                *server_index,
2041                                entries,
2042                                window,
2043                                cx,
2044                            )),
2045                        })
2046                        .child(ListSeparator)
2047                        .child({
2048                            div()
2049                                .id("ssh-options-copy-server-address")
2050                                .track_focus(&last_entry.focus_handle)
2051                                .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
2052                                    this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
2053                                    cx.focus_self(window);
2054                                    cx.notify();
2055                                }))
2056                                .child(
2057                                    ListItem::new("go-back")
2058                                        .toggle_state(
2059                                            last_entry.focus_handle.contains_focused(window, cx),
2060                                        )
2061                                        .inset(true)
2062                                        .spacing(ui::ListItemSpacing::Sparse)
2063                                        .start_slot(
2064                                            Icon::new(IconName::ArrowLeft).color(Color::Muted),
2065                                        )
2066                                        .child(Label::new("Go Back"))
2067                                        .on_click(cx.listener(|this, _, window, cx| {
2068                                            this.mode =
2069                                                Mode::default_mode(&this.ssh_config_servers, cx);
2070                                            cx.focus_self(window);
2071                                            cx.notify()
2072                                        })),
2073                                )
2074                        }),
2075                )
2076                .into_any_element(),
2077        );
2078
2079        for entry in options.entries() {
2080            view = view.entry(entry.clone());
2081        }
2082
2083        view.render(window, cx).into_any_element()
2084    }
2085
2086    fn render_edit_wsl(
2087        &self,
2088        connection: &WslConnectionOptions,
2089        index: WslServerIndex,
2090        entries: &[NavigableEntry],
2091        window: &mut Window,
2092        cx: &mut Context<Self>,
2093    ) -> impl IntoElement {
2094        let distro_name = SharedString::new(connection.distro_name.clone());
2095
2096        v_flex().child({
2097            fn remove_wsl_distro(
2098                remote_servers: Entity<RemoteServerProjects>,
2099                index: WslServerIndex,
2100                distro_name: SharedString,
2101                window: &mut Window,
2102                cx: &mut App,
2103            ) {
2104                let prompt_message = format!("Remove WSL distro `{}`?", distro_name);
2105
2106                let confirmation = window.prompt(
2107                    PromptLevel::Warning,
2108                    &prompt_message,
2109                    None,
2110                    &["Yes, remove it", "No, keep it"],
2111                    cx,
2112                );
2113
2114                cx.spawn(async move |cx| {
2115                    if confirmation.await.ok() == Some(0) {
2116                        remote_servers
2117                            .update(cx, |this, cx| {
2118                                this.delete_wsl_distro(index, cx);
2119                            })
2120                            .ok();
2121                        remote_servers
2122                            .update(cx, |this, cx| {
2123                                this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
2124                                cx.notify();
2125                            })
2126                            .ok();
2127                    }
2128                    anyhow::Ok(())
2129                })
2130                .detach_and_log_err(cx);
2131            }
2132            div()
2133                .id("wsl-options-remove-distro")
2134                .track_focus(&entries[0].focus_handle)
2135                .on_action(cx.listener({
2136                    let distro_name = distro_name.clone();
2137                    move |_, _: &menu::Confirm, window, cx| {
2138                        remove_wsl_distro(cx.entity(), index, distro_name.clone(), window, cx);
2139                        cx.focus_self(window);
2140                    }
2141                }))
2142                .child(
2143                    ListItem::new("remove-distro")
2144                        .toggle_state(entries[0].focus_handle.contains_focused(window, cx))
2145                        .inset(true)
2146                        .spacing(ui::ListItemSpacing::Sparse)
2147                        .start_slot(Icon::new(IconName::Trash).color(Color::Error))
2148                        .child(Label::new("Remove Distro").color(Color::Error))
2149                        .on_click(cx.listener(move |_, _, window, cx| {
2150                            remove_wsl_distro(cx.entity(), index, distro_name.clone(), window, cx);
2151                            cx.focus_self(window);
2152                        })),
2153                )
2154        })
2155    }
2156
2157    fn render_edit_ssh(
2158        &self,
2159        connection: &SshConnectionOptions,
2160        index: SshServerIndex,
2161        entries: &[NavigableEntry],
2162        window: &mut Window,
2163        cx: &mut Context<Self>,
2164    ) -> impl IntoElement {
2165        let connection_string = SharedString::new(connection.host.to_string());
2166
2167        v_flex()
2168            .child({
2169                let label = if connection.nickname.is_some() {
2170                    "Edit Nickname"
2171                } else {
2172                    "Add Nickname to Server"
2173                };
2174                div()
2175                    .id("ssh-options-add-nickname")
2176                    .track_focus(&entries[0].focus_handle)
2177                    .on_action(cx.listener(move |this, _: &menu::Confirm, window, cx| {
2178                        this.mode = Mode::EditNickname(EditNicknameState::new(index, window, cx));
2179                        cx.notify();
2180                    }))
2181                    .child(
2182                        ListItem::new("add-nickname")
2183                            .toggle_state(entries[0].focus_handle.contains_focused(window, cx))
2184                            .inset(true)
2185                            .spacing(ui::ListItemSpacing::Sparse)
2186                            .start_slot(Icon::new(IconName::Pencil).color(Color::Muted))
2187                            .child(Label::new(label))
2188                            .on_click(cx.listener(move |this, _, window, cx| {
2189                                this.mode =
2190                                    Mode::EditNickname(EditNicknameState::new(index, window, cx));
2191                                cx.notify();
2192                            })),
2193                    )
2194            })
2195            .child({
2196                let workspace = self.workspace.clone();
2197                fn callback(
2198                    workspace: WeakEntity<Workspace>,
2199                    connection_string: SharedString,
2200                    cx: &mut App,
2201                ) {
2202                    cx.write_to_clipboard(ClipboardItem::new_string(connection_string.to_string()));
2203                    workspace
2204                        .update(cx, |this, cx| {
2205                            struct SshServerAddressCopiedToClipboard;
2206                            let notification = format!(
2207                                "Copied server address ({}) to clipboard",
2208                                connection_string
2209                            );
2210
2211                            this.show_toast(
2212                                Toast::new(
2213                                    NotificationId::composite::<SshServerAddressCopiedToClipboard>(
2214                                        connection_string.clone(),
2215                                    ),
2216                                    notification,
2217                                )
2218                                .autohide(),
2219                                cx,
2220                            );
2221                        })
2222                        .ok();
2223                }
2224                div()
2225                    .id("ssh-options-copy-server-address")
2226                    .track_focus(&entries[1].focus_handle)
2227                    .on_action({
2228                        let connection_string = connection_string.clone();
2229                        let workspace = self.workspace.clone();
2230                        move |_: &menu::Confirm, _, cx| {
2231                            callback(workspace.clone(), connection_string.clone(), cx);
2232                        }
2233                    })
2234                    .child(
2235                        ListItem::new("copy-server-address")
2236                            .toggle_state(entries[1].focus_handle.contains_focused(window, cx))
2237                            .inset(true)
2238                            .spacing(ui::ListItemSpacing::Sparse)
2239                            .start_slot(Icon::new(IconName::Copy).color(Color::Muted))
2240                            .child(Label::new("Copy Server Address"))
2241                            .end_hover_slot(
2242                                Label::new(connection_string.clone()).color(Color::Muted),
2243                            )
2244                            .on_click({
2245                                let connection_string = connection_string.clone();
2246                                move |_, _, cx| {
2247                                    callback(workspace.clone(), connection_string.clone(), cx);
2248                                }
2249                            }),
2250                    )
2251            })
2252            .child({
2253                fn remove_ssh_server(
2254                    remote_servers: Entity<RemoteServerProjects>,
2255                    index: SshServerIndex,
2256                    connection_string: SharedString,
2257                    window: &mut Window,
2258                    cx: &mut App,
2259                ) {
2260                    let prompt_message = format!("Remove server `{}`?", connection_string);
2261
2262                    let confirmation = window.prompt(
2263                        PromptLevel::Warning,
2264                        &prompt_message,
2265                        None,
2266                        &["Yes, remove it", "No, keep it"],
2267                        cx,
2268                    );
2269
2270                    cx.spawn(async move |cx| {
2271                        if confirmation.await.ok() == Some(0) {
2272                            remote_servers
2273                                .update(cx, |this, cx| {
2274                                    this.delete_ssh_server(index, cx);
2275                                })
2276                                .ok();
2277                            remote_servers
2278                                .update(cx, |this, cx| {
2279                                    this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
2280                                    cx.notify();
2281                                })
2282                                .ok();
2283                        }
2284                        anyhow::Ok(())
2285                    })
2286                    .detach_and_log_err(cx);
2287                }
2288                div()
2289                    .id("ssh-options-copy-server-address")
2290                    .track_focus(&entries[2].focus_handle)
2291                    .on_action(cx.listener({
2292                        let connection_string = connection_string.clone();
2293                        move |_, _: &menu::Confirm, window, cx| {
2294                            remove_ssh_server(
2295                                cx.entity(),
2296                                index,
2297                                connection_string.clone(),
2298                                window,
2299                                cx,
2300                            );
2301                            cx.focus_self(window);
2302                        }
2303                    }))
2304                    .child(
2305                        ListItem::new("remove-server")
2306                            .toggle_state(entries[2].focus_handle.contains_focused(window, cx))
2307                            .inset(true)
2308                            .spacing(ui::ListItemSpacing::Sparse)
2309                            .start_slot(Icon::new(IconName::Trash).color(Color::Error))
2310                            .child(Label::new("Remove Server").color(Color::Error))
2311                            .on_click(cx.listener(move |_, _, window, cx| {
2312                                remove_ssh_server(
2313                                    cx.entity(),
2314                                    index,
2315                                    connection_string.clone(),
2316                                    window,
2317                                    cx,
2318                                );
2319                                cx.focus_self(window);
2320                            })),
2321                    )
2322            })
2323    }
2324
2325    fn render_edit_nickname(
2326        &self,
2327        state: &EditNicknameState,
2328        window: &mut Window,
2329        cx: &mut Context<Self>,
2330    ) -> impl IntoElement {
2331        let Some(connection) = SshSettings::get_global(cx)
2332            .ssh_connections()
2333            .nth(state.index.0)
2334        else {
2335            return v_flex()
2336                .id("ssh-edit-nickname")
2337                .track_focus(&self.focus_handle(cx));
2338        };
2339
2340        let connection_string = connection.host.clone();
2341        let nickname = connection.nickname.map(|s| s.into());
2342
2343        v_flex()
2344            .id("ssh-edit-nickname")
2345            .track_focus(&self.focus_handle(cx))
2346            .child(
2347                SshConnectionHeader {
2348                    connection_string,
2349                    paths: Default::default(),
2350                    nickname,
2351                    is_wsl: false,
2352                    is_devcontainer: false,
2353                }
2354                .render(window, cx),
2355            )
2356            .child(
2357                h_flex()
2358                    .p_2()
2359                    .border_t_1()
2360                    .border_color(cx.theme().colors().border_variant)
2361                    .child(state.editor.clone()),
2362            )
2363    }
2364
2365    fn render_default(
2366        &mut self,
2367        mut state: DefaultState,
2368        window: &mut Window,
2369        cx: &mut Context<Self>,
2370    ) -> impl IntoElement {
2371        let ssh_settings = SshSettings::get_global(cx);
2372        let mut should_rebuild = false;
2373
2374        let ssh_connections_changed = ssh_settings.ssh_connections.0.iter().ne(state
2375            .servers
2376            .iter()
2377            .filter_map(|server| match server {
2378                RemoteEntry::Project {
2379                    connection: Connection::Ssh(connection),
2380                    ..
2381                } => Some(connection),
2382                _ => None,
2383            }));
2384
2385        let wsl_connections_changed = ssh_settings.wsl_connections.0.iter().ne(state
2386            .servers
2387            .iter()
2388            .filter_map(|server| match server {
2389                RemoteEntry::Project {
2390                    connection: Connection::Wsl(connection),
2391                    ..
2392                } => Some(connection),
2393                _ => None,
2394            }));
2395
2396        if ssh_connections_changed || wsl_connections_changed {
2397            should_rebuild = true;
2398        };
2399
2400        if !should_rebuild && ssh_settings.read_ssh_config {
2401            let current_ssh_hosts: BTreeSet<SharedString> = state
2402                .servers
2403                .iter()
2404                .filter_map(|server| match server {
2405                    RemoteEntry::SshConfig { host, .. } => Some(host.clone()),
2406                    _ => None,
2407                })
2408                .collect();
2409            let mut expected_ssh_hosts = self.ssh_config_servers.clone();
2410            for server in &state.servers {
2411                if let RemoteEntry::Project {
2412                    connection: Connection::Ssh(connection),
2413                    ..
2414                } = server
2415                {
2416                    expected_ssh_hosts.remove(&connection.host);
2417                }
2418            }
2419            should_rebuild = current_ssh_hosts != expected_ssh_hosts;
2420        }
2421
2422        if should_rebuild {
2423            self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
2424            if let Mode::Default(new_state) = &self.mode {
2425                state = new_state.clone();
2426            }
2427        }
2428
2429        let connect_button = div()
2430            .id("ssh-connect-new-server-container")
2431            .track_focus(&state.add_new_server.focus_handle)
2432            .anchor_scroll(state.add_new_server.scroll_anchor.clone())
2433            .child(
2434                ListItem::new("register-remote-server-button")
2435                    .toggle_state(
2436                        state
2437                            .add_new_server
2438                            .focus_handle
2439                            .contains_focused(window, cx),
2440                    )
2441                    .inset(true)
2442                    .spacing(ui::ListItemSpacing::Sparse)
2443                    .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
2444                    .child(Label::new("Connect SSH Server"))
2445                    .on_click(cx.listener(|this, _, window, cx| {
2446                        let state = CreateRemoteServer::new(window, cx);
2447                        this.mode = Mode::CreateRemoteServer(state);
2448
2449                        cx.notify();
2450                    })),
2451            )
2452            .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
2453                let state = CreateRemoteServer::new(window, cx);
2454                this.mode = Mode::CreateRemoteServer(state);
2455
2456                cx.notify();
2457            }));
2458
2459        let connect_dev_container_button = div()
2460            .id("connect-new-dev-container")
2461            .track_focus(&state.add_new_devcontainer.focus_handle)
2462            .anchor_scroll(state.add_new_devcontainer.scroll_anchor.clone())
2463            .child(
2464                ListItem::new("register-dev-container-button")
2465                    .toggle_state(
2466                        state
2467                            .add_new_devcontainer
2468                            .focus_handle
2469                            .contains_focused(window, cx),
2470                    )
2471                    .inset(true)
2472                    .spacing(ui::ListItemSpacing::Sparse)
2473                    .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
2474                    .child(Label::new("Connect Dev Container"))
2475                    .on_click(cx.listener(|this, _, window, cx| {
2476                        let state = CreateRemoteDevContainer::new(window, cx);
2477                        this.mode = Mode::CreateRemoteDevContainer(state);
2478
2479                        cx.notify();
2480                    })),
2481            )
2482            .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
2483                let state = CreateRemoteDevContainer::new(window, cx);
2484                this.mode = Mode::CreateRemoteDevContainer(state);
2485
2486                cx.notify();
2487            }));
2488
2489        #[cfg(target_os = "windows")]
2490        let wsl_connect_button = div()
2491            .id("wsl-connect-new-server")
2492            .track_focus(&state.add_new_wsl.focus_handle)
2493            .anchor_scroll(state.add_new_wsl.scroll_anchor.clone())
2494            .child(
2495                ListItem::new("wsl-add-new-server")
2496                    .toggle_state(state.add_new_wsl.focus_handle.contains_focused(window, cx))
2497                    .inset(true)
2498                    .spacing(ui::ListItemSpacing::Sparse)
2499                    .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
2500                    .child(Label::new("Add WSL Distro"))
2501                    .on_click(cx.listener(|this, _, window, cx| {
2502                        let state = AddWslDistro::new(window, cx);
2503                        this.mode = Mode::AddWslDistro(state);
2504
2505                        cx.notify();
2506                    })),
2507            )
2508            .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
2509                let state = AddWslDistro::new(window, cx);
2510                this.mode = Mode::AddWslDistro(state);
2511
2512                cx.notify();
2513            }));
2514
2515        let has_open_project = self
2516            .workspace
2517            .upgrade()
2518            .map(|workspace| {
2519                workspace
2520                    .read(cx)
2521                    .project()
2522                    .read(cx)
2523                    .visible_worktrees(cx)
2524                    .next()
2525                    .is_some()
2526            })
2527            .unwrap_or(false);
2528
2529        let modal_section = v_flex()
2530            .track_focus(&self.focus_handle(cx))
2531            .id("ssh-server-list")
2532            .overflow_y_scroll()
2533            .track_scroll(&state.scroll_handle)
2534            .size_full()
2535            .child(connect_button)
2536            .when(has_open_project, |this| {
2537                this.child(connect_dev_container_button)
2538            });
2539
2540        #[cfg(target_os = "windows")]
2541        let modal_section = modal_section.child(wsl_connect_button);
2542        #[cfg(not(target_os = "windows"))]
2543        let modal_section = modal_section;
2544
2545        let mut modal_section = Navigable::new(
2546            modal_section
2547                .child(
2548                    List::new()
2549                        .empty_message(
2550                            h_flex()
2551                                .size_full()
2552                                .p_2()
2553                                .justify_center()
2554                                .border_t_1()
2555                                .border_color(cx.theme().colors().border_variant)
2556                                .child(
2557                                    Label::new("No remote servers registered yet.")
2558                                        .color(Color::Muted),
2559                                )
2560                                .into_any_element(),
2561                        )
2562                        .children(state.servers.iter().enumerate().map(|(ix, connection)| {
2563                            self.render_remote_connection(ix, connection.clone(), window, cx)
2564                                .into_any_element()
2565                        })),
2566                )
2567                .into_any_element(),
2568        )
2569        .entry(state.add_new_server.clone());
2570
2571        if has_open_project {
2572            modal_section = modal_section.entry(state.add_new_devcontainer.clone());
2573        }
2574
2575        if cfg!(target_os = "windows") {
2576            modal_section = modal_section.entry(state.add_new_wsl.clone());
2577        }
2578
2579        for server in &state.servers {
2580            match server {
2581                RemoteEntry::Project {
2582                    open_folder,
2583                    projects,
2584                    configure,
2585                    ..
2586                } => {
2587                    for (navigation_state, _) in projects {
2588                        modal_section = modal_section.entry(navigation_state.clone());
2589                    }
2590                    modal_section = modal_section
2591                        .entry(open_folder.clone())
2592                        .entry(configure.clone());
2593                }
2594                RemoteEntry::SshConfig { open_folder, .. } => {
2595                    modal_section = modal_section.entry(open_folder.clone());
2596                }
2597            }
2598        }
2599        let mut modal_section = modal_section.render(window, cx).into_any_element();
2600
2601        let (create_window, reuse_window) = if self.create_new_window {
2602            (
2603                window.keystroke_text_for(&menu::Confirm),
2604                window.keystroke_text_for(&menu::SecondaryConfirm),
2605            )
2606        } else {
2607            (
2608                window.keystroke_text_for(&menu::SecondaryConfirm),
2609                window.keystroke_text_for(&menu::Confirm),
2610            )
2611        };
2612        let placeholder_text = Arc::from(format!(
2613            "{reuse_window} reuses this window, {create_window} opens a new one",
2614        ));
2615
2616        Modal::new("remote-projects", None)
2617            .header(
2618                ModalHeader::new()
2619                    .child(Headline::new("Remote Projects").size(HeadlineSize::XSmall))
2620                    .child(
2621                        Label::new(placeholder_text)
2622                            .color(Color::Muted)
2623                            .size(LabelSize::XSmall),
2624                    ),
2625            )
2626            .section(
2627                Section::new().padded(false).child(
2628                    v_flex()
2629                        .min_h(rems(20.))
2630                        .size_full()
2631                        .relative()
2632                        .child(ListSeparator)
2633                        .child(
2634                            canvas(
2635                                |bounds, window, cx| {
2636                                    modal_section.prepaint_as_root(
2637                                        bounds.origin,
2638                                        bounds.size.into(),
2639                                        window,
2640                                        cx,
2641                                    );
2642                                    modal_section
2643                                },
2644                                |_, mut modal_section, window, cx| {
2645                                    modal_section.paint(window, cx);
2646                                },
2647                            )
2648                            .size_full(),
2649                        )
2650                        .vertical_scrollbar_for(&state.scroll_handle, window, cx),
2651                ),
2652            )
2653            .into_any_element()
2654    }
2655
2656    fn create_host_from_ssh_config(
2657        &mut self,
2658        ssh_config_host: &SharedString,
2659        cx: &mut Context<'_, Self>,
2660    ) -> SshServerIndex {
2661        let new_ix = Arc::new(AtomicUsize::new(0));
2662
2663        let update_new_ix = new_ix.clone();
2664        self.update_settings_file(cx, move |settings, _| {
2665            update_new_ix.store(
2666                settings
2667                    .ssh_connections
2668                    .as_ref()
2669                    .map_or(0, |connections| connections.len()),
2670                atomic::Ordering::Release,
2671            );
2672        });
2673
2674        self.add_ssh_server(
2675            SshConnectionOptions {
2676                host: ssh_config_host.to_string().into(),
2677                ..SshConnectionOptions::default()
2678            },
2679            cx,
2680        );
2681        self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
2682        SshServerIndex(new_ix.load(atomic::Ordering::Acquire))
2683    }
2684}
2685
2686fn spawn_ssh_config_watch(fs: Arc<dyn Fs>, cx: &Context<RemoteServerProjects>) -> Task<()> {
2687    let mut user_ssh_config_watcher =
2688        watch_config_file(cx.background_executor(), fs.clone(), user_ssh_config_file());
2689    let mut global_ssh_config_watcher = global_ssh_config_file()
2690        .map(|it| watch_config_file(cx.background_executor(), fs, it.to_owned()))
2691        .unwrap_or_else(|| futures::channel::mpsc::unbounded().1);
2692
2693    cx.spawn(async move |remote_server_projects, cx| {
2694        let mut global_hosts = BTreeSet::default();
2695        let mut user_hosts = BTreeSet::default();
2696        let mut running_receivers = 2;
2697
2698        loop {
2699            select! {
2700                new_global_file_contents = global_ssh_config_watcher.next().fuse() => {
2701                    match new_global_file_contents {
2702                        Some(new_global_file_contents) => {
2703                            global_hosts = parse_ssh_config_hosts(&new_global_file_contents);
2704                            if remote_server_projects.update(cx, |remote_server_projects, cx| {
2705                                remote_server_projects.ssh_config_servers = global_hosts.iter().chain(user_hosts.iter()).map(SharedString::from).collect();
2706                                cx.notify();
2707                            }).is_err() {
2708                                return;
2709                            }
2710                        },
2711                        None => {
2712                            running_receivers -= 1;
2713                            if running_receivers == 0 {
2714                                return;
2715                            }
2716                        }
2717                    }
2718                },
2719                new_user_file_contents = user_ssh_config_watcher.next().fuse() => {
2720                    match new_user_file_contents {
2721                        Some(new_user_file_contents) => {
2722                            user_hosts = parse_ssh_config_hosts(&new_user_file_contents);
2723                            if remote_server_projects.update(cx, |remote_server_projects, cx| {
2724                                remote_server_projects.ssh_config_servers = global_hosts.iter().chain(user_hosts.iter()).map(SharedString::from).collect();
2725                                cx.notify();
2726                            }).is_err() {
2727                                return;
2728                            }
2729                        },
2730                        None => {
2731                            running_receivers -= 1;
2732                            if running_receivers == 0 {
2733                                return;
2734                            }
2735                        }
2736                    }
2737                },
2738            }
2739        }
2740    })
2741}
2742
2743fn get_text(element: &Entity<Editor>, cx: &mut App) -> String {
2744    element.read(cx).text(cx).trim().to_string()
2745}
2746
2747impl ModalView for RemoteServerProjects {}
2748
2749impl Focusable for RemoteServerProjects {
2750    fn focus_handle(&self, cx: &App) -> FocusHandle {
2751        match &self.mode {
2752            Mode::ProjectPicker(picker) => picker.focus_handle(cx),
2753            _ => self.focus_handle.clone(),
2754        }
2755    }
2756}
2757
2758impl EventEmitter<DismissEvent> for RemoteServerProjects {}
2759
2760impl Render for RemoteServerProjects {
2761    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2762        div()
2763            .elevation_3(cx)
2764            .w(rems(34.))
2765            .key_context("RemoteServerModal")
2766            .on_action(cx.listener(Self::cancel))
2767            .on_action(cx.listener(Self::confirm))
2768            .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
2769                this.focus_handle(cx).focus(window, cx);
2770            }))
2771            .on_mouse_down_out(cx.listener(|this, _, _, cx| {
2772                if matches!(this.mode, Mode::Default(_)) {
2773                    cx.emit(DismissEvent)
2774                }
2775            }))
2776            .child(match &self.mode {
2777                Mode::Default(state) => self
2778                    .render_default(state.clone(), window, cx)
2779                    .into_any_element(),
2780                Mode::ViewServerOptions(state) => self
2781                    .render_view_options(state.clone(), window, cx)
2782                    .into_any_element(),
2783                Mode::ProjectPicker(element) => element.clone().into_any_element(),
2784                Mode::CreateRemoteServer(state) => self
2785                    .render_create_remote_server(state, window, cx)
2786                    .into_any_element(),
2787                Mode::CreateRemoteDevContainer(state) => self
2788                    .render_create_dev_container(state, window, cx)
2789                    .into_any_element(),
2790                Mode::EditNickname(state) => self
2791                    .render_edit_nickname(state, window, cx)
2792                    .into_any_element(),
2793                #[cfg(target_os = "windows")]
2794                Mode::AddWslDistro(state) => self
2795                    .render_add_wsl_distro(state, window, cx)
2796                    .into_any_element(),
2797            })
2798    }
2799}