remote_servers.rs

   1use std::path::PathBuf;
   2use std::sync::Arc;
   3
   4use editor::Editor;
   5use file_finder::OpenPathDelegate;
   6use futures::channel::oneshot;
   7use futures::future::Shared;
   8use futures::FutureExt;
   9use gpui::canvas;
  10use gpui::ClipboardItem;
  11use gpui::Task;
  12use gpui::WeakView;
  13use gpui::{
  14    AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Model,
  15    PromptLevel, ScrollHandle, View, ViewContext,
  16};
  17use picker::Picker;
  18use project::Project;
  19use remote::ssh_session::ConnectionIdentifier;
  20use remote::SshConnectionOptions;
  21use remote::SshRemoteClient;
  22use settings::update_settings_file;
  23use settings::Settings;
  24use ui::{
  25    prelude::*, IconButtonShape, List, ListItem, ListSeparator, Modal, ModalHeader, Scrollbar,
  26    ScrollbarState, Section, Tooltip,
  27};
  28use util::ResultExt;
  29use workspace::notifications::NotificationId;
  30use workspace::OpenOptions;
  31use workspace::Toast;
  32use workspace::{notifications::DetachAndPromptErr, ModalView, Workspace};
  33
  34use crate::ssh_connections::connect_over_ssh;
  35use crate::ssh_connections::open_ssh_project;
  36use crate::ssh_connections::RemoteSettingsContent;
  37use crate::ssh_connections::SshConnection;
  38use crate::ssh_connections::SshConnectionHeader;
  39use crate::ssh_connections::SshConnectionModal;
  40use crate::ssh_connections::SshProject;
  41use crate::ssh_connections::SshPrompt;
  42use crate::ssh_connections::SshSettings;
  43use crate::OpenRemote;
  44
  45pub struct RemoteServerProjects {
  46    mode: Mode,
  47    focus_handle: FocusHandle,
  48    scroll_handle: ScrollHandle,
  49    workspace: WeakView<Workspace>,
  50    selectable_items: SelectableItemList,
  51    retained_connections: Vec<Model<SshRemoteClient>>,
  52}
  53
  54struct CreateRemoteServer {
  55    address_editor: View<Editor>,
  56    address_error: Option<SharedString>,
  57    ssh_prompt: Option<View<SshPrompt>>,
  58    _creating: Option<Task<Option<()>>>,
  59}
  60
  61impl CreateRemoteServer {
  62    fn new(cx: &mut WindowContext<'_>) -> Self {
  63        let address_editor = cx.new_view(Editor::single_line);
  64        address_editor.update(cx, |this, cx| {
  65            this.focus_handle(cx).focus(cx);
  66        });
  67        Self {
  68            address_editor,
  69            address_error: None,
  70            ssh_prompt: None,
  71            _creating: None,
  72        }
  73    }
  74}
  75
  76struct ProjectPicker {
  77    connection_string: SharedString,
  78    nickname: Option<SharedString>,
  79    picker: View<Picker<OpenPathDelegate>>,
  80    _path_task: Shared<Task<Option<()>>>,
  81}
  82
  83type SelectedItemCallback =
  84    Box<dyn Fn(&mut RemoteServerProjects, &mut ViewContext<RemoteServerProjects>) + 'static>;
  85
  86/// Used to implement keyboard navigation for SSH modal.
  87#[derive(Default)]
  88struct SelectableItemList {
  89    items: Vec<SelectedItemCallback>,
  90    active_item: Option<usize>,
  91}
  92
  93struct EditNicknameState {
  94    index: usize,
  95    editor: View<Editor>,
  96}
  97
  98impl EditNicknameState {
  99    fn new(index: usize, cx: &mut WindowContext<'_>) -> Self {
 100        let this = Self {
 101            index,
 102            editor: cx.new_view(Editor::single_line),
 103        };
 104        let starting_text = SshSettings::get_global(cx)
 105            .ssh_connections()
 106            .nth(index)
 107            .and_then(|state| state.nickname.clone())
 108            .filter(|text| !text.is_empty());
 109        this.editor.update(cx, |this, cx| {
 110            this.set_placeholder_text("Add a nickname for this server", cx);
 111            if let Some(starting_text) = starting_text {
 112                this.set_text(starting_text, cx);
 113            }
 114        });
 115        this.editor.focus_handle(cx).focus(cx);
 116        this
 117    }
 118}
 119
 120impl SelectableItemList {
 121    fn reset(&mut self) {
 122        self.items.clear();
 123    }
 124
 125    fn reset_selection(&mut self) {
 126        self.active_item.take();
 127    }
 128
 129    fn prev(&mut self, _: &mut WindowContext<'_>) {
 130        match self.active_item.as_mut() {
 131            Some(active_index) => {
 132                *active_index = active_index.checked_sub(1).unwrap_or(self.items.len() - 1)
 133            }
 134            None => {
 135                self.active_item = Some(self.items.len() - 1);
 136            }
 137        }
 138    }
 139
 140    fn next(&mut self, _: &mut WindowContext<'_>) {
 141        match self.active_item.as_mut() {
 142            Some(active_index) => {
 143                if *active_index + 1 < self.items.len() {
 144                    *active_index += 1;
 145                } else {
 146                    *active_index = 0;
 147                }
 148            }
 149            None => {
 150                self.active_item = Some(0);
 151            }
 152        }
 153    }
 154
 155    fn add_item(&mut self, callback: SelectedItemCallback) {
 156        self.items.push(callback)
 157    }
 158
 159    fn is_selected(&self) -> bool {
 160        self.active_item == self.items.len().checked_sub(1)
 161    }
 162
 163    fn confirm(
 164        &self,
 165        remote_modal: &mut RemoteServerProjects,
 166        cx: &mut ViewContext<RemoteServerProjects>,
 167    ) {
 168        if let Some(active_item) = self.active_item.and_then(|ix| self.items.get(ix)) {
 169            active_item(remote_modal, cx);
 170        }
 171    }
 172}
 173
 174impl FocusableView for ProjectPicker {
 175    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 176        self.picker.focus_handle(cx)
 177    }
 178}
 179
 180impl ProjectPicker {
 181    fn new(
 182        ix: usize,
 183        connection: SshConnectionOptions,
 184        project: Model<Project>,
 185        workspace: WeakView<Workspace>,
 186        cx: &mut ViewContext<RemoteServerProjects>,
 187    ) -> View<Self> {
 188        let (tx, rx) = oneshot::channel();
 189        let lister = project::DirectoryLister::Project(project.clone());
 190        let query = lister.default_query(cx);
 191        let delegate = file_finder::OpenPathDelegate::new(tx, lister);
 192
 193        let picker = cx.new_view(|cx| {
 194            let picker = Picker::uniform_list(delegate, cx)
 195                .width(rems(34.))
 196                .modal(false);
 197            picker.set_query(query, cx);
 198            picker
 199        });
 200        let connection_string = connection.connection_string().into();
 201        let nickname = connection.nickname.clone().map(|nick| nick.into());
 202        let _path_task = cx
 203            .spawn({
 204                let workspace = workspace.clone();
 205                move |this, mut cx| async move {
 206                    let Ok(Some(paths)) = rx.await else {
 207                        workspace
 208                            .update(&mut cx, |workspace, cx| {
 209                                let weak = cx.view().downgrade();
 210                                workspace
 211                                    .toggle_modal(cx, |cx| RemoteServerProjects::new(cx, weak));
 212                            })
 213                            .log_err()?;
 214                        return None;
 215                    };
 216
 217                    let app_state = workspace
 218                        .update(&mut cx, |workspace, _| workspace.app_state().clone())
 219                        .ok()?;
 220                    let options = cx
 221                        .update(|cx| (app_state.build_window_options)(None, cx))
 222                        .log_err()?;
 223
 224                    cx.open_window(options, |cx| {
 225                        cx.activate_window();
 226
 227                        let fs = app_state.fs.clone();
 228                        update_settings_file::<SshSettings>(fs, cx, {
 229                            let paths = paths
 230                                .iter()
 231                                .map(|path| path.to_string_lossy().to_string())
 232                                .collect();
 233                            move |setting, _| {
 234                                if let Some(server) = setting
 235                                    .ssh_connections
 236                                    .as_mut()
 237                                    .and_then(|connections| connections.get_mut(ix))
 238                                {
 239                                    server.projects.push(SshProject { paths })
 240                                }
 241                            }
 242                        });
 243
 244                        let tasks = paths
 245                            .into_iter()
 246                            .map(|path| {
 247                                project.update(cx, |project, cx| {
 248                                    project.find_or_create_worktree(&path, true, cx)
 249                                })
 250                            })
 251                            .collect::<Vec<_>>();
 252                        cx.spawn(|_| async move {
 253                            for task in tasks {
 254                                task.await?;
 255                            }
 256                            Ok(())
 257                        })
 258                        .detach_and_prompt_err(
 259                            "Failed to open path",
 260                            cx,
 261                            |_, _| None,
 262                        );
 263
 264                        cx.new_view(|cx| {
 265                            let workspace =
 266                                Workspace::new(None, project.clone(), app_state.clone(), cx);
 267
 268                            workspace
 269                                .client()
 270                                .telemetry()
 271                                .report_app_event("create ssh project".to_string());
 272
 273                            workspace
 274                        })
 275                    })
 276                    .log_err();
 277                    this.update(&mut cx, |_, cx| {
 278                        cx.emit(DismissEvent);
 279                    })
 280                    .ok();
 281                    Some(())
 282                }
 283            })
 284            .shared();
 285        cx.new_view(|_| Self {
 286            _path_task,
 287            picker,
 288            connection_string,
 289            nickname,
 290        })
 291    }
 292}
 293
 294impl gpui::Render for ProjectPicker {
 295    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 296        v_flex()
 297            .child(
 298                SshConnectionHeader {
 299                    connection_string: self.connection_string.clone(),
 300                    paths: Default::default(),
 301                    nickname: self.nickname.clone(),
 302                }
 303                .render(cx),
 304            )
 305            .child(
 306                div()
 307                    .border_t_1()
 308                    .border_color(cx.theme().colors().border_variant)
 309                    .child(self.picker.clone()),
 310            )
 311    }
 312}
 313enum Mode {
 314    Default(ScrollbarState),
 315    ViewServerOptions(usize, SshConnection),
 316    EditNickname(EditNicknameState),
 317    ProjectPicker(View<ProjectPicker>),
 318    CreateRemoteServer(CreateRemoteServer),
 319}
 320
 321impl Mode {
 322    fn default_mode() -> Self {
 323        let handle = ScrollHandle::new();
 324        Self::Default(ScrollbarState::new(handle))
 325    }
 326}
 327impl RemoteServerProjects {
 328    pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 329        workspace.register_action(|workspace, _: &OpenRemote, cx| {
 330            let handle = cx.view().downgrade();
 331            workspace.toggle_modal(cx, |cx| Self::new(cx, handle))
 332        });
 333    }
 334
 335    pub fn open(workspace: View<Workspace>, cx: &mut WindowContext) {
 336        workspace.update(cx, |workspace, cx| {
 337            let handle = cx.view().downgrade();
 338            workspace.toggle_modal(cx, |cx| Self::new(cx, handle))
 339        })
 340    }
 341
 342    pub fn new(cx: &mut ViewContext<Self>, workspace: WeakView<Workspace>) -> Self {
 343        let focus_handle = cx.focus_handle();
 344
 345        let mut base_style = cx.text_style();
 346        base_style.refine(&gpui::TextStyleRefinement {
 347            color: Some(cx.theme().colors().editor_foreground),
 348            ..Default::default()
 349        });
 350
 351        Self {
 352            mode: Mode::default_mode(),
 353            focus_handle,
 354            scroll_handle: ScrollHandle::new(),
 355            workspace,
 356            selectable_items: Default::default(),
 357            retained_connections: Vec::new(),
 358        }
 359    }
 360
 361    fn next_item(&mut self, _: &menu::SelectNext, cx: &mut ViewContext<Self>) {
 362        if !matches!(self.mode, Mode::Default(_) | Mode::ViewServerOptions(_, _)) {
 363            return;
 364        }
 365
 366        self.selectable_items.next(cx);
 367    }
 368
 369    fn prev_item(&mut self, _: &menu::SelectPrev, cx: &mut ViewContext<Self>) {
 370        if !matches!(self.mode, Mode::Default(_) | Mode::ViewServerOptions(_, _)) {
 371            return;
 372        }
 373        self.selectable_items.prev(cx);
 374    }
 375
 376    pub fn project_picker(
 377        ix: usize,
 378        connection_options: remote::SshConnectionOptions,
 379        project: Model<Project>,
 380        cx: &mut ViewContext<Self>,
 381        workspace: WeakView<Workspace>,
 382    ) -> Self {
 383        let mut this = Self::new(cx, workspace.clone());
 384        this.mode = Mode::ProjectPicker(ProjectPicker::new(
 385            ix,
 386            connection_options,
 387            project,
 388            workspace,
 389            cx,
 390        ));
 391        cx.notify();
 392
 393        this
 394    }
 395
 396    fn create_ssh_server(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
 397        let input = get_text(&editor, cx);
 398        if input.is_empty() {
 399            return;
 400        }
 401
 402        let connection_options = match SshConnectionOptions::parse_command_line(&input) {
 403            Ok(c) => c,
 404            Err(e) => {
 405                self.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 406                    address_editor: editor,
 407                    address_error: Some(format!("could not parse: {:?}", e).into()),
 408                    ssh_prompt: None,
 409                    _creating: None,
 410                });
 411                return;
 412            }
 413        };
 414        let ssh_prompt = cx.new_view(|cx| SshPrompt::new(&connection_options, cx));
 415
 416        let connection = connect_over_ssh(
 417            ConnectionIdentifier::Setup,
 418            connection_options.clone(),
 419            ssh_prompt.clone(),
 420            cx,
 421        )
 422        .prompt_err("Failed to connect", cx, |_, _| None);
 423
 424        let address_editor = editor.clone();
 425        let creating = cx.spawn(move |this, mut cx| async move {
 426            match connection.await {
 427                Some(Some(client)) => this
 428                    .update(&mut cx, |this, cx| {
 429                        let _ = this.workspace.update(cx, |workspace, _| {
 430                            workspace
 431                                .client()
 432                                .telemetry()
 433                                .report_app_event("create ssh server".to_string())
 434                        });
 435                        this.retained_connections.push(client);
 436                        this.add_ssh_server(connection_options, cx);
 437                        this.mode = Mode::default_mode();
 438                        this.selectable_items.reset_selection();
 439                        cx.notify()
 440                    })
 441                    .log_err(),
 442                _ => this
 443                    .update(&mut cx, |this, cx| {
 444                        address_editor.update(cx, |this, _| {
 445                            this.set_read_only(false);
 446                        });
 447                        this.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 448                            address_editor,
 449                            address_error: None,
 450                            ssh_prompt: None,
 451                            _creating: None,
 452                        });
 453                        cx.notify()
 454                    })
 455                    .log_err(),
 456            };
 457            None
 458        });
 459
 460        editor.update(cx, |this, _| {
 461            this.set_read_only(true);
 462        });
 463        self.mode = Mode::CreateRemoteServer(CreateRemoteServer {
 464            address_editor: editor,
 465            address_error: None,
 466            ssh_prompt: Some(ssh_prompt.clone()),
 467            _creating: Some(creating),
 468        });
 469    }
 470
 471    fn view_server_options(
 472        &mut self,
 473        (index, connection): (usize, SshConnection),
 474        cx: &mut ViewContext<Self>,
 475    ) {
 476        self.selectable_items.reset_selection();
 477        self.mode = Mode::ViewServerOptions(index, connection);
 478        cx.notify();
 479    }
 480
 481    fn create_ssh_project(
 482        &mut self,
 483        ix: usize,
 484        ssh_connection: SshConnection,
 485        cx: &mut ViewContext<Self>,
 486    ) {
 487        let Some(workspace) = self.workspace.upgrade() else {
 488            return;
 489        };
 490
 491        let connection_options = ssh_connection.into();
 492        workspace.update(cx, |_, cx| {
 493            cx.defer(move |workspace, cx| {
 494                workspace.toggle_modal(cx, |cx| {
 495                    SshConnectionModal::new(&connection_options, Vec::new(), cx)
 496                });
 497                let prompt = workspace
 498                    .active_modal::<SshConnectionModal>(cx)
 499                    .unwrap()
 500                    .read(cx)
 501                    .prompt
 502                    .clone();
 503
 504                let connect = connect_over_ssh(
 505                    ConnectionIdentifier::Setup,
 506                    connection_options.clone(),
 507                    prompt,
 508                    cx,
 509                )
 510                .prompt_err("Failed to connect", cx, |_, _| None);
 511
 512                cx.spawn(move |workspace, mut cx| async move {
 513                    let session = connect.await;
 514
 515                    workspace
 516                        .update(&mut cx, |workspace, cx| {
 517                            if let Some(prompt) = workspace.active_modal::<SshConnectionModal>(cx) {
 518                                prompt.update(cx, |prompt, cx| prompt.finished(cx))
 519                            }
 520                        })
 521                        .ok();
 522
 523                    let Some(Some(session)) = session else {
 524                        workspace
 525                            .update(&mut cx, |workspace, cx| {
 526                                let weak = cx.view().downgrade();
 527                                workspace
 528                                    .toggle_modal(cx, |cx| RemoteServerProjects::new(cx, weak));
 529                            })
 530                            .log_err();
 531                        return;
 532                    };
 533
 534                    workspace
 535                        .update(&mut cx, |workspace, cx| {
 536                            let app_state = workspace.app_state().clone();
 537                            let weak = cx.view().downgrade();
 538                            let project = project::Project::ssh(
 539                                session,
 540                                app_state.client.clone(),
 541                                app_state.node_runtime.clone(),
 542                                app_state.user_store.clone(),
 543                                app_state.languages.clone(),
 544                                app_state.fs.clone(),
 545                                cx,
 546                            );
 547                            workspace.toggle_modal(cx, |cx| {
 548                                RemoteServerProjects::project_picker(
 549                                    ix,
 550                                    connection_options,
 551                                    project,
 552                                    cx,
 553                                    weak,
 554                                )
 555                            });
 556                        })
 557                        .ok();
 558                })
 559                .detach()
 560            })
 561        })
 562    }
 563
 564    fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
 565        match &self.mode {
 566            Mode::Default(_) | Mode::ViewServerOptions(_, _) => {
 567                let items = std::mem::take(&mut self.selectable_items);
 568                items.confirm(self, cx);
 569                self.selectable_items = items;
 570            }
 571            Mode::ProjectPicker(_) => {}
 572            Mode::CreateRemoteServer(state) => {
 573                if let Some(prompt) = state.ssh_prompt.as_ref() {
 574                    prompt.update(cx, |prompt, cx| {
 575                        prompt.confirm(cx);
 576                    });
 577                    return;
 578                }
 579
 580                self.create_ssh_server(state.address_editor.clone(), cx);
 581            }
 582            Mode::EditNickname(state) => {
 583                let text = Some(state.editor.read(cx).text(cx)).filter(|text| !text.is_empty());
 584                let index = state.index;
 585                self.update_settings_file(cx, move |setting, _| {
 586                    if let Some(connections) = setting.ssh_connections.as_mut() {
 587                        if let Some(connection) = connections.get_mut(index) {
 588                            connection.nickname = text;
 589                        }
 590                    }
 591                });
 592                self.mode = Mode::default_mode();
 593                self.selectable_items.reset_selection();
 594                self.focus_handle.focus(cx);
 595            }
 596        }
 597    }
 598
 599    fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
 600        match &self.mode {
 601            Mode::Default(_) => cx.emit(DismissEvent),
 602            Mode::CreateRemoteServer(state) if state.ssh_prompt.is_some() => {
 603                let new_state = CreateRemoteServer::new(cx);
 604                let old_prompt = state.address_editor.read(cx).text(cx);
 605                new_state.address_editor.update(cx, |this, cx| {
 606                    this.set_text(old_prompt, cx);
 607                });
 608
 609                self.mode = Mode::CreateRemoteServer(new_state);
 610                self.selectable_items.reset_selection();
 611                cx.notify();
 612            }
 613            _ => {
 614                self.mode = Mode::default_mode();
 615                self.selectable_items.reset_selection();
 616                self.focus_handle(cx).focus(cx);
 617                cx.notify();
 618            }
 619        }
 620    }
 621
 622    fn render_ssh_connection(
 623        &mut self,
 624        ix: usize,
 625        ssh_connection: SshConnection,
 626        cx: &mut ViewContext<Self>,
 627    ) -> impl IntoElement {
 628        let (main_label, aux_label) = if let Some(nickname) = ssh_connection.nickname.clone() {
 629            let aux_label = SharedString::from(format!("({})", ssh_connection.host));
 630            (nickname.into(), Some(aux_label))
 631        } else {
 632            (ssh_connection.host.clone(), None)
 633        };
 634        v_flex()
 635            .w_full()
 636            .child(ListSeparator)
 637            .child(
 638                h_flex()
 639                    .group("ssh-server")
 640                    .w_full()
 641                    .pt_0p5()
 642                    .px_3()
 643                    .gap_1()
 644                    .overflow_hidden()
 645                    .child(
 646                        div().max_w_96().overflow_hidden().text_ellipsis().child(
 647                            Label::new(main_label)
 648                                .size(LabelSize::Small)
 649                                .color(Color::Muted),
 650                        ),
 651                    )
 652                    .children(
 653                        aux_label.map(|label| {
 654                            Label::new(label).size(LabelSize::Small).color(Color::Muted)
 655                        }),
 656                    ),
 657            )
 658            .child(
 659                List::new()
 660                    .empty_message("No projects.")
 661                    .children(ssh_connection.projects.iter().enumerate().map(|(pix, p)| {
 662                        v_flex().gap_0p5().child(self.render_ssh_project(
 663                            ix,
 664                            &ssh_connection,
 665                            pix,
 666                            p,
 667                            cx,
 668                        ))
 669                    }))
 670                    .child(h_flex().map(|this| {
 671                        self.selectable_items.add_item(Box::new({
 672                            let ssh_connection = ssh_connection.clone();
 673                            move |this, cx| {
 674                                this.create_ssh_project(ix, ssh_connection.clone(), cx);
 675                            }
 676                        }));
 677                        let is_selected = self.selectable_items.is_selected();
 678                        this.child(
 679                            ListItem::new(("new-remote-project", ix))
 680                                .selected(is_selected)
 681                                .inset(true)
 682                                .spacing(ui::ListItemSpacing::Sparse)
 683                                .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
 684                                .child(Label::new("Open Folder"))
 685                                .on_click(cx.listener({
 686                                    let ssh_connection = ssh_connection.clone();
 687                                    move |this, _, cx| {
 688                                        this.create_ssh_project(ix, ssh_connection.clone(), cx);
 689                                    }
 690                                })),
 691                        )
 692                    }))
 693                    .child(h_flex().map(|this| {
 694                        self.selectable_items.add_item(Box::new({
 695                            let ssh_connection = ssh_connection.clone();
 696                            move |this, cx| {
 697                                this.view_server_options((ix, ssh_connection.clone()), cx);
 698                            }
 699                        }));
 700                        let is_selected = self.selectable_items.is_selected();
 701                        this.child(
 702                            ListItem::new(("server-options", ix))
 703                                .selected(is_selected)
 704                                .inset(true)
 705                                .spacing(ui::ListItemSpacing::Sparse)
 706                                .start_slot(Icon::new(IconName::Settings).color(Color::Muted))
 707                                .child(Label::new("View Server Options"))
 708                                .on_click(cx.listener({
 709                                    let ssh_connection = ssh_connection.clone();
 710                                    move |this, _, cx| {
 711                                        this.view_server_options((ix, ssh_connection.clone()), cx);
 712                                    }
 713                                })),
 714                        )
 715                    })),
 716            )
 717    }
 718
 719    fn render_ssh_project(
 720        &mut self,
 721        server_ix: usize,
 722        server: &SshConnection,
 723        ix: usize,
 724        project: &SshProject,
 725        cx: &ViewContext<Self>,
 726    ) -> impl IntoElement {
 727        let server = server.clone();
 728
 729        let element_id_base = SharedString::from(format!("remote-project-{server_ix}"));
 730        let callback = Arc::new({
 731            let project = project.clone();
 732            move |this: &mut Self, cx: &mut ViewContext<Self>| {
 733                let Some(app_state) = this
 734                    .workspace
 735                    .update(cx, |workspace, _| workspace.app_state().clone())
 736                    .log_err()
 737                else {
 738                    return;
 739                };
 740                let project = project.clone();
 741                let server = server.clone();
 742                cx.emit(DismissEvent);
 743                cx.spawn(|_, mut cx| async move {
 744                    let result = open_ssh_project(
 745                        server.into(),
 746                        project.paths.into_iter().map(PathBuf::from).collect(),
 747                        app_state,
 748                        OpenOptions::default(),
 749                        &mut cx,
 750                    )
 751                    .await;
 752                    if let Err(e) = result {
 753                        log::error!("Failed to connect: {:?}", e);
 754                        cx.prompt(
 755                            gpui::PromptLevel::Critical,
 756                            "Failed to connect",
 757                            Some(&e.to_string()),
 758                            &["Ok"],
 759                        )
 760                        .await
 761                        .ok();
 762                    }
 763                })
 764                .detach();
 765            }
 766        });
 767        self.selectable_items.add_item(Box::new({
 768            let callback = callback.clone();
 769            move |this, cx| callback(this, cx)
 770        }));
 771        let is_selected = self.selectable_items.is_selected();
 772
 773        ListItem::new((element_id_base, ix))
 774            .inset(true)
 775            .selected(is_selected)
 776            .spacing(ui::ListItemSpacing::Sparse)
 777            .start_slot(
 778                Icon::new(IconName::Folder)
 779                    .color(Color::Muted)
 780                    .size(IconSize::Small),
 781            )
 782            .child(Label::new(project.paths.join(", ")))
 783            .on_click(cx.listener(move |this, _, cx| callback(this, cx)))
 784            .end_hover_slot::<AnyElement>(Some(
 785                div()
 786                    .mr_2()
 787                    .child(
 788                        // Right-margin to offset it from the Scrollbar
 789                        IconButton::new("remove-remote-project", IconName::TrashAlt)
 790                            .icon_size(IconSize::Small)
 791                            .shape(IconButtonShape::Square)
 792                            .size(ButtonSize::Large)
 793                            .tooltip(|cx| Tooltip::text("Delete Remote Project", cx))
 794                            .on_click(cx.listener(move |this, _, cx| {
 795                                this.delete_ssh_project(server_ix, ix, cx)
 796                            })),
 797                    )
 798                    .into_any_element(),
 799            ))
 800    }
 801
 802    fn update_settings_file(
 803        &mut self,
 804        cx: &mut ViewContext<Self>,
 805        f: impl FnOnce(&mut RemoteSettingsContent, &AppContext) + Send + Sync + 'static,
 806    ) {
 807        let Some(fs) = self
 808            .workspace
 809            .update(cx, |workspace, _| workspace.app_state().fs.clone())
 810            .log_err()
 811        else {
 812            return;
 813        };
 814        update_settings_file::<SshSettings>(fs, cx, move |setting, cx| f(setting, cx));
 815    }
 816
 817    fn delete_ssh_server(&mut self, server: usize, cx: &mut ViewContext<Self>) {
 818        self.update_settings_file(cx, move |setting, _| {
 819            if let Some(connections) = setting.ssh_connections.as_mut() {
 820                connections.remove(server);
 821            }
 822        });
 823    }
 824
 825    fn delete_ssh_project(&mut self, server: usize, project: usize, cx: &mut ViewContext<Self>) {
 826        self.update_settings_file(cx, move |setting, _| {
 827            if let Some(server) = setting
 828                .ssh_connections
 829                .as_mut()
 830                .and_then(|connections| connections.get_mut(server))
 831            {
 832                server.projects.remove(project);
 833            }
 834        });
 835    }
 836
 837    fn add_ssh_server(
 838        &mut self,
 839        connection_options: remote::SshConnectionOptions,
 840        cx: &mut ViewContext<Self>,
 841    ) {
 842        self.update_settings_file(cx, move |setting, _| {
 843            setting
 844                .ssh_connections
 845                .get_or_insert(Default::default())
 846                .push(SshConnection {
 847                    host: SharedString::from(connection_options.host),
 848                    username: connection_options.username,
 849                    port: connection_options.port,
 850                    projects: vec![],
 851                    nickname: None,
 852                    args: connection_options.args.unwrap_or_default(),
 853                    upload_binary_over_ssh: None,
 854                })
 855        });
 856    }
 857
 858    fn render_create_remote_server(
 859        &self,
 860        state: &CreateRemoteServer,
 861        cx: &mut ViewContext<Self>,
 862    ) -> impl IntoElement {
 863        let ssh_prompt = state.ssh_prompt.clone();
 864
 865        state.address_editor.update(cx, |editor, cx| {
 866            if editor.text(cx).is_empty() {
 867                editor.set_placeholder_text("ssh user@example -p 2222", cx);
 868            }
 869        });
 870
 871        let theme = cx.theme();
 872
 873        v_flex()
 874            .id("create-remote-server")
 875            .overflow_hidden()
 876            .size_full()
 877            .flex_1()
 878            .child(
 879                div()
 880                    .p_2()
 881                    .border_b_1()
 882                    .border_color(theme.colors().border_variant)
 883                    .child(state.address_editor.clone()),
 884            )
 885            .child(
 886                h_flex()
 887                    .bg(theme.colors().editor_background)
 888                    .rounded_b_md()
 889                    .w_full()
 890                    .map(|this| {
 891                        if let Some(ssh_prompt) = ssh_prompt {
 892                            this.child(h_flex().w_full().child(ssh_prompt))
 893                        } else if let Some(address_error) = &state.address_error {
 894                            this.child(
 895                                h_flex().p_2().w_full().gap_2().child(
 896                                    Label::new(address_error.clone())
 897                                        .size(LabelSize::Small)
 898                                        .color(Color::Error),
 899                                ),
 900                            )
 901                        } else {
 902                            this.child(
 903                                h_flex()
 904                                    .p_2()
 905                                    .w_full()
 906                                    .gap_1()
 907                                    .child(
 908                                        Label::new(
 909                                            "Enter the command you use to SSH into this server.",
 910                                        )
 911                                        .color(Color::Muted)
 912                                        .size(LabelSize::Small),
 913                                    )
 914                                    .child(
 915                                        Button::new("learn-more", "Learn more…")
 916                                            .label_size(LabelSize::Small)
 917                                            .size(ButtonSize::None)
 918                                            .color(Color::Accent)
 919                                            .style(ButtonStyle::Transparent)
 920                                            .on_click(|_, cx| {
 921                                                cx.open_url(
 922                                                    "https://zed.dev/docs/remote-development",
 923                                                );
 924                                            }),
 925                                    ),
 926                            )
 927                        }
 928                    }),
 929            )
 930    }
 931
 932    fn render_view_options(
 933        &mut self,
 934        index: usize,
 935        connection: SshConnection,
 936        cx: &mut ViewContext<Self>,
 937    ) -> impl IntoElement {
 938        let connection_string = connection.host.clone();
 939
 940        div()
 941            .size_full()
 942            .child(
 943                SshConnectionHeader {
 944                    connection_string: connection_string.clone(),
 945                    paths: Default::default(),
 946                    nickname: connection.nickname.clone().map(|s| s.into()),
 947                }
 948                .render(cx),
 949            )
 950            .child(
 951                v_flex()
 952                    .pb_1()
 953                    .child(ListSeparator)
 954                    .child({
 955                        self.selectable_items.add_item(Box::new({
 956                            move |this, cx| {
 957                                this.mode = Mode::EditNickname(EditNicknameState::new(index, cx));
 958                                cx.notify();
 959                            }
 960                        }));
 961                        let is_selected = self.selectable_items.is_selected();
 962                        let label = if connection.nickname.is_some() {
 963                            "Edit Nickname"
 964                        } else {
 965                            "Add Nickname to Server"
 966                        };
 967                        ListItem::new("add-nickname")
 968                            .selected(is_selected)
 969                            .inset(true)
 970                            .spacing(ui::ListItemSpacing::Sparse)
 971                            .start_slot(Icon::new(IconName::Pencil).color(Color::Muted))
 972                            .child(Label::new(label))
 973                            .on_click(cx.listener(move |this, _, cx| {
 974                                this.mode = Mode::EditNickname(EditNicknameState::new(index, cx));
 975                                cx.notify();
 976                            }))
 977                    })
 978                    .child({
 979                        let workspace = self.workspace.clone();
 980                        fn callback(
 981                            workspace: WeakView<Workspace>,
 982                            connection_string: SharedString,
 983                            cx: &mut WindowContext<'_>,
 984                        ) {
 985                            cx.write_to_clipboard(ClipboardItem::new_string(
 986                                connection_string.to_string(),
 987                            ));
 988                            workspace
 989                                .update(cx, |this, cx| {
 990                                    struct SshServerAddressCopiedToClipboard;
 991                                    let notification = format!(
 992                                        "Copied server address ({}) to clipboard",
 993                                        connection_string
 994                                    );
 995
 996                                    this.show_toast(
 997                                        Toast::new(
 998                                            NotificationId::composite::<
 999                                                SshServerAddressCopiedToClipboard,
1000                                            >(
1001                                                connection_string.clone()
1002                                            ),
1003                                            notification,
1004                                        )
1005                                        .autohide(),
1006                                        cx,
1007                                    );
1008                                })
1009                                .ok();
1010                        }
1011                        self.selectable_items.add_item(Box::new({
1012                            let workspace = workspace.clone();
1013                            let connection_string = connection_string.clone();
1014                            move |_, cx| {
1015                                callback(workspace.clone(), connection_string.clone(), cx);
1016                            }
1017                        }));
1018                        let is_selected = self.selectable_items.is_selected();
1019                        ListItem::new("copy-server-address")
1020                            .selected(is_selected)
1021                            .inset(true)
1022                            .spacing(ui::ListItemSpacing::Sparse)
1023                            .start_slot(Icon::new(IconName::Copy).color(Color::Muted))
1024                            .child(Label::new("Copy Server Address"))
1025                            .end_hover_slot(
1026                                Label::new(connection_string.clone()).color(Color::Muted),
1027                            )
1028                            .on_click({
1029                                let connection_string = connection_string.clone();
1030                                move |_, cx| {
1031                                    callback(workspace.clone(), connection_string.clone(), cx);
1032                                }
1033                            })
1034                    })
1035                    .child({
1036                        fn remove_ssh_server(
1037                            remote_servers: View<RemoteServerProjects>,
1038                            index: usize,
1039                            connection_string: SharedString,
1040                            cx: &mut WindowContext<'_>,
1041                        ) {
1042                            let prompt_message = format!("Remove server `{}`?", connection_string);
1043
1044                            let confirmation = cx.prompt(
1045                                PromptLevel::Warning,
1046                                &prompt_message,
1047                                None,
1048                                &["Yes, remove it", "No, keep it"],
1049                            );
1050
1051                            cx.spawn(|mut cx| async move {
1052                                if confirmation.await.ok() == Some(0) {
1053                                    remote_servers
1054                                        .update(&mut cx, |this, cx| {
1055                                            this.delete_ssh_server(index, cx);
1056                                            this.mode = Mode::default_mode();
1057                                            cx.notify();
1058                                        })
1059                                        .ok();
1060                                }
1061                                anyhow::Ok(())
1062                            })
1063                            .detach_and_log_err(cx);
1064                        }
1065                        self.selectable_items.add_item(Box::new({
1066                            let connection_string = connection_string.clone();
1067                            move |_, cx| {
1068                                remove_ssh_server(
1069                                    cx.view().clone(),
1070                                    index,
1071                                    connection_string.clone(),
1072                                    cx,
1073                                );
1074                            }
1075                        }));
1076                        let is_selected = self.selectable_items.is_selected();
1077                        ListItem::new("remove-server")
1078                            .selected(is_selected)
1079                            .inset(true)
1080                            .spacing(ui::ListItemSpacing::Sparse)
1081                            .start_slot(Icon::new(IconName::Trash).color(Color::Error))
1082                            .child(Label::new("Remove Server").color(Color::Error))
1083                            .on_click(cx.listener(move |_, _, cx| {
1084                                remove_ssh_server(
1085                                    cx.view().clone(),
1086                                    index,
1087                                    connection_string.clone(),
1088                                    cx,
1089                                );
1090                            }))
1091                    })
1092                    .child(ListSeparator)
1093                    .child({
1094                        self.selectable_items.add_item(Box::new({
1095                            move |this, cx| {
1096                                this.mode = Mode::default_mode();
1097                                cx.notify();
1098                            }
1099                        }));
1100                        let is_selected = self.selectable_items.is_selected();
1101                        ListItem::new("go-back")
1102                            .selected(is_selected)
1103                            .inset(true)
1104                            .spacing(ui::ListItemSpacing::Sparse)
1105                            .start_slot(Icon::new(IconName::ArrowLeft).color(Color::Muted))
1106                            .child(Label::new("Go Back"))
1107                            .on_click(cx.listener(|this, _, cx| {
1108                                this.mode = Mode::default_mode();
1109                                cx.notify()
1110                            }))
1111                    }),
1112            )
1113    }
1114
1115    fn render_edit_nickname(
1116        &self,
1117        state: &EditNicknameState,
1118        cx: &mut ViewContext<Self>,
1119    ) -> impl IntoElement {
1120        let Some(connection) = SshSettings::get_global(cx)
1121            .ssh_connections()
1122            .nth(state.index)
1123        else {
1124            return v_flex();
1125        };
1126
1127        let connection_string = connection.host.clone();
1128        let nickname = connection.nickname.clone().map(|s| s.into());
1129
1130        v_flex()
1131            .child(
1132                SshConnectionHeader {
1133                    connection_string,
1134                    paths: Default::default(),
1135                    nickname,
1136                }
1137                .render(cx),
1138            )
1139            .child(
1140                h_flex()
1141                    .p_2()
1142                    .border_t_1()
1143                    .border_color(cx.theme().colors().border_variant)
1144                    .child(state.editor.clone()),
1145            )
1146    }
1147
1148    fn render_default(
1149        &mut self,
1150        scroll_state: ScrollbarState,
1151        cx: &mut ViewContext<Self>,
1152    ) -> impl IntoElement {
1153        let scroll_state = scroll_state.parent_view(cx.view());
1154        let ssh_connections = SshSettings::get_global(cx)
1155            .ssh_connections()
1156            .collect::<Vec<_>>();
1157        self.selectable_items.add_item(Box::new(|this, cx| {
1158            this.mode = Mode::CreateRemoteServer(CreateRemoteServer::new(cx));
1159            cx.notify();
1160        }));
1161
1162        let is_selected = self.selectable_items.is_selected();
1163
1164        let connect_button = ListItem::new("register-remove-server-button")
1165            .selected(is_selected)
1166            .inset(true)
1167            .spacing(ui::ListItemSpacing::Sparse)
1168            .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
1169            .child(Label::new("Connect New Server"))
1170            .on_click(cx.listener(|this, _, cx| {
1171                let state = CreateRemoteServer::new(cx);
1172                this.mode = Mode::CreateRemoteServer(state);
1173
1174                cx.notify();
1175            }));
1176
1177        let ui::ScrollableHandle::NonUniform(scroll_handle) = scroll_state.scroll_handle() else {
1178            unreachable!()
1179        };
1180
1181        let mut modal_section = v_flex()
1182            .id("ssh-server-list")
1183            .overflow_y_scroll()
1184            .track_scroll(&scroll_handle)
1185            .size_full()
1186            .child(connect_button)
1187            .child(
1188                List::new()
1189                    .empty_message(
1190                        v_flex()
1191                            .child(div().px_3().child(
1192                                Label::new("No remote servers registered yet.").color(Color::Muted),
1193                            ))
1194                            .into_any_element(),
1195                    )
1196                    .children(ssh_connections.iter().cloned().enumerate().map(
1197                        |(ix, connection)| {
1198                            self.render_ssh_connection(ix, connection, cx)
1199                                .into_any_element()
1200                        },
1201                    )),
1202            )
1203            .into_any_element();
1204
1205        Modal::new("remote-projects", Some(self.scroll_handle.clone()))
1206            .header(
1207                ModalHeader::new()
1208                    .child(Headline::new("Remote Projects (beta)").size(HeadlineSize::XSmall)),
1209            )
1210            .section(
1211                Section::new().padded(false).child(
1212                    v_flex()
1213                        .min_h(rems(20.))
1214                        .size_full()
1215                        .relative()
1216                        .child(ListSeparator)
1217                        .child(
1218                            canvas(
1219                                |bounds, cx| {
1220                                    modal_section.prepaint_as_root(
1221                                        bounds.origin,
1222                                        bounds.size.into(),
1223                                        cx,
1224                                    );
1225                                    modal_section
1226                                },
1227                                |_, mut modal_section, cx| {
1228                                    modal_section.paint(cx);
1229                                },
1230                            )
1231                            .size_full(),
1232                        )
1233                        .child(
1234                            div()
1235                                .occlude()
1236                                .h_full()
1237                                .absolute()
1238                                .top_1()
1239                                .bottom_1()
1240                                .right_1()
1241                                .w(px(8.))
1242                                .children(Scrollbar::vertical(scroll_state)),
1243                        ),
1244                ),
1245            )
1246    }
1247}
1248
1249fn get_text(element: &View<Editor>, cx: &mut WindowContext) -> String {
1250    element.read(cx).text(cx).trim().to_string()
1251}
1252
1253impl ModalView for RemoteServerProjects {}
1254
1255impl FocusableView for RemoteServerProjects {
1256    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1257        match &self.mode {
1258            Mode::ProjectPicker(picker) => picker.focus_handle(cx),
1259            _ => self.focus_handle.clone(),
1260        }
1261    }
1262}
1263
1264impl EventEmitter<DismissEvent> for RemoteServerProjects {}
1265
1266impl Render for RemoteServerProjects {
1267    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1268        self.selectable_items.reset();
1269        div()
1270            .track_focus(&self.focus_handle(cx))
1271            .elevation_3(cx)
1272            .w(rems(34.))
1273            .key_context("RemoteServerModal")
1274            .on_action(cx.listener(Self::cancel))
1275            .on_action(cx.listener(Self::confirm))
1276            .on_action(cx.listener(Self::prev_item))
1277            .on_action(cx.listener(Self::next_item))
1278            .capture_any_mouse_down(cx.listener(|this, _, cx| {
1279                this.focus_handle(cx).focus(cx);
1280            }))
1281            .on_mouse_down_out(cx.listener(|this, _, cx| {
1282                if matches!(this.mode, Mode::Default(_)) {
1283                    cx.emit(DismissEvent)
1284                }
1285            }))
1286            .child(match &self.mode {
1287                Mode::Default(state) => self.render_default(state.clone(), cx).into_any_element(),
1288                Mode::ViewServerOptions(index, connection) => self
1289                    .render_view_options(*index, connection.clone(), cx)
1290                    .into_any_element(),
1291                Mode::ProjectPicker(element) => element.clone().into_any_element(),
1292                Mode::CreateRemoteServer(state) => self
1293                    .render_create_remote_server(state, cx)
1294                    .into_any_element(),
1295                Mode::EditNickname(state) => {
1296                    self.render_edit_nickname(state, cx).into_any_element()
1297                }
1298            })
1299    }
1300}