remote_servers.rs

   1use std::any::Any;
   2use std::borrow::Cow;
   3use std::collections::BTreeSet;
   4use std::path::PathBuf;
   5use std::rc::Rc;
   6use std::sync::Arc;
   7use std::sync::atomic;
   8use std::sync::atomic::AtomicUsize;
   9
  10use editor::Editor;
  11use file_finder::OpenPathDelegate;
  12use futures::FutureExt;
  13use futures::channel::oneshot;
  14use futures::future::Shared;
  15use futures::select;
  16use gpui::ClickEvent;
  17use gpui::ClipboardItem;
  18use gpui::Subscription;
  19use gpui::Task;
  20use gpui::WeakEntity;
  21use gpui::canvas;
  22use gpui::{
  23    AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  24    PromptLevel, ScrollHandle, Window,
  25};
  26use paths::global_ssh_config_file;
  27use paths::user_ssh_config_file;
  28use picker::Picker;
  29use project::Fs;
  30use project::Project;
  31use remote::ssh_session::ConnectionIdentifier;
  32use remote::{SshConnectionOptions, SshRemoteClient};
  33use settings::Settings;
  34use settings::SettingsStore;
  35use settings::update_settings_file;
  36use settings::watch_config_file;
  37use smol::stream::StreamExt as _;
  38use ui::Navigable;
  39use ui::NavigableEntry;
  40use ui::{
  41    IconButtonShape, List, ListItem, ListSeparator, Modal, ModalHeader, Scrollbar, ScrollbarState,
  42    Section, Tooltip, prelude::*,
  43};
  44use util::{
  45    ResultExt,
  46    paths::{PathStyle, RemotePathBuf},
  47};
  48use workspace::OpenOptions;
  49use workspace::Toast;
  50use workspace::notifications::NotificationId;
  51use workspace::{
  52    ModalView, Workspace, notifications::DetachAndPromptErr,
  53    open_ssh_project_with_existing_connection,
  54};
  55
  56use crate::ssh_config::parse_ssh_config_hosts;
  57use crate::ssh_connections::RemoteSettingsContent;
  58use crate::ssh_connections::SshConnection;
  59use crate::ssh_connections::SshConnectionHeader;
  60use crate::ssh_connections::SshConnectionModal;
  61use crate::ssh_connections::SshProject;
  62use crate::ssh_connections::SshPrompt;
  63use crate::ssh_connections::SshSettings;
  64use crate::ssh_connections::connect_over_ssh;
  65use crate::ssh_connections::open_ssh_project;
  66
  67mod navigation_base {}
  68pub struct RemoteServerProjects {
  69    mode: Mode,
  70    focus_handle: FocusHandle,
  71    workspace: WeakEntity<Workspace>,
  72    retained_connections: Vec<Entity<SshRemoteClient>>,
  73    ssh_config_updates: Task<()>,
  74    ssh_config_servers: BTreeSet<SharedString>,
  75    create_new_window: bool,
  76    _subscription: Subscription,
  77}
  78
  79struct CreateRemoteServer {
  80    address_editor: Entity<Editor>,
  81    address_error: Option<SharedString>,
  82    ssh_prompt: Option<Entity<SshPrompt>>,
  83    _creating: Option<Task<Option<()>>>,
  84}
  85
  86impl CreateRemoteServer {
  87    fn new(window: &mut Window, cx: &mut App) -> Self {
  88        let address_editor = cx.new(|cx| Editor::single_line(window, cx));
  89        address_editor.update(cx, |this, cx| {
  90            this.focus_handle(cx).focus(window);
  91        });
  92        Self {
  93            address_editor,
  94            address_error: None,
  95            ssh_prompt: None,
  96            _creating: None,
  97        }
  98    }
  99}
 100
 101struct ProjectPicker {
 102    connection_string: SharedString,
 103    nickname: Option<SharedString>,
 104    picker: Entity<Picker<OpenPathDelegate>>,
 105    _path_task: Shared<Task<Option<()>>>,
 106}
 107
 108struct EditNicknameState {
 109    index: usize,
 110    editor: Entity<Editor>,
 111}
 112
 113impl EditNicknameState {
 114    fn new(index: usize, window: &mut Window, cx: &mut App) -> Self {
 115        let this = Self {
 116            index,
 117            editor: cx.new(|cx| Editor::single_line(window, cx)),
 118        };
 119        let starting_text = SshSettings::get_global(cx)
 120            .ssh_connections()
 121            .nth(index)
 122            .and_then(|state| state.nickname.clone())
 123            .filter(|text| !text.is_empty());
 124        this.editor.update(cx, |this, cx| {
 125            this.set_placeholder_text("Add a nickname for this server", cx);
 126            if let Some(starting_text) = starting_text {
 127                this.set_text(starting_text, window, cx);
 128            }
 129        });
 130        this.editor.focus_handle(cx).focus(window);
 131        this
 132    }
 133}
 134
 135impl Focusable for ProjectPicker {
 136    fn focus_handle(&self, cx: &App) -> FocusHandle {
 137        self.picker.focus_handle(cx)
 138    }
 139}
 140
 141impl ProjectPicker {
 142    fn new(
 143        create_new_window: bool,
 144        ix: usize,
 145        connection: SshConnectionOptions,
 146        project: Entity<Project>,
 147        home_dir: RemotePathBuf,
 148        path_style: PathStyle,
 149        workspace: WeakEntity<Workspace>,
 150        window: &mut Window,
 151        cx: &mut Context<RemoteServerProjects>,
 152    ) -> Entity<Self> {
 153        let (tx, rx) = oneshot::channel();
 154        let lister = project::DirectoryLister::Project(project.clone());
 155        let delegate = file_finder::OpenPathDelegate::new(tx, lister, false, path_style);
 156
 157        let picker = cx.new(|cx| {
 158            let picker = Picker::uniform_list(delegate, window, cx)
 159                .width(rems(34.))
 160                .modal(false);
 161            picker.set_query(home_dir.to_string(), window, cx);
 162            picker
 163        });
 164        let connection_string = connection.connection_string().into();
 165        let nickname = connection.nickname.clone().map(|nick| nick.into());
 166        let _path_task = cx
 167            .spawn_in(window, {
 168                let workspace = workspace.clone();
 169                async move |this, cx| {
 170                    let Ok(Some(paths)) = rx.await else {
 171                        workspace
 172                            .update_in(cx, |workspace, window, cx| {
 173                                let fs = workspace.project().read(cx).fs().clone();
 174                                let weak = cx.entity().downgrade();
 175                                workspace.toggle_modal(window, cx, |window, cx| {
 176                                    RemoteServerProjects::new(
 177                                        create_new_window,
 178                                        fs,
 179                                        window,
 180                                        weak,
 181                                        cx,
 182                                    )
 183                                });
 184                            })
 185                            .log_err()?;
 186                        return None;
 187                    };
 188
 189                    let app_state = workspace
 190                        .read_with(cx, |workspace, _| workspace.app_state().clone())
 191                        .ok()?;
 192
 193                    cx.update(|_, cx| {
 194                        let fs = app_state.fs.clone();
 195                        update_settings_file::<SshSettings>(fs, cx, {
 196                            let paths = paths
 197                                .iter()
 198                                .map(|path| path.to_string_lossy().to_string())
 199                                .collect();
 200                            move |setting, _| {
 201                                if let Some(server) = setting
 202                                    .ssh_connections
 203                                    .as_mut()
 204                                    .and_then(|connections| connections.get_mut(ix))
 205                                {
 206                                    server.projects.insert(SshProject { paths });
 207                                }
 208                            }
 209                        });
 210                    })
 211                    .log_err();
 212
 213                    let options = cx
 214                        .update(|_, cx| (app_state.build_window_options)(None, cx))
 215                        .log_err()?;
 216                    let window = cx
 217                        .open_window(options, |window, cx| {
 218                            cx.new(|cx| {
 219                                telemetry::event!("SSH Project Created");
 220                                Workspace::new(None, project.clone(), app_state.clone(), window, cx)
 221                            })
 222                        })
 223                        .log_err()?;
 224
 225                    open_ssh_project_with_existing_connection(
 226                        connection, project, paths, app_state, window, cx,
 227                    )
 228                    .await
 229                    .log_err();
 230
 231                    this.update(cx, |_, cx| {
 232                        cx.emit(DismissEvent);
 233                    })
 234                    .ok();
 235                    Some(())
 236                }
 237            })
 238            .shared();
 239        cx.new(|_| Self {
 240            _path_task,
 241            picker,
 242            connection_string,
 243            nickname,
 244        })
 245    }
 246}
 247
 248impl gpui::Render for ProjectPicker {
 249    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 250        v_flex()
 251            .child(
 252                SshConnectionHeader {
 253                    connection_string: self.connection_string.clone(),
 254                    paths: Default::default(),
 255                    nickname: self.nickname.clone(),
 256                }
 257                .render(window, cx),
 258            )
 259            .child(
 260                div()
 261                    .border_t_1()
 262                    .border_color(cx.theme().colors().border_variant)
 263                    .child(self.picker.clone()),
 264            )
 265    }
 266}
 267
 268#[derive(Clone)]
 269enum RemoteEntry {
 270    Project {
 271        open_folder: NavigableEntry,
 272        projects: Vec<(NavigableEntry, SshProject)>,
 273        configure: NavigableEntry,
 274        connection: SshConnection,
 275    },
 276    SshConfig {
 277        open_folder: NavigableEntry,
 278        host: SharedString,
 279    },
 280}
 281
 282impl RemoteEntry {
 283    fn is_from_zed(&self) -> bool {
 284        matches!(self, Self::Project { .. })
 285    }
 286
 287    fn connection(&self) -> Cow<'_, SshConnection> {
 288        match self {
 289            Self::Project { connection, .. } => Cow::Borrowed(connection),
 290            Self::SshConfig { host, .. } => Cow::Owned(SshConnection {
 291                host: host.clone(),
 292                ..SshConnection::default()
 293            }),
 294        }
 295    }
 296}
 297
 298#[derive(Clone)]
 299struct DefaultState {
 300    scrollbar: ScrollbarState,
 301    add_new_server: NavigableEntry,
 302    servers: Vec<RemoteEntry>,
 303}
 304
 305impl DefaultState {
 306    fn new(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self {
 307        let handle = ScrollHandle::new();
 308        let scrollbar = ScrollbarState::new(handle.clone());
 309        let add_new_server = NavigableEntry::new(&handle, cx);
 310
 311        let ssh_settings = SshSettings::get_global(cx);
 312        let read_ssh_config = ssh_settings.read_ssh_config;
 313
 314        let mut servers: Vec<RemoteEntry> = ssh_settings
 315            .ssh_connections()
 316            .map(|connection| {
 317                let open_folder = NavigableEntry::new(&handle, cx);
 318                let configure = NavigableEntry::new(&handle, cx);
 319                let projects = connection
 320                    .projects
 321                    .iter()
 322                    .map(|project| (NavigableEntry::new(&handle, cx), project.clone()))
 323                    .collect();
 324                RemoteEntry::Project {
 325                    open_folder,
 326                    configure,
 327                    projects,
 328                    connection,
 329                }
 330            })
 331            .collect();
 332
 333        if read_ssh_config {
 334            let mut extra_servers_from_config = ssh_config_servers.clone();
 335            for server in &servers {
 336                if let RemoteEntry::Project { connection, .. } = server {
 337                    extra_servers_from_config.remove(&connection.host);
 338                }
 339            }
 340            servers.extend(extra_servers_from_config.into_iter().map(|host| {
 341                RemoteEntry::SshConfig {
 342                    open_folder: NavigableEntry::new(&handle, cx),
 343                    host,
 344                }
 345            }));
 346        }
 347
 348        Self {
 349            scrollbar,
 350            add_new_server,
 351            servers,
 352        }
 353    }
 354}
 355
 356#[derive(Clone)]
 357struct ViewServerOptionsState {
 358    server_index: usize,
 359    connection: SshConnection,
 360    entries: [NavigableEntry; 4],
 361}
 362enum Mode {
 363    Default(DefaultState),
 364    ViewServerOptions(ViewServerOptionsState),
 365    EditNickname(EditNicknameState),
 366    ProjectPicker(Entity<ProjectPicker>),
 367    CreateRemoteServer(CreateRemoteServer),
 368}
 369
 370impl Mode {
 371    fn default_mode(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self {
 372        Self::Default(DefaultState::new(ssh_config_servers, cx))
 373    }
 374}
 375impl RemoteServerProjects {
 376    pub fn new(
 377        create_new_window: bool,
 378        fs: Arc<dyn Fs>,
 379        window: &mut Window,
 380        workspace: WeakEntity<Workspace>,
 381        cx: &mut Context<Self>,
 382    ) -> Self {
 383        let focus_handle = cx.focus_handle();
 384        let mut read_ssh_config = SshSettings::get_global(cx).read_ssh_config;
 385        let ssh_config_updates = if read_ssh_config {
 386            spawn_ssh_config_watch(fs.clone(), cx)
 387        } else {
 388            Task::ready(())
 389        };
 390
 391        let mut base_style = window.text_style();
 392        base_style.refine(&gpui::TextStyleRefinement {
 393            color: Some(cx.theme().colors().editor_foreground),
 394            ..Default::default()
 395        });
 396
 397        let _subscription =
 398            cx.observe_global_in::<SettingsStore>(window, move |recent_projects, _, cx| {
 399                let new_read_ssh_config = SshSettings::get_global(cx).read_ssh_config;
 400                if read_ssh_config != new_read_ssh_config {
 401                    read_ssh_config = new_read_ssh_config;
 402                    if read_ssh_config {
 403                        recent_projects.ssh_config_updates = spawn_ssh_config_watch(fs.clone(), cx);
 404                    } else {
 405                        recent_projects.ssh_config_servers.clear();
 406                        recent_projects.ssh_config_updates = Task::ready(());
 407                    }
 408                }
 409            });
 410
 411        Self {
 412            mode: Mode::default_mode(&BTreeSet::new(), cx),
 413            focus_handle,
 414            workspace,
 415            retained_connections: Vec::new(),
 416            ssh_config_updates,
 417            ssh_config_servers: BTreeSet::new(),
 418            create_new_window,
 419            _subscription,
 420        }
 421    }
 422
 423    pub fn project_picker(
 424        create_new_window: bool,
 425        ix: usize,
 426        connection_options: remote::SshConnectionOptions,
 427        project: Entity<Project>,
 428        home_dir: RemotePathBuf,
 429        path_style: PathStyle,
 430        window: &mut Window,
 431        cx: &mut Context<Self>,
 432        workspace: WeakEntity<Workspace>,
 433    ) -> Self {
 434        let fs = project.read(cx).fs().clone();
 435        let mut this = Self::new(create_new_window, fs, window, workspace.clone(), cx);
 436        this.mode = Mode::ProjectPicker(ProjectPicker::new(
 437            create_new_window,
 438            ix,
 439            connection_options,
 440            project,
 441            home_dir,
 442            path_style,
 443            workspace,
 444            window,
 445            cx,
 446        ));
 447        cx.notify();
 448
 449        this
 450    }
 451
 452    fn create_ssh_server(
 453        &mut self,
 454        editor: Entity<Editor>,
 455        window: &mut Window,
 456        cx: &mut Context<Self>,
 457    ) {
 458        let input = get_text(&editor, cx);
 459        if input.is_empty() {
 460            return;
 461        }
 462
 463        let connection_options = match SshConnectionOptions::parse_command_line(&input) {
 464            Ok(c) => c,
 465            Err(e) => {
 466                self.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 467                    address_editor: editor,
 468                    address_error: Some(format!("could not parse: {:?}", e).into()),
 469                    ssh_prompt: None,
 470                    _creating: None,
 471                });
 472                return;
 473            }
 474        };
 475        let ssh_prompt = cx.new(|cx| SshPrompt::new(&connection_options, window, cx));
 476
 477        let connection = connect_over_ssh(
 478            ConnectionIdentifier::setup(),
 479            connection_options.clone(),
 480            ssh_prompt.clone(),
 481            window,
 482            cx,
 483        )
 484        .prompt_err("Failed to connect", window, cx, |_, _, _| None);
 485
 486        let address_editor = editor.clone();
 487        let creating = cx.spawn_in(window, async move |this, cx| {
 488            match connection.await {
 489                Some(Some(client)) => this
 490                    .update_in(cx, |this, window, cx| {
 491                        telemetry::event!("SSH Server Created");
 492                        this.retained_connections.push(client);
 493                        this.add_ssh_server(connection_options, cx);
 494                        this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
 495                        this.focus_handle(cx).focus(window);
 496                        cx.notify()
 497                    })
 498                    .log_err(),
 499                _ => this
 500                    .update(cx, |this, cx| {
 501                        address_editor.update(cx, |this, _| {
 502                            this.set_read_only(false);
 503                        });
 504                        this.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 505                            address_editor,
 506                            address_error: None,
 507                            ssh_prompt: None,
 508                            _creating: None,
 509                        });
 510                        cx.notify()
 511                    })
 512                    .log_err(),
 513            };
 514            None
 515        });
 516
 517        editor.update(cx, |this, _| {
 518            this.set_read_only(true);
 519        });
 520        self.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 521            address_editor: editor,
 522            address_error: None,
 523            ssh_prompt: Some(ssh_prompt.clone()),
 524            _creating: Some(creating),
 525        });
 526    }
 527
 528    fn view_server_options(
 529        &mut self,
 530        (server_index, connection): (usize, SshConnection),
 531        window: &mut Window,
 532        cx: &mut Context<Self>,
 533    ) {
 534        self.mode = Mode::ViewServerOptions(ViewServerOptionsState {
 535            server_index,
 536            connection,
 537            entries: std::array::from_fn(|_| NavigableEntry::focusable(cx)),
 538        });
 539        self.focus_handle(cx).focus(window);
 540        cx.notify();
 541    }
 542
 543    fn create_ssh_project(
 544        &mut self,
 545        ix: usize,
 546        ssh_connection: SshConnection,
 547        window: &mut Window,
 548        cx: &mut Context<Self>,
 549    ) {
 550        let Some(workspace) = self.workspace.upgrade() else {
 551            return;
 552        };
 553
 554        let create_new_window = self.create_new_window;
 555        let connection_options = ssh_connection.into();
 556        workspace.update(cx, |_, cx| {
 557            cx.defer_in(window, move |workspace, window, cx| {
 558                let app_state = workspace.app_state().clone();
 559                workspace.toggle_modal(window, cx, |window, cx| {
 560                    SshConnectionModal::new(&connection_options, Vec::new(), window, cx)
 561                });
 562                let prompt = workspace
 563                    .active_modal::<SshConnectionModal>(cx)
 564                    .unwrap()
 565                    .read(cx)
 566                    .prompt
 567                    .clone();
 568
 569                let connect = connect_over_ssh(
 570                    ConnectionIdentifier::setup(),
 571                    connection_options.clone(),
 572                    prompt,
 573                    window,
 574                    cx,
 575                )
 576                .prompt_err("Failed to connect", window, cx, |_, _, _| None);
 577
 578                cx.spawn_in(window, async move |workspace, cx| {
 579                    let session = connect.await;
 580
 581                    workspace.update(cx, |workspace, cx| {
 582                        if let Some(prompt) = workspace.active_modal::<SshConnectionModal>(cx) {
 583                            prompt.update(cx, |prompt, cx| prompt.finished(cx))
 584                        }
 585                    })?;
 586
 587                    let Some(Some(session)) = session else {
 588                        return workspace.update_in(cx, |workspace, window, cx| {
 589                            let weak = cx.entity().downgrade();
 590                            let fs = workspace.project().read(cx).fs().clone();
 591                            workspace.toggle_modal(window, cx, |window, cx| {
 592                                RemoteServerProjects::new(create_new_window, fs, window, weak, cx)
 593                            });
 594                        });
 595                    };
 596
 597                    let (path_style, project) = cx.update(|_, cx| {
 598                        (
 599                            session.read(cx).path_style(),
 600                            project::Project::ssh(
 601                                session,
 602                                app_state.client.clone(),
 603                                app_state.node_runtime.clone(),
 604                                app_state.user_store.clone(),
 605                                app_state.languages.clone(),
 606                                app_state.fs.clone(),
 607                                cx,
 608                            ),
 609                        )
 610                    })?;
 611
 612                    let home_dir = project
 613                        .read_with(cx, |project, cx| project.resolve_abs_path("~", cx))?
 614                        .await
 615                        .and_then(|path| path.into_abs_path())
 616                        .map(|path| RemotePathBuf::new(path, path_style))
 617                        .unwrap_or_else(|| match path_style {
 618                            PathStyle::Posix => RemotePathBuf::from_str("/", PathStyle::Posix),
 619                            PathStyle::Windows => {
 620                                RemotePathBuf::from_str("C:\\", PathStyle::Windows)
 621                            }
 622                        });
 623
 624                    workspace
 625                        .update_in(cx, |workspace, window, cx| {
 626                            let weak = cx.entity().downgrade();
 627                            workspace.toggle_modal(window, cx, |window, cx| {
 628                                RemoteServerProjects::project_picker(
 629                                    create_new_window,
 630                                    ix,
 631                                    connection_options,
 632                                    project,
 633                                    home_dir,
 634                                    path_style,
 635                                    window,
 636                                    cx,
 637                                    weak,
 638                                )
 639                            });
 640                        })
 641                        .ok();
 642                    Ok(())
 643                })
 644                .detach();
 645            })
 646        })
 647    }
 648
 649    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 650        match &self.mode {
 651            Mode::Default(_) | Mode::ViewServerOptions(_) => {}
 652            Mode::ProjectPicker(_) => {}
 653            Mode::CreateRemoteServer(state) => {
 654                if let Some(prompt) = state.ssh_prompt.as_ref() {
 655                    prompt.update(cx, |prompt, cx| {
 656                        prompt.confirm(window, cx);
 657                    });
 658                    return;
 659                }
 660
 661                self.create_ssh_server(state.address_editor.clone(), window, cx);
 662            }
 663            Mode::EditNickname(state) => {
 664                let text = Some(state.editor.read(cx).text(cx)).filter(|text| !text.is_empty());
 665                let index = state.index;
 666                self.update_settings_file(cx, move |setting, _| {
 667                    if let Some(connections) = setting.ssh_connections.as_mut()
 668                        && let Some(connection) = connections.get_mut(index) {
 669                            connection.nickname = text;
 670                        }
 671                });
 672                self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
 673                self.focus_handle.focus(window);
 674            }
 675        }
 676    }
 677
 678    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 679        match &self.mode {
 680            Mode::Default(_) => cx.emit(DismissEvent),
 681            Mode::CreateRemoteServer(state) if state.ssh_prompt.is_some() => {
 682                let new_state = CreateRemoteServer::new(window, cx);
 683                let old_prompt = state.address_editor.read(cx).text(cx);
 684                new_state.address_editor.update(cx, |this, cx| {
 685                    this.set_text(old_prompt, window, cx);
 686                });
 687
 688                self.mode = Mode::CreateRemoteServer(new_state);
 689                cx.notify();
 690            }
 691            _ => {
 692                self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
 693                self.focus_handle(cx).focus(window);
 694                cx.notify();
 695            }
 696        }
 697    }
 698
 699    fn render_ssh_connection(
 700        &mut self,
 701        ix: usize,
 702        ssh_server: RemoteEntry,
 703        window: &mut Window,
 704        cx: &mut Context<Self>,
 705    ) -> impl IntoElement {
 706        let connection = ssh_server.connection().into_owned();
 707        let (main_label, aux_label) = if let Some(nickname) = connection.nickname.clone() {
 708            let aux_label = SharedString::from(format!("({})", connection.host));
 709            (nickname.into(), Some(aux_label))
 710        } else {
 711            (connection.host.clone(), None)
 712        };
 713        v_flex()
 714            .w_full()
 715            .child(ListSeparator)
 716            .child(
 717                h_flex()
 718                    .group("ssh-server")
 719                    .w_full()
 720                    .pt_0p5()
 721                    .px_3()
 722                    .gap_1()
 723                    .overflow_hidden()
 724                    .child(
 725                        div().max_w_96().overflow_hidden().text_ellipsis().child(
 726                            Label::new(main_label)
 727                                .size(LabelSize::Small)
 728                                .color(Color::Muted),
 729                        ),
 730                    )
 731                    .children(
 732                        aux_label.map(|label| {
 733                            Label::new(label).size(LabelSize::Small).color(Color::Muted)
 734                        }),
 735                    ),
 736            )
 737            .child(match &ssh_server {
 738                RemoteEntry::Project {
 739                    open_folder,
 740                    projects,
 741                    configure,
 742                    connection,
 743                } => List::new()
 744                    .empty_message("No projects.")
 745                    .children(projects.iter().enumerate().map(|(pix, p)| {
 746                        v_flex().gap_0p5().child(self.render_ssh_project(
 747                            ix,
 748                            ssh_server.clone(),
 749                            pix,
 750                            p,
 751                            window,
 752                            cx,
 753                        ))
 754                    }))
 755                    .child(
 756                        h_flex()
 757                            .id(("new-remote-project-container", ix))
 758                            .track_focus(&open_folder.focus_handle)
 759                            .anchor_scroll(open_folder.scroll_anchor.clone())
 760                            .on_action(cx.listener({
 761                                let ssh_connection = connection.clone();
 762                                move |this, _: &menu::Confirm, window, cx| {
 763                                    this.create_ssh_project(ix, ssh_connection.clone(), window, cx);
 764                                }
 765                            }))
 766                            .child(
 767                                ListItem::new(("new-remote-project", ix))
 768                                    .toggle_state(
 769                                        open_folder.focus_handle.contains_focused(window, cx),
 770                                    )
 771                                    .inset(true)
 772                                    .spacing(ui::ListItemSpacing::Sparse)
 773                                    .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
 774                                    .child(Label::new("Open Folder"))
 775                                    .on_click(cx.listener({
 776                                        let ssh_connection = connection.clone();
 777                                        move |this, _, window, cx| {
 778                                            this.create_ssh_project(
 779                                                ix,
 780                                                ssh_connection.clone(),
 781                                                window,
 782                                                cx,
 783                                            );
 784                                        }
 785                                    })),
 786                            ),
 787                    )
 788                    .child(
 789                        h_flex()
 790                            .id(("server-options-container", ix))
 791                            .track_focus(&configure.focus_handle)
 792                            .anchor_scroll(configure.scroll_anchor.clone())
 793                            .on_action(cx.listener({
 794                                let ssh_connection = connection.clone();
 795                                move |this, _: &menu::Confirm, window, cx| {
 796                                    this.view_server_options(
 797                                        (ix, ssh_connection.clone()),
 798                                        window,
 799                                        cx,
 800                                    );
 801                                }
 802                            }))
 803                            .child(
 804                                ListItem::new(("server-options", ix))
 805                                    .toggle_state(
 806                                        configure.focus_handle.contains_focused(window, cx),
 807                                    )
 808                                    .inset(true)
 809                                    .spacing(ui::ListItemSpacing::Sparse)
 810                                    .start_slot(Icon::new(IconName::Settings).color(Color::Muted))
 811                                    .child(Label::new("View Server Options"))
 812                                    .on_click(cx.listener({
 813                                        let ssh_connection = connection.clone();
 814                                        move |this, _, window, cx| {
 815                                            this.view_server_options(
 816                                                (ix, ssh_connection.clone()),
 817                                                window,
 818                                                cx,
 819                                            );
 820                                        }
 821                                    })),
 822                            ),
 823                    ),
 824                RemoteEntry::SshConfig { open_folder, host } => List::new().child(
 825                    h_flex()
 826                        .id(("new-remote-project-container", ix))
 827                        .track_focus(&open_folder.focus_handle)
 828                        .anchor_scroll(open_folder.scroll_anchor.clone())
 829                        .on_action(cx.listener({
 830                            let ssh_connection = connection.clone();
 831                            let host = host.clone();
 832                            move |this, _: &menu::Confirm, window, cx| {
 833                                let new_ix = this.create_host_from_ssh_config(&host, cx);
 834                                this.create_ssh_project(new_ix, ssh_connection.clone(), window, cx);
 835                            }
 836                        }))
 837                        .child(
 838                            ListItem::new(("new-remote-project", ix))
 839                                .toggle_state(open_folder.focus_handle.contains_focused(window, cx))
 840                                .inset(true)
 841                                .spacing(ui::ListItemSpacing::Sparse)
 842                                .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
 843                                .child(Label::new("Open Folder"))
 844                                .on_click(cx.listener({
 845                                    let ssh_connection = connection.clone();
 846                                    let host = host.clone();
 847                                    move |this, _, window, cx| {
 848                                        let new_ix = this.create_host_from_ssh_config(&host, cx);
 849                                        this.create_ssh_project(
 850                                            new_ix,
 851                                            ssh_connection.clone(),
 852                                            window,
 853                                            cx,
 854                                        );
 855                                    }
 856                                })),
 857                        ),
 858                ),
 859            })
 860    }
 861
 862    fn render_ssh_project(
 863        &mut self,
 864        server_ix: usize,
 865        server: RemoteEntry,
 866        ix: usize,
 867        (navigation, project): &(NavigableEntry, SshProject),
 868        window: &mut Window,
 869        cx: &mut Context<Self>,
 870    ) -> impl IntoElement {
 871        let create_new_window = self.create_new_window;
 872        let is_from_zed = server.is_from_zed();
 873        let element_id_base = SharedString::from(format!("remote-project-{server_ix}"));
 874        let container_element_id_base =
 875            SharedString::from(format!("remote-project-container-{element_id_base}"));
 876
 877        let callback = Rc::new({
 878            let project = project.clone();
 879            move |remote_server_projects: &mut Self,
 880                  secondary_confirm: bool,
 881                  window: &mut Window,
 882                  cx: &mut Context<Self>| {
 883                let Some(app_state) = remote_server_projects
 884                    .workspace
 885                    .read_with(cx, |workspace, _| workspace.app_state().clone())
 886                    .log_err()
 887                else {
 888                    return;
 889                };
 890                let project = project.clone();
 891                let server = server.connection().into_owned();
 892                cx.emit(DismissEvent);
 893
 894                let replace_window = match (create_new_window, secondary_confirm) {
 895                    (true, false) | (false, true) => None,
 896                    (true, true) | (false, false) => window.window_handle().downcast::<Workspace>(),
 897                };
 898
 899                cx.spawn_in(window, async move |_, cx| {
 900                    let result = open_ssh_project(
 901                        server.into(),
 902                        project.paths.into_iter().map(PathBuf::from).collect(),
 903                        app_state,
 904                        OpenOptions {
 905                            replace_window,
 906                            ..OpenOptions::default()
 907                        },
 908                        cx,
 909                    )
 910                    .await;
 911                    if let Err(e) = result {
 912                        log::error!("Failed to connect: {e:#}");
 913                        cx.prompt(
 914                            gpui::PromptLevel::Critical,
 915                            "Failed to connect",
 916                            Some(&e.to_string()),
 917                            &["Ok"],
 918                        )
 919                        .await
 920                        .ok();
 921                    }
 922                })
 923                .detach();
 924            }
 925        });
 926
 927        div()
 928            .id((container_element_id_base, ix))
 929            .track_focus(&navigation.focus_handle)
 930            .anchor_scroll(navigation.scroll_anchor.clone())
 931            .on_action(cx.listener({
 932                let callback = callback.clone();
 933                move |this, _: &menu::Confirm, window, cx| {
 934                    callback(this, false, window, cx);
 935                }
 936            }))
 937            .on_action(cx.listener({
 938                let callback = callback.clone();
 939                move |this, _: &menu::SecondaryConfirm, window, cx| {
 940                    callback(this, true, window, cx);
 941                }
 942            }))
 943            .child(
 944                ListItem::new((element_id_base, ix))
 945                    .toggle_state(navigation.focus_handle.contains_focused(window, cx))
 946                    .inset(true)
 947                    .spacing(ui::ListItemSpacing::Sparse)
 948                    .start_slot(
 949                        Icon::new(IconName::Folder)
 950                            .color(Color::Muted)
 951                            .size(IconSize::Small),
 952                    )
 953                    .child(Label::new(project.paths.join(", ")))
 954                    .on_click(cx.listener(move |this, e: &ClickEvent, window, cx| {
 955                        let secondary_confirm = e.modifiers().platform;
 956                        callback(this, secondary_confirm, window, cx)
 957                    }))
 958                    .when(is_from_zed, |server_list_item| {
 959                        server_list_item.end_hover_slot::<AnyElement>(Some(
 960                            div()
 961                                .mr_2()
 962                                .child({
 963                                    let project = project.clone();
 964                                    // Right-margin to offset it from the Scrollbar
 965                                    IconButton::new("remove-remote-project", IconName::Trash)
 966                                        .icon_size(IconSize::Small)
 967                                        .shape(IconButtonShape::Square)
 968                                        .size(ButtonSize::Large)
 969                                        .tooltip(Tooltip::text("Delete Remote Project"))
 970                                        .on_click(cx.listener(move |this, _, _, cx| {
 971                                            this.delete_ssh_project(server_ix, &project, cx)
 972                                        }))
 973                                })
 974                                .into_any_element(),
 975                        ))
 976                    }),
 977            )
 978    }
 979
 980    fn update_settings_file(
 981        &mut self,
 982        cx: &mut Context<Self>,
 983        f: impl FnOnce(&mut RemoteSettingsContent, &App) + Send + Sync + 'static,
 984    ) {
 985        let Some(fs) = self
 986            .workspace
 987            .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
 988            .log_err()
 989        else {
 990            return;
 991        };
 992        update_settings_file::<SshSettings>(fs, cx, move |setting, cx| f(setting, cx));
 993    }
 994
 995    fn delete_ssh_server(&mut self, server: usize, cx: &mut Context<Self>) {
 996        self.update_settings_file(cx, move |setting, _| {
 997            if let Some(connections) = setting.ssh_connections.as_mut() {
 998                connections.remove(server);
 999            }
1000        });
1001    }
1002
1003    fn delete_ssh_project(&mut self, server: usize, project: &SshProject, cx: &mut Context<Self>) {
1004        let project = project.clone();
1005        self.update_settings_file(cx, move |setting, _| {
1006            if let Some(server) = setting
1007                .ssh_connections
1008                .as_mut()
1009                .and_then(|connections| connections.get_mut(server))
1010            {
1011                server.projects.remove(&project);
1012            }
1013        });
1014    }
1015
1016    fn add_ssh_server(
1017        &mut self,
1018        connection_options: remote::SshConnectionOptions,
1019        cx: &mut Context<Self>,
1020    ) {
1021        self.update_settings_file(cx, move |setting, _| {
1022            setting
1023                .ssh_connections
1024                .get_or_insert(Default::default())
1025                .push(SshConnection {
1026                    host: SharedString::from(connection_options.host),
1027                    username: connection_options.username,
1028                    port: connection_options.port,
1029                    projects: BTreeSet::new(),
1030                    nickname: None,
1031                    args: connection_options.args.unwrap_or_default(),
1032                    upload_binary_over_ssh: None,
1033                    port_forwards: connection_options.port_forwards,
1034                })
1035        });
1036    }
1037
1038    fn render_create_remote_server(
1039        &self,
1040        state: &CreateRemoteServer,
1041        cx: &mut Context<Self>,
1042    ) -> impl IntoElement {
1043        let ssh_prompt = state.ssh_prompt.clone();
1044
1045        state.address_editor.update(cx, |editor, cx| {
1046            if editor.text(cx).is_empty() {
1047                editor.set_placeholder_text("ssh user@example -p 2222", cx);
1048            }
1049        });
1050
1051        let theme = cx.theme();
1052
1053        v_flex()
1054            .track_focus(&self.focus_handle(cx))
1055            .id("create-remote-server")
1056            .overflow_hidden()
1057            .size_full()
1058            .flex_1()
1059            .child(
1060                div()
1061                    .p_2()
1062                    .border_b_1()
1063                    .border_color(theme.colors().border_variant)
1064                    .child(state.address_editor.clone()),
1065            )
1066            .child(
1067                h_flex()
1068                    .bg(theme.colors().editor_background)
1069                    .rounded_b_sm()
1070                    .w_full()
1071                    .map(|this| {
1072                        if let Some(ssh_prompt) = ssh_prompt {
1073                            this.child(h_flex().w_full().child(ssh_prompt))
1074                        } else if let Some(address_error) = &state.address_error {
1075                            this.child(
1076                                h_flex().p_2().w_full().gap_2().child(
1077                                    Label::new(address_error.clone())
1078                                        .size(LabelSize::Small)
1079                                        .color(Color::Error),
1080                                ),
1081                            )
1082                        } else {
1083                            this.child(
1084                                h_flex()
1085                                    .p_2()
1086                                    .w_full()
1087                                    .gap_1()
1088                                    .child(
1089                                        Label::new(
1090                                            "Enter the command you use to SSH into this server.",
1091                                        )
1092                                        .color(Color::Muted)
1093                                        .size(LabelSize::Small),
1094                                    )
1095                                    .child(
1096                                        Button::new("learn-more", "Learn More")
1097                                            .label_size(LabelSize::Small)
1098                                            .icon(IconName::ArrowUpRight)
1099                                            .icon_size(IconSize::XSmall)
1100                                            .on_click(|_, _, cx| {
1101                                                cx.open_url(
1102                                                    "https://zed.dev/docs/remote-development",
1103                                                );
1104                                            }),
1105                                    ),
1106                            )
1107                        }
1108                    }),
1109            )
1110    }
1111
1112    fn render_view_options(
1113        &mut self,
1114        ViewServerOptionsState {
1115            server_index,
1116            connection,
1117            entries,
1118        }: ViewServerOptionsState,
1119        window: &mut Window,
1120        cx: &mut Context<Self>,
1121    ) -> impl IntoElement {
1122        let connection_string = connection.host.clone();
1123
1124        let mut view = Navigable::new(
1125            div()
1126                .track_focus(&self.focus_handle(cx))
1127                .size_full()
1128                .child(
1129                    SshConnectionHeader {
1130                        connection_string: connection_string.clone(),
1131                        paths: Default::default(),
1132                        nickname: connection.nickname.clone().map(|s| s.into()),
1133                    }
1134                    .render(window, cx),
1135                )
1136                .child(
1137                    v_flex()
1138                        .pb_1()
1139                        .child(ListSeparator)
1140                        .child({
1141                            let label = if connection.nickname.is_some() {
1142                                "Edit Nickname"
1143                            } else {
1144                                "Add Nickname to Server"
1145                            };
1146                            div()
1147                                .id("ssh-options-add-nickname")
1148                                .track_focus(&entries[0].focus_handle)
1149                                .on_action(cx.listener(
1150                                    move |this, _: &menu::Confirm, window, cx| {
1151                                        this.mode = Mode::EditNickname(EditNicknameState::new(
1152                                            server_index,
1153                                            window,
1154                                            cx,
1155                                        ));
1156                                        cx.notify();
1157                                    },
1158                                ))
1159                                .child(
1160                                    ListItem::new("add-nickname")
1161                                        .toggle_state(
1162                                            entries[0].focus_handle.contains_focused(window, cx),
1163                                        )
1164                                        .inset(true)
1165                                        .spacing(ui::ListItemSpacing::Sparse)
1166                                        .start_slot(Icon::new(IconName::Pencil).color(Color::Muted))
1167                                        .child(Label::new(label))
1168                                        .on_click(cx.listener(move |this, _, window, cx| {
1169                                            this.mode = Mode::EditNickname(EditNicknameState::new(
1170                                                server_index,
1171                                                window,
1172                                                cx,
1173                                            ));
1174                                            cx.notify();
1175                                        })),
1176                                )
1177                        })
1178                        .child({
1179                            let workspace = self.workspace.clone();
1180                            fn callback(
1181                                workspace: WeakEntity<Workspace>,
1182                                connection_string: SharedString,
1183                                cx: &mut App,
1184                            ) {
1185                                cx.write_to_clipboard(ClipboardItem::new_string(
1186                                    connection_string.to_string(),
1187                                ));
1188                                workspace
1189                                    .update(cx, |this, cx| {
1190                                        struct SshServerAddressCopiedToClipboard;
1191                                        let notification = format!(
1192                                            "Copied server address ({}) to clipboard",
1193                                            connection_string
1194                                        );
1195
1196                                        this.show_toast(
1197                                            Toast::new(
1198                                                NotificationId::composite::<
1199                                                    SshServerAddressCopiedToClipboard,
1200                                                >(
1201                                                    connection_string.clone()
1202                                                ),
1203                                                notification,
1204                                            )
1205                                            .autohide(),
1206                                            cx,
1207                                        );
1208                                    })
1209                                    .ok();
1210                            }
1211                            div()
1212                                .id("ssh-options-copy-server-address")
1213                                .track_focus(&entries[1].focus_handle)
1214                                .on_action({
1215                                    let connection_string = connection_string.clone();
1216                                    let workspace = self.workspace.clone();
1217                                    move |_: &menu::Confirm, _, cx| {
1218                                        callback(workspace.clone(), connection_string.clone(), cx);
1219                                    }
1220                                })
1221                                .child(
1222                                    ListItem::new("copy-server-address")
1223                                        .toggle_state(
1224                                            entries[1].focus_handle.contains_focused(window, cx),
1225                                        )
1226                                        .inset(true)
1227                                        .spacing(ui::ListItemSpacing::Sparse)
1228                                        .start_slot(Icon::new(IconName::Copy).color(Color::Muted))
1229                                        .child(Label::new("Copy Server Address"))
1230                                        .end_hover_slot(
1231                                            Label::new(connection_string.clone())
1232                                                .color(Color::Muted),
1233                                        )
1234                                        .on_click({
1235                                            let connection_string = connection_string.clone();
1236                                            move |_, _, cx| {
1237                                                callback(
1238                                                    workspace.clone(),
1239                                                    connection_string.clone(),
1240                                                    cx,
1241                                                );
1242                                            }
1243                                        }),
1244                                )
1245                        })
1246                        .child({
1247                            fn remove_ssh_server(
1248                                remote_servers: Entity<RemoteServerProjects>,
1249                                index: usize,
1250                                connection_string: SharedString,
1251                                window: &mut Window,
1252                                cx: &mut App,
1253                            ) {
1254                                let prompt_message =
1255                                    format!("Remove server `{}`?", connection_string);
1256
1257                                let confirmation = window.prompt(
1258                                    PromptLevel::Warning,
1259                                    &prompt_message,
1260                                    None,
1261                                    &["Yes, remove it", "No, keep it"],
1262                                    cx,
1263                                );
1264
1265                                cx.spawn(async move |cx| {
1266                                    if confirmation.await.ok() == Some(0) {
1267                                        remote_servers
1268                                            .update(cx, |this, cx| {
1269                                                this.delete_ssh_server(index, cx);
1270                                            })
1271                                            .ok();
1272                                        remote_servers
1273                                            .update(cx, |this, cx| {
1274                                                this.mode = Mode::default_mode(
1275                                                    &this.ssh_config_servers,
1276                                                    cx,
1277                                                );
1278                                                cx.notify();
1279                                            })
1280                                            .ok();
1281                                    }
1282                                    anyhow::Ok(())
1283                                })
1284                                .detach_and_log_err(cx);
1285                            }
1286                            div()
1287                                .id("ssh-options-copy-server-address")
1288                                .track_focus(&entries[2].focus_handle)
1289                                .on_action(cx.listener({
1290                                    let connection_string = connection_string.clone();
1291                                    move |_, _: &menu::Confirm, window, cx| {
1292                                        remove_ssh_server(
1293                                            cx.entity(),
1294                                            server_index,
1295                                            connection_string.clone(),
1296                                            window,
1297                                            cx,
1298                                        );
1299                                        cx.focus_self(window);
1300                                    }
1301                                }))
1302                                .child(
1303                                    ListItem::new("remove-server")
1304                                        .toggle_state(
1305                                            entries[2].focus_handle.contains_focused(window, cx),
1306                                        )
1307                                        .inset(true)
1308                                        .spacing(ui::ListItemSpacing::Sparse)
1309                                        .start_slot(Icon::new(IconName::Trash).color(Color::Error))
1310                                        .child(Label::new("Remove Server").color(Color::Error))
1311                                        .on_click(cx.listener(move |_, _, window, cx| {
1312                                            remove_ssh_server(
1313                                                cx.entity(),
1314                                                server_index,
1315                                                connection_string.clone(),
1316                                                window,
1317                                                cx,
1318                                            );
1319                                            cx.focus_self(window);
1320                                        })),
1321                                )
1322                        })
1323                        .child(ListSeparator)
1324                        .child({
1325                            div()
1326                                .id("ssh-options-copy-server-address")
1327                                .track_focus(&entries[3].focus_handle)
1328                                .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
1329                                    this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
1330                                    cx.focus_self(window);
1331                                    cx.notify();
1332                                }))
1333                                .child(
1334                                    ListItem::new("go-back")
1335                                        .toggle_state(
1336                                            entries[3].focus_handle.contains_focused(window, cx),
1337                                        )
1338                                        .inset(true)
1339                                        .spacing(ui::ListItemSpacing::Sparse)
1340                                        .start_slot(
1341                                            Icon::new(IconName::ArrowLeft).color(Color::Muted),
1342                                        )
1343                                        .child(Label::new("Go Back"))
1344                                        .on_click(cx.listener(|this, _, window, cx| {
1345                                            this.mode =
1346                                                Mode::default_mode(&this.ssh_config_servers, cx);
1347                                            cx.focus_self(window);
1348                                            cx.notify()
1349                                        })),
1350                                )
1351                        }),
1352                )
1353                .into_any_element(),
1354        );
1355        for entry in entries {
1356            view = view.entry(entry);
1357        }
1358
1359        view.render(window, cx).into_any_element()
1360    }
1361
1362    fn render_edit_nickname(
1363        &self,
1364        state: &EditNicknameState,
1365        window: &mut Window,
1366        cx: &mut Context<Self>,
1367    ) -> impl IntoElement {
1368        let Some(connection) = SshSettings::get_global(cx)
1369            .ssh_connections()
1370            .nth(state.index)
1371        else {
1372            return v_flex()
1373                .id("ssh-edit-nickname")
1374                .track_focus(&self.focus_handle(cx));
1375        };
1376
1377        let connection_string = connection.host.clone();
1378        let nickname = connection.nickname.clone().map(|s| s.into());
1379
1380        v_flex()
1381            .id("ssh-edit-nickname")
1382            .track_focus(&self.focus_handle(cx))
1383            .child(
1384                SshConnectionHeader {
1385                    connection_string,
1386                    paths: Default::default(),
1387                    nickname,
1388                }
1389                .render(window, cx),
1390            )
1391            .child(
1392                h_flex()
1393                    .p_2()
1394                    .border_t_1()
1395                    .border_color(cx.theme().colors().border_variant)
1396                    .child(state.editor.clone()),
1397            )
1398    }
1399
1400    fn render_default(
1401        &mut self,
1402        mut state: DefaultState,
1403        window: &mut Window,
1404        cx: &mut Context<Self>,
1405    ) -> impl IntoElement {
1406        let ssh_settings = SshSettings::get_global(cx);
1407        let mut should_rebuild = false;
1408
1409        if ssh_settings
1410            .ssh_connections
1411            .as_ref()
1412            .map_or(false, |connections| {
1413                state
1414                    .servers
1415                    .iter()
1416                    .filter_map(|server| match server {
1417                        RemoteEntry::Project { connection, .. } => Some(connection),
1418                        RemoteEntry::SshConfig { .. } => None,
1419                    })
1420                    .ne(connections.iter())
1421            })
1422        {
1423            should_rebuild = true;
1424        };
1425
1426        if !should_rebuild && ssh_settings.read_ssh_config {
1427            let current_ssh_hosts: BTreeSet<SharedString> = state
1428                .servers
1429                .iter()
1430                .filter_map(|server| match server {
1431                    RemoteEntry::SshConfig { host, .. } => Some(host.clone()),
1432                    _ => None,
1433                })
1434                .collect();
1435            let mut expected_ssh_hosts = self.ssh_config_servers.clone();
1436            for server in &state.servers {
1437                if let RemoteEntry::Project { connection, .. } = server {
1438                    expected_ssh_hosts.remove(&connection.host);
1439                }
1440            }
1441            should_rebuild = current_ssh_hosts != expected_ssh_hosts;
1442        }
1443
1444        if should_rebuild {
1445            self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
1446            if let Mode::Default(new_state) = &self.mode {
1447                state = new_state.clone();
1448            }
1449        }
1450
1451        let scroll_state = state.scrollbar.parent_entity(&cx.entity());
1452        let connect_button = div()
1453            .id("ssh-connect-new-server-container")
1454            .track_focus(&state.add_new_server.focus_handle)
1455            .anchor_scroll(state.add_new_server.scroll_anchor.clone())
1456            .child(
1457                ListItem::new("register-remove-server-button")
1458                    .toggle_state(
1459                        state
1460                            .add_new_server
1461                            .focus_handle
1462                            .contains_focused(window, cx),
1463                    )
1464                    .inset(true)
1465                    .spacing(ui::ListItemSpacing::Sparse)
1466                    .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
1467                    .child(Label::new("Connect New Server"))
1468                    .on_click(cx.listener(|this, _, window, cx| {
1469                        let state = CreateRemoteServer::new(window, cx);
1470                        this.mode = Mode::CreateRemoteServer(state);
1471
1472                        cx.notify();
1473                    })),
1474            )
1475            .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
1476                let state = CreateRemoteServer::new(window, cx);
1477                this.mode = Mode::CreateRemoteServer(state);
1478
1479                cx.notify();
1480            }));
1481
1482        let handle = &**scroll_state.scroll_handle() as &dyn Any;
1483        let Some(scroll_handle) = handle.downcast_ref::<ScrollHandle>() else {
1484            unreachable!()
1485        };
1486
1487        let mut modal_section = Navigable::new(
1488            v_flex()
1489                .track_focus(&self.focus_handle(cx))
1490                .id("ssh-server-list")
1491                .overflow_y_scroll()
1492                .track_scroll(scroll_handle)
1493                .size_full()
1494                .child(connect_button)
1495                .child(
1496                    List::new()
1497                        .empty_message(
1498                            v_flex()
1499                                .child(
1500                                    div().px_3().child(
1501                                        Label::new("No remote servers registered yet.")
1502                                            .color(Color::Muted),
1503                                    ),
1504                                )
1505                                .into_any_element(),
1506                        )
1507                        .children(state.servers.iter().enumerate().map(|(ix, connection)| {
1508                            self.render_ssh_connection(ix, connection.clone(), window, cx)
1509                                .into_any_element()
1510                        })),
1511                )
1512                .into_any_element(),
1513        )
1514        .entry(state.add_new_server.clone());
1515
1516        for server in &state.servers {
1517            match server {
1518                RemoteEntry::Project {
1519                    open_folder,
1520                    projects,
1521                    configure,
1522                    ..
1523                } => {
1524                    for (navigation_state, _) in projects {
1525                        modal_section = modal_section.entry(navigation_state.clone());
1526                    }
1527                    modal_section = modal_section
1528                        .entry(open_folder.clone())
1529                        .entry(configure.clone());
1530                }
1531                RemoteEntry::SshConfig { open_folder, .. } => {
1532                    modal_section = modal_section.entry(open_folder.clone());
1533                }
1534            }
1535        }
1536        let mut modal_section = modal_section.render(window, cx).into_any_element();
1537
1538        let (create_window, reuse_window) = if self.create_new_window {
1539            (
1540                window.keystroke_text_for(&menu::Confirm),
1541                window.keystroke_text_for(&menu::SecondaryConfirm),
1542            )
1543        } else {
1544            (
1545                window.keystroke_text_for(&menu::SecondaryConfirm),
1546                window.keystroke_text_for(&menu::Confirm),
1547            )
1548        };
1549        let placeholder_text = Arc::from(format!(
1550            "{reuse_window} reuses this window, {create_window} opens a new one",
1551        ));
1552
1553        Modal::new("remote-projects", None)
1554            .header(
1555                ModalHeader::new()
1556                    .child(Headline::new("Remote Projects").size(HeadlineSize::XSmall))
1557                    .child(
1558                        Label::new(placeholder_text)
1559                            .color(Color::Muted)
1560                            .size(LabelSize::XSmall),
1561                    ),
1562            )
1563            .section(
1564                Section::new().padded(false).child(
1565                    v_flex()
1566                        .min_h(rems(20.))
1567                        .size_full()
1568                        .relative()
1569                        .child(ListSeparator)
1570                        .child(
1571                            canvas(
1572                                |bounds, window, cx| {
1573                                    modal_section.prepaint_as_root(
1574                                        bounds.origin,
1575                                        bounds.size.into(),
1576                                        window,
1577                                        cx,
1578                                    );
1579                                    modal_section
1580                                },
1581                                |_, mut modal_section, window, cx| {
1582                                    modal_section.paint(window, cx);
1583                                },
1584                            )
1585                            .size_full(),
1586                        )
1587                        .child(
1588                            div()
1589                                .occlude()
1590                                .h_full()
1591                                .absolute()
1592                                .top_1()
1593                                .bottom_1()
1594                                .right_1()
1595                                .w(px(8.))
1596                                .children(Scrollbar::vertical(scroll_state)),
1597                        ),
1598                ),
1599            )
1600            .into_any_element()
1601    }
1602
1603    fn create_host_from_ssh_config(
1604        &mut self,
1605        ssh_config_host: &SharedString,
1606        cx: &mut Context<'_, Self>,
1607    ) -> usize {
1608        let new_ix = Arc::new(AtomicUsize::new(0));
1609
1610        let update_new_ix = new_ix.clone();
1611        self.update_settings_file(cx, move |settings, _| {
1612            update_new_ix.store(
1613                settings
1614                    .ssh_connections
1615                    .as_ref()
1616                    .map_or(0, |connections| connections.len()),
1617                atomic::Ordering::Release,
1618            );
1619        });
1620
1621        self.add_ssh_server(
1622            SshConnectionOptions {
1623                host: ssh_config_host.to_string(),
1624                ..SshConnectionOptions::default()
1625            },
1626            cx,
1627        );
1628        self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
1629        new_ix.load(atomic::Ordering::Acquire)
1630    }
1631}
1632
1633fn spawn_ssh_config_watch(fs: Arc<dyn Fs>, cx: &Context<RemoteServerProjects>) -> Task<()> {
1634    let mut user_ssh_config_watcher =
1635        watch_config_file(cx.background_executor(), fs.clone(), user_ssh_config_file());
1636    let mut global_ssh_config_watcher = watch_config_file(
1637        cx.background_executor(),
1638        fs,
1639        global_ssh_config_file().to_owned(),
1640    );
1641
1642    cx.spawn(async move |remote_server_projects, cx| {
1643        let mut global_hosts = BTreeSet::default();
1644        let mut user_hosts = BTreeSet::default();
1645        let mut running_receivers = 2;
1646
1647        loop {
1648            select! {
1649                new_global_file_contents = global_ssh_config_watcher.next().fuse() => {
1650                    match new_global_file_contents {
1651                        Some(new_global_file_contents) => {
1652                            global_hosts = parse_ssh_config_hosts(&new_global_file_contents);
1653                            if remote_server_projects.update(cx, |remote_server_projects, cx| {
1654                                remote_server_projects.ssh_config_servers = global_hosts.iter().chain(user_hosts.iter()).map(SharedString::from).collect();
1655                                cx.notify();
1656                            }).is_err() {
1657                                return;
1658                            }
1659                        },
1660                        None => {
1661                            running_receivers -= 1;
1662                            if running_receivers == 0 {
1663                                return;
1664                            }
1665                        }
1666                    }
1667                },
1668                new_user_file_contents = user_ssh_config_watcher.next().fuse() => {
1669                    match new_user_file_contents {
1670                        Some(new_user_file_contents) => {
1671                            user_hosts = parse_ssh_config_hosts(&new_user_file_contents);
1672                            if remote_server_projects.update(cx, |remote_server_projects, cx| {
1673                                remote_server_projects.ssh_config_servers = global_hosts.iter().chain(user_hosts.iter()).map(SharedString::from).collect();
1674                                cx.notify();
1675                            }).is_err() {
1676                                return;
1677                            }
1678                        },
1679                        None => {
1680                            running_receivers -= 1;
1681                            if running_receivers == 0 {
1682                                return;
1683                            }
1684                        }
1685                    }
1686                },
1687            }
1688        }
1689    })
1690}
1691
1692fn get_text(element: &Entity<Editor>, cx: &mut App) -> String {
1693    element.read(cx).text(cx).trim().to_string()
1694}
1695
1696impl ModalView for RemoteServerProjects {}
1697
1698impl Focusable for RemoteServerProjects {
1699    fn focus_handle(&self, cx: &App) -> FocusHandle {
1700        match &self.mode {
1701            Mode::ProjectPicker(picker) => picker.focus_handle(cx),
1702            _ => self.focus_handle.clone(),
1703        }
1704    }
1705}
1706
1707impl EventEmitter<DismissEvent> for RemoteServerProjects {}
1708
1709impl Render for RemoteServerProjects {
1710    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1711        div()
1712            .elevation_3(cx)
1713            .w(rems(34.))
1714            .key_context("RemoteServerModal")
1715            .on_action(cx.listener(Self::cancel))
1716            .on_action(cx.listener(Self::confirm))
1717            .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
1718                this.focus_handle(cx).focus(window);
1719            }))
1720            .on_mouse_down_out(cx.listener(|this, _, _, cx| {
1721                if matches!(this.mode, Mode::Default(_)) {
1722                    cx.emit(DismissEvent)
1723                }
1724            }))
1725            .child(match &self.mode {
1726                Mode::Default(state) => self
1727                    .render_default(state.clone(), window, cx)
1728                    .into_any_element(),
1729                Mode::ViewServerOptions(state) => self
1730                    .render_view_options(state.clone(), window, cx)
1731                    .into_any_element(),
1732                Mode::ProjectPicker(element) => element.clone().into_any_element(),
1733                Mode::CreateRemoteServer(state) => self
1734                    .render_create_remote_server(state, cx)
1735                    .into_any_element(),
1736                Mode::EditNickname(state) => self
1737                    .render_edit_nickname(state, window, cx)
1738                    .into_any_element(),
1739            })
1740    }
1741}