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 if let Some(connection) = connections.get_mut(index) {
669 connection.nickname = text;
670 }
671 }
672 });
673 self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
674 self.focus_handle.focus(window);
675 }
676 }
677 }
678
679 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
680 match &self.mode {
681 Mode::Default(_) => cx.emit(DismissEvent),
682 Mode::CreateRemoteServer(state) if state.ssh_prompt.is_some() => {
683 let new_state = CreateRemoteServer::new(window, cx);
684 let old_prompt = state.address_editor.read(cx).text(cx);
685 new_state.address_editor.update(cx, |this, cx| {
686 this.set_text(old_prompt, window, cx);
687 });
688
689 self.mode = Mode::CreateRemoteServer(new_state);
690 cx.notify();
691 }
692 _ => {
693 self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
694 self.focus_handle(cx).focus(window);
695 cx.notify();
696 }
697 }
698 }
699
700 fn render_ssh_connection(
701 &mut self,
702 ix: usize,
703 ssh_server: RemoteEntry,
704 window: &mut Window,
705 cx: &mut Context<Self>,
706 ) -> impl IntoElement {
707 let connection = ssh_server.connection().into_owned();
708 let (main_label, aux_label) = if let Some(nickname) = connection.nickname.clone() {
709 let aux_label = SharedString::from(format!("({})", connection.host));
710 (nickname.into(), Some(aux_label))
711 } else {
712 (connection.host.clone(), None)
713 };
714 v_flex()
715 .w_full()
716 .child(ListSeparator)
717 .child(
718 h_flex()
719 .group("ssh-server")
720 .w_full()
721 .pt_0p5()
722 .px_3()
723 .gap_1()
724 .overflow_hidden()
725 .child(
726 div().max_w_96().overflow_hidden().text_ellipsis().child(
727 Label::new(main_label)
728 .size(LabelSize::Small)
729 .color(Color::Muted),
730 ),
731 )
732 .children(
733 aux_label.map(|label| {
734 Label::new(label).size(LabelSize::Small).color(Color::Muted)
735 }),
736 ),
737 )
738 .child(match &ssh_server {
739 RemoteEntry::Project {
740 open_folder,
741 projects,
742 configure,
743 connection,
744 } => List::new()
745 .empty_message("No projects.")
746 .children(projects.iter().enumerate().map(|(pix, p)| {
747 v_flex().gap_0p5().child(self.render_ssh_project(
748 ix,
749 ssh_server.clone(),
750 pix,
751 p,
752 window,
753 cx,
754 ))
755 }))
756 .child(
757 h_flex()
758 .id(("new-remote-project-container", ix))
759 .track_focus(&open_folder.focus_handle)
760 .anchor_scroll(open_folder.scroll_anchor.clone())
761 .on_action(cx.listener({
762 let ssh_connection = connection.clone();
763 move |this, _: &menu::Confirm, window, cx| {
764 this.create_ssh_project(ix, ssh_connection.clone(), window, cx);
765 }
766 }))
767 .child(
768 ListItem::new(("new-remote-project", ix))
769 .toggle_state(
770 open_folder.focus_handle.contains_focused(window, cx),
771 )
772 .inset(true)
773 .spacing(ui::ListItemSpacing::Sparse)
774 .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
775 .child(Label::new("Open Folder"))
776 .on_click(cx.listener({
777 let ssh_connection = connection.clone();
778 move |this, _, window, cx| {
779 this.create_ssh_project(
780 ix,
781 ssh_connection.clone(),
782 window,
783 cx,
784 );
785 }
786 })),
787 ),
788 )
789 .child(
790 h_flex()
791 .id(("server-options-container", ix))
792 .track_focus(&configure.focus_handle)
793 .anchor_scroll(configure.scroll_anchor.clone())
794 .on_action(cx.listener({
795 let ssh_connection = connection.clone();
796 move |this, _: &menu::Confirm, window, cx| {
797 this.view_server_options(
798 (ix, ssh_connection.clone()),
799 window,
800 cx,
801 );
802 }
803 }))
804 .child(
805 ListItem::new(("server-options", ix))
806 .toggle_state(
807 configure.focus_handle.contains_focused(window, cx),
808 )
809 .inset(true)
810 .spacing(ui::ListItemSpacing::Sparse)
811 .start_slot(Icon::new(IconName::Settings).color(Color::Muted))
812 .child(Label::new("View Server Options"))
813 .on_click(cx.listener({
814 let ssh_connection = connection.clone();
815 move |this, _, window, cx| {
816 this.view_server_options(
817 (ix, ssh_connection.clone()),
818 window,
819 cx,
820 );
821 }
822 })),
823 ),
824 ),
825 RemoteEntry::SshConfig { open_folder, host } => List::new().child(
826 h_flex()
827 .id(("new-remote-project-container", ix))
828 .track_focus(&open_folder.focus_handle)
829 .anchor_scroll(open_folder.scroll_anchor.clone())
830 .on_action(cx.listener({
831 let ssh_connection = connection.clone();
832 let host = host.clone();
833 move |this, _: &menu::Confirm, window, cx| {
834 let new_ix = this.create_host_from_ssh_config(&host, cx);
835 this.create_ssh_project(new_ix, ssh_connection.clone(), window, cx);
836 }
837 }))
838 .child(
839 ListItem::new(("new-remote-project", ix))
840 .toggle_state(open_folder.focus_handle.contains_focused(window, cx))
841 .inset(true)
842 .spacing(ui::ListItemSpacing::Sparse)
843 .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
844 .child(Label::new("Open Folder"))
845 .on_click(cx.listener({
846 let ssh_connection = connection.clone();
847 let host = host.clone();
848 move |this, _, window, cx| {
849 let new_ix = this.create_host_from_ssh_config(&host, cx);
850 this.create_ssh_project(
851 new_ix,
852 ssh_connection.clone(),
853 window,
854 cx,
855 );
856 }
857 })),
858 ),
859 ),
860 })
861 }
862
863 fn render_ssh_project(
864 &mut self,
865 server_ix: usize,
866 server: RemoteEntry,
867 ix: usize,
868 (navigation, project): &(NavigableEntry, SshProject),
869 window: &mut Window,
870 cx: &mut Context<Self>,
871 ) -> impl IntoElement {
872 let create_new_window = self.create_new_window;
873 let is_from_zed = server.is_from_zed();
874 let element_id_base = SharedString::from(format!("remote-project-{server_ix}"));
875 let container_element_id_base =
876 SharedString::from(format!("remote-project-container-{element_id_base}"));
877
878 let callback = Rc::new({
879 let project = project.clone();
880 move |remote_server_projects: &mut Self,
881 secondary_confirm: bool,
882 window: &mut Window,
883 cx: &mut Context<Self>| {
884 let Some(app_state) = remote_server_projects
885 .workspace
886 .read_with(cx, |workspace, _| workspace.app_state().clone())
887 .log_err()
888 else {
889 return;
890 };
891 let project = project.clone();
892 let server = server.connection().into_owned();
893 cx.emit(DismissEvent);
894
895 let replace_window = match (create_new_window, secondary_confirm) {
896 (true, false) | (false, true) => None,
897 (true, true) | (false, false) => window.window_handle().downcast::<Workspace>(),
898 };
899
900 cx.spawn_in(window, async move |_, cx| {
901 let result = open_ssh_project(
902 server.into(),
903 project.paths.into_iter().map(PathBuf::from).collect(),
904 app_state,
905 OpenOptions {
906 replace_window,
907 ..OpenOptions::default()
908 },
909 cx,
910 )
911 .await;
912 if let Err(e) = result {
913 log::error!("Failed to connect: {e:#}");
914 cx.prompt(
915 gpui::PromptLevel::Critical,
916 "Failed to connect",
917 Some(&e.to_string()),
918 &["Ok"],
919 )
920 .await
921 .ok();
922 }
923 })
924 .detach();
925 }
926 });
927
928 div()
929 .id((container_element_id_base, ix))
930 .track_focus(&navigation.focus_handle)
931 .anchor_scroll(navigation.scroll_anchor.clone())
932 .on_action(cx.listener({
933 let callback = callback.clone();
934 move |this, _: &menu::Confirm, window, cx| {
935 callback(this, false, window, cx);
936 }
937 }))
938 .on_action(cx.listener({
939 let callback = callback.clone();
940 move |this, _: &menu::SecondaryConfirm, window, cx| {
941 callback(this, true, window, cx);
942 }
943 }))
944 .child(
945 ListItem::new((element_id_base, ix))
946 .toggle_state(navigation.focus_handle.contains_focused(window, cx))
947 .inset(true)
948 .spacing(ui::ListItemSpacing::Sparse)
949 .start_slot(
950 Icon::new(IconName::Folder)
951 .color(Color::Muted)
952 .size(IconSize::Small),
953 )
954 .child(Label::new(project.paths.join(", ")))
955 .on_click(cx.listener(move |this, e: &ClickEvent, window, cx| {
956 let secondary_confirm = e.modifiers().platform;
957 callback(this, secondary_confirm, window, cx)
958 }))
959 .when(is_from_zed, |server_list_item| {
960 server_list_item.end_hover_slot::<AnyElement>(Some(
961 div()
962 .mr_2()
963 .child({
964 let project = project.clone();
965 // Right-margin to offset it from the Scrollbar
966 IconButton::new("remove-remote-project", IconName::Trash)
967 .icon_size(IconSize::Small)
968 .shape(IconButtonShape::Square)
969 .size(ButtonSize::Large)
970 .tooltip(Tooltip::text("Delete Remote Project"))
971 .on_click(cx.listener(move |this, _, _, cx| {
972 this.delete_ssh_project(server_ix, &project, cx)
973 }))
974 })
975 .into_any_element(),
976 ))
977 }),
978 )
979 }
980
981 fn update_settings_file(
982 &mut self,
983 cx: &mut Context<Self>,
984 f: impl FnOnce(&mut RemoteSettingsContent, &App) + Send + Sync + 'static,
985 ) {
986 let Some(fs) = self
987 .workspace
988 .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
989 .log_err()
990 else {
991 return;
992 };
993 update_settings_file::<SshSettings>(fs, cx, move |setting, cx| f(setting, cx));
994 }
995
996 fn delete_ssh_server(&mut self, server: usize, cx: &mut Context<Self>) {
997 self.update_settings_file(cx, move |setting, _| {
998 if let Some(connections) = setting.ssh_connections.as_mut() {
999 connections.remove(server);
1000 }
1001 });
1002 }
1003
1004 fn delete_ssh_project(&mut self, server: usize, project: &SshProject, cx: &mut Context<Self>) {
1005 let project = project.clone();
1006 self.update_settings_file(cx, move |setting, _| {
1007 if let Some(server) = setting
1008 .ssh_connections
1009 .as_mut()
1010 .and_then(|connections| connections.get_mut(server))
1011 {
1012 server.projects.remove(&project);
1013 }
1014 });
1015 }
1016
1017 fn add_ssh_server(
1018 &mut self,
1019 connection_options: remote::SshConnectionOptions,
1020 cx: &mut Context<Self>,
1021 ) {
1022 self.update_settings_file(cx, move |setting, _| {
1023 setting
1024 .ssh_connections
1025 .get_or_insert(Default::default())
1026 .push(SshConnection {
1027 host: SharedString::from(connection_options.host),
1028 username: connection_options.username,
1029 port: connection_options.port,
1030 projects: BTreeSet::new(),
1031 nickname: None,
1032 args: connection_options.args.unwrap_or_default(),
1033 upload_binary_over_ssh: None,
1034 port_forwards: connection_options.port_forwards,
1035 })
1036 });
1037 }
1038
1039 fn render_create_remote_server(
1040 &self,
1041 state: &CreateRemoteServer,
1042 cx: &mut Context<Self>,
1043 ) -> impl IntoElement {
1044 let ssh_prompt = state.ssh_prompt.clone();
1045
1046 state.address_editor.update(cx, |editor, cx| {
1047 if editor.text(cx).is_empty() {
1048 editor.set_placeholder_text("ssh user@example -p 2222", cx);
1049 }
1050 });
1051
1052 let theme = cx.theme();
1053
1054 v_flex()
1055 .track_focus(&self.focus_handle(cx))
1056 .id("create-remote-server")
1057 .overflow_hidden()
1058 .size_full()
1059 .flex_1()
1060 .child(
1061 div()
1062 .p_2()
1063 .border_b_1()
1064 .border_color(theme.colors().border_variant)
1065 .child(state.address_editor.clone()),
1066 )
1067 .child(
1068 h_flex()
1069 .bg(theme.colors().editor_background)
1070 .rounded_b_sm()
1071 .w_full()
1072 .map(|this| {
1073 if let Some(ssh_prompt) = ssh_prompt {
1074 this.child(h_flex().w_full().child(ssh_prompt))
1075 } else if let Some(address_error) = &state.address_error {
1076 this.child(
1077 h_flex().p_2().w_full().gap_2().child(
1078 Label::new(address_error.clone())
1079 .size(LabelSize::Small)
1080 .color(Color::Error),
1081 ),
1082 )
1083 } else {
1084 this.child(
1085 h_flex()
1086 .p_2()
1087 .w_full()
1088 .gap_1()
1089 .child(
1090 Label::new(
1091 "Enter the command you use to SSH into this server.",
1092 )
1093 .color(Color::Muted)
1094 .size(LabelSize::Small),
1095 )
1096 .child(
1097 Button::new("learn-more", "Learn more…")
1098 .label_size(LabelSize::Small)
1099 .size(ButtonSize::None)
1100 .color(Color::Accent)
1101 .style(ButtonStyle::Transparent)
1102 .on_click(|_, _, cx| {
1103 cx.open_url(
1104 "https://zed.dev/docs/remote-development",
1105 );
1106 }),
1107 ),
1108 )
1109 }
1110 }),
1111 )
1112 }
1113
1114 fn render_view_options(
1115 &mut self,
1116 ViewServerOptionsState {
1117 server_index,
1118 connection,
1119 entries,
1120 }: ViewServerOptionsState,
1121 window: &mut Window,
1122 cx: &mut Context<Self>,
1123 ) -> impl IntoElement {
1124 let connection_string = connection.host.clone();
1125
1126 let mut view = Navigable::new(
1127 div()
1128 .track_focus(&self.focus_handle(cx))
1129 .size_full()
1130 .child(
1131 SshConnectionHeader {
1132 connection_string: connection_string.clone(),
1133 paths: Default::default(),
1134 nickname: connection.nickname.clone().map(|s| s.into()),
1135 }
1136 .render(window, cx),
1137 )
1138 .child(
1139 v_flex()
1140 .pb_1()
1141 .child(ListSeparator)
1142 .child({
1143 let label = if connection.nickname.is_some() {
1144 "Edit Nickname"
1145 } else {
1146 "Add Nickname to Server"
1147 };
1148 div()
1149 .id("ssh-options-add-nickname")
1150 .track_focus(&entries[0].focus_handle)
1151 .on_action(cx.listener(
1152 move |this, _: &menu::Confirm, window, cx| {
1153 this.mode = Mode::EditNickname(EditNicknameState::new(
1154 server_index,
1155 window,
1156 cx,
1157 ));
1158 cx.notify();
1159 },
1160 ))
1161 .child(
1162 ListItem::new("add-nickname")
1163 .toggle_state(
1164 entries[0].focus_handle.contains_focused(window, cx),
1165 )
1166 .inset(true)
1167 .spacing(ui::ListItemSpacing::Sparse)
1168 .start_slot(Icon::new(IconName::Pencil).color(Color::Muted))
1169 .child(Label::new(label))
1170 .on_click(cx.listener(move |this, _, window, cx| {
1171 this.mode = Mode::EditNickname(EditNicknameState::new(
1172 server_index,
1173 window,
1174 cx,
1175 ));
1176 cx.notify();
1177 })),
1178 )
1179 })
1180 .child({
1181 let workspace = self.workspace.clone();
1182 fn callback(
1183 workspace: WeakEntity<Workspace>,
1184 connection_string: SharedString,
1185 cx: &mut App,
1186 ) {
1187 cx.write_to_clipboard(ClipboardItem::new_string(
1188 connection_string.to_string(),
1189 ));
1190 workspace
1191 .update(cx, |this, cx| {
1192 struct SshServerAddressCopiedToClipboard;
1193 let notification = format!(
1194 "Copied server address ({}) to clipboard",
1195 connection_string
1196 );
1197
1198 this.show_toast(
1199 Toast::new(
1200 NotificationId::composite::<
1201 SshServerAddressCopiedToClipboard,
1202 >(
1203 connection_string.clone()
1204 ),
1205 notification,
1206 )
1207 .autohide(),
1208 cx,
1209 );
1210 })
1211 .ok();
1212 }
1213 div()
1214 .id("ssh-options-copy-server-address")
1215 .track_focus(&entries[1].focus_handle)
1216 .on_action({
1217 let connection_string = connection_string.clone();
1218 let workspace = self.workspace.clone();
1219 move |_: &menu::Confirm, _, cx| {
1220 callback(workspace.clone(), connection_string.clone(), cx);
1221 }
1222 })
1223 .child(
1224 ListItem::new("copy-server-address")
1225 .toggle_state(
1226 entries[1].focus_handle.contains_focused(window, cx),
1227 )
1228 .inset(true)
1229 .spacing(ui::ListItemSpacing::Sparse)
1230 .start_slot(Icon::new(IconName::Copy).color(Color::Muted))
1231 .child(Label::new("Copy Server Address"))
1232 .end_hover_slot(
1233 Label::new(connection_string.clone())
1234 .color(Color::Muted),
1235 )
1236 .on_click({
1237 let connection_string = connection_string.clone();
1238 move |_, _, cx| {
1239 callback(
1240 workspace.clone(),
1241 connection_string.clone(),
1242 cx,
1243 );
1244 }
1245 }),
1246 )
1247 })
1248 .child({
1249 fn remove_ssh_server(
1250 remote_servers: Entity<RemoteServerProjects>,
1251 index: usize,
1252 connection_string: SharedString,
1253 window: &mut Window,
1254 cx: &mut App,
1255 ) {
1256 let prompt_message =
1257 format!("Remove server `{}`?", connection_string);
1258
1259 let confirmation = window.prompt(
1260 PromptLevel::Warning,
1261 &prompt_message,
1262 None,
1263 &["Yes, remove it", "No, keep it"],
1264 cx,
1265 );
1266
1267 cx.spawn(async move |cx| {
1268 if confirmation.await.ok() == Some(0) {
1269 remote_servers
1270 .update(cx, |this, cx| {
1271 this.delete_ssh_server(index, cx);
1272 })
1273 .ok();
1274 remote_servers
1275 .update(cx, |this, cx| {
1276 this.mode = Mode::default_mode(
1277 &this.ssh_config_servers,
1278 cx,
1279 );
1280 cx.notify();
1281 })
1282 .ok();
1283 }
1284 anyhow::Ok(())
1285 })
1286 .detach_and_log_err(cx);
1287 }
1288 div()
1289 .id("ssh-options-copy-server-address")
1290 .track_focus(&entries[2].focus_handle)
1291 .on_action(cx.listener({
1292 let connection_string = connection_string.clone();
1293 move |_, _: &menu::Confirm, window, cx| {
1294 remove_ssh_server(
1295 cx.entity(),
1296 server_index,
1297 connection_string.clone(),
1298 window,
1299 cx,
1300 );
1301 cx.focus_self(window);
1302 }
1303 }))
1304 .child(
1305 ListItem::new("remove-server")
1306 .toggle_state(
1307 entries[2].focus_handle.contains_focused(window, cx),
1308 )
1309 .inset(true)
1310 .spacing(ui::ListItemSpacing::Sparse)
1311 .start_slot(Icon::new(IconName::Trash).color(Color::Error))
1312 .child(Label::new("Remove Server").color(Color::Error))
1313 .on_click(cx.listener(move |_, _, window, cx| {
1314 remove_ssh_server(
1315 cx.entity(),
1316 server_index,
1317 connection_string.clone(),
1318 window,
1319 cx,
1320 );
1321 cx.focus_self(window);
1322 })),
1323 )
1324 })
1325 .child(ListSeparator)
1326 .child({
1327 div()
1328 .id("ssh-options-copy-server-address")
1329 .track_focus(&entries[3].focus_handle)
1330 .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
1331 this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
1332 cx.focus_self(window);
1333 cx.notify();
1334 }))
1335 .child(
1336 ListItem::new("go-back")
1337 .toggle_state(
1338 entries[3].focus_handle.contains_focused(window, cx),
1339 )
1340 .inset(true)
1341 .spacing(ui::ListItemSpacing::Sparse)
1342 .start_slot(
1343 Icon::new(IconName::ArrowLeft).color(Color::Muted),
1344 )
1345 .child(Label::new("Go Back"))
1346 .on_click(cx.listener(|this, _, window, cx| {
1347 this.mode =
1348 Mode::default_mode(&this.ssh_config_servers, cx);
1349 cx.focus_self(window);
1350 cx.notify()
1351 })),
1352 )
1353 }),
1354 )
1355 .into_any_element(),
1356 );
1357 for entry in entries {
1358 view = view.entry(entry);
1359 }
1360
1361 view.render(window, cx).into_any_element()
1362 }
1363
1364 fn render_edit_nickname(
1365 &self,
1366 state: &EditNicknameState,
1367 window: &mut Window,
1368 cx: &mut Context<Self>,
1369 ) -> impl IntoElement {
1370 let Some(connection) = SshSettings::get_global(cx)
1371 .ssh_connections()
1372 .nth(state.index)
1373 else {
1374 return v_flex()
1375 .id("ssh-edit-nickname")
1376 .track_focus(&self.focus_handle(cx));
1377 };
1378
1379 let connection_string = connection.host.clone();
1380 let nickname = connection.nickname.clone().map(|s| s.into());
1381
1382 v_flex()
1383 .id("ssh-edit-nickname")
1384 .track_focus(&self.focus_handle(cx))
1385 .child(
1386 SshConnectionHeader {
1387 connection_string,
1388 paths: Default::default(),
1389 nickname,
1390 }
1391 .render(window, cx),
1392 )
1393 .child(
1394 h_flex()
1395 .p_2()
1396 .border_t_1()
1397 .border_color(cx.theme().colors().border_variant)
1398 .child(state.editor.clone()),
1399 )
1400 }
1401
1402 fn render_default(
1403 &mut self,
1404 mut state: DefaultState,
1405 window: &mut Window,
1406 cx: &mut Context<Self>,
1407 ) -> impl IntoElement {
1408 let ssh_settings = SshSettings::get_global(cx);
1409 let mut should_rebuild = false;
1410
1411 if ssh_settings
1412 .ssh_connections
1413 .as_ref()
1414 .map_or(false, |connections| {
1415 state
1416 .servers
1417 .iter()
1418 .filter_map(|server| match server {
1419 RemoteEntry::Project { connection, .. } => Some(connection),
1420 RemoteEntry::SshConfig { .. } => None,
1421 })
1422 .ne(connections.iter())
1423 })
1424 {
1425 should_rebuild = true;
1426 };
1427
1428 if !should_rebuild && ssh_settings.read_ssh_config {
1429 let current_ssh_hosts: BTreeSet<SharedString> = state
1430 .servers
1431 .iter()
1432 .filter_map(|server| match server {
1433 RemoteEntry::SshConfig { host, .. } => Some(host.clone()),
1434 _ => None,
1435 })
1436 .collect();
1437 let mut expected_ssh_hosts = self.ssh_config_servers.clone();
1438 for server in &state.servers {
1439 if let RemoteEntry::Project { connection, .. } = server {
1440 expected_ssh_hosts.remove(&connection.host);
1441 }
1442 }
1443 should_rebuild = current_ssh_hosts != expected_ssh_hosts;
1444 }
1445
1446 if should_rebuild {
1447 self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
1448 if let Mode::Default(new_state) = &self.mode {
1449 state = new_state.clone();
1450 }
1451 }
1452
1453 let scroll_state = state.scrollbar.parent_entity(&cx.entity());
1454 let connect_button = div()
1455 .id("ssh-connect-new-server-container")
1456 .track_focus(&state.add_new_server.focus_handle)
1457 .anchor_scroll(state.add_new_server.scroll_anchor.clone())
1458 .child(
1459 ListItem::new("register-remove-server-button")
1460 .toggle_state(
1461 state
1462 .add_new_server
1463 .focus_handle
1464 .contains_focused(window, cx),
1465 )
1466 .inset(true)
1467 .spacing(ui::ListItemSpacing::Sparse)
1468 .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
1469 .child(Label::new("Connect New Server"))
1470 .on_click(cx.listener(|this, _, window, cx| {
1471 let state = CreateRemoteServer::new(window, cx);
1472 this.mode = Mode::CreateRemoteServer(state);
1473
1474 cx.notify();
1475 })),
1476 )
1477 .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
1478 let state = CreateRemoteServer::new(window, cx);
1479 this.mode = Mode::CreateRemoteServer(state);
1480
1481 cx.notify();
1482 }));
1483
1484 let handle = &**scroll_state.scroll_handle() as &dyn Any;
1485 let Some(scroll_handle) = handle.downcast_ref::<ScrollHandle>() else {
1486 unreachable!()
1487 };
1488
1489 let mut modal_section = Navigable::new(
1490 v_flex()
1491 .track_focus(&self.focus_handle(cx))
1492 .id("ssh-server-list")
1493 .overflow_y_scroll()
1494 .track_scroll(&scroll_handle)
1495 .size_full()
1496 .child(connect_button)
1497 .child(
1498 List::new()
1499 .empty_message(
1500 v_flex()
1501 .child(
1502 div().px_3().child(
1503 Label::new("No remote servers registered yet.")
1504 .color(Color::Muted),
1505 ),
1506 )
1507 .into_any_element(),
1508 )
1509 .children(state.servers.iter().enumerate().map(|(ix, connection)| {
1510 self.render_ssh_connection(ix, connection.clone(), window, cx)
1511 .into_any_element()
1512 })),
1513 )
1514 .into_any_element(),
1515 )
1516 .entry(state.add_new_server.clone());
1517
1518 for server in &state.servers {
1519 match server {
1520 RemoteEntry::Project {
1521 open_folder,
1522 projects,
1523 configure,
1524 ..
1525 } => {
1526 for (navigation_state, _) in projects {
1527 modal_section = modal_section.entry(navigation_state.clone());
1528 }
1529 modal_section = modal_section
1530 .entry(open_folder.clone())
1531 .entry(configure.clone());
1532 }
1533 RemoteEntry::SshConfig { open_folder, .. } => {
1534 modal_section = modal_section.entry(open_folder.clone());
1535 }
1536 }
1537 }
1538 let mut modal_section = modal_section.render(window, cx).into_any_element();
1539
1540 let (create_window, reuse_window) = if self.create_new_window {
1541 (
1542 window.keystroke_text_for(&menu::Confirm),
1543 window.keystroke_text_for(&menu::SecondaryConfirm),
1544 )
1545 } else {
1546 (
1547 window.keystroke_text_for(&menu::SecondaryConfirm),
1548 window.keystroke_text_for(&menu::Confirm),
1549 )
1550 };
1551 let placeholder_text = Arc::from(format!(
1552 "{reuse_window} reuses this window, {create_window} opens a new one",
1553 ));
1554
1555 Modal::new("remote-projects", None)
1556 .header(
1557 ModalHeader::new()
1558 .child(Headline::new("Remote Projects").size(HeadlineSize::XSmall))
1559 .child(
1560 Label::new(placeholder_text)
1561 .color(Color::Muted)
1562 .size(LabelSize::XSmall),
1563 ),
1564 )
1565 .section(
1566 Section::new().padded(false).child(
1567 v_flex()
1568 .min_h(rems(20.))
1569 .size_full()
1570 .relative()
1571 .child(ListSeparator)
1572 .child(
1573 canvas(
1574 |bounds, window, cx| {
1575 modal_section.prepaint_as_root(
1576 bounds.origin,
1577 bounds.size.into(),
1578 window,
1579 cx,
1580 );
1581 modal_section
1582 },
1583 |_, mut modal_section, window, cx| {
1584 modal_section.paint(window, cx);
1585 },
1586 )
1587 .size_full(),
1588 )
1589 .child(
1590 div()
1591 .occlude()
1592 .h_full()
1593 .absolute()
1594 .top_1()
1595 .bottom_1()
1596 .right_1()
1597 .w(px(8.))
1598 .children(Scrollbar::vertical(scroll_state)),
1599 ),
1600 ),
1601 )
1602 .into_any_element()
1603 }
1604
1605 fn create_host_from_ssh_config(
1606 &mut self,
1607 ssh_config_host: &SharedString,
1608 cx: &mut Context<'_, Self>,
1609 ) -> usize {
1610 let new_ix = Arc::new(AtomicUsize::new(0));
1611
1612 let update_new_ix = new_ix.clone();
1613 self.update_settings_file(cx, move |settings, _| {
1614 update_new_ix.store(
1615 settings
1616 .ssh_connections
1617 .as_ref()
1618 .map_or(0, |connections| connections.len()),
1619 atomic::Ordering::Release,
1620 );
1621 });
1622
1623 self.add_ssh_server(
1624 SshConnectionOptions {
1625 host: ssh_config_host.to_string(),
1626 ..SshConnectionOptions::default()
1627 },
1628 cx,
1629 );
1630 self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
1631 new_ix.load(atomic::Ordering::Acquire)
1632 }
1633}
1634
1635fn spawn_ssh_config_watch(fs: Arc<dyn Fs>, cx: &Context<RemoteServerProjects>) -> Task<()> {
1636 let mut user_ssh_config_watcher =
1637 watch_config_file(cx.background_executor(), fs.clone(), user_ssh_config_file());
1638 let mut global_ssh_config_watcher = watch_config_file(
1639 cx.background_executor(),
1640 fs,
1641 global_ssh_config_file().to_owned(),
1642 );
1643
1644 cx.spawn(async move |remote_server_projects, cx| {
1645 let mut global_hosts = BTreeSet::default();
1646 let mut user_hosts = BTreeSet::default();
1647 let mut running_receivers = 2;
1648
1649 loop {
1650 select! {
1651 new_global_file_contents = global_ssh_config_watcher.next().fuse() => {
1652 match new_global_file_contents {
1653 Some(new_global_file_contents) => {
1654 global_hosts = parse_ssh_config_hosts(&new_global_file_contents);
1655 if remote_server_projects.update(cx, |remote_server_projects, cx| {
1656 remote_server_projects.ssh_config_servers = global_hosts.iter().chain(user_hosts.iter()).map(SharedString::from).collect();
1657 cx.notify();
1658 }).is_err() {
1659 return;
1660 }
1661 },
1662 None => {
1663 running_receivers -= 1;
1664 if running_receivers == 0 {
1665 return;
1666 }
1667 }
1668 }
1669 },
1670 new_user_file_contents = user_ssh_config_watcher.next().fuse() => {
1671 match new_user_file_contents {
1672 Some(new_user_file_contents) => {
1673 user_hosts = parse_ssh_config_hosts(&new_user_file_contents);
1674 if remote_server_projects.update(cx, |remote_server_projects, cx| {
1675 remote_server_projects.ssh_config_servers = global_hosts.iter().chain(user_hosts.iter()).map(SharedString::from).collect();
1676 cx.notify();
1677 }).is_err() {
1678 return;
1679 }
1680 },
1681 None => {
1682 running_receivers -= 1;
1683 if running_receivers == 0 {
1684 return;
1685 }
1686 }
1687 }
1688 },
1689 }
1690 }
1691 })
1692}
1693
1694fn get_text(element: &Entity<Editor>, cx: &mut App) -> String {
1695 element.read(cx).text(cx).trim().to_string()
1696}
1697
1698impl ModalView for RemoteServerProjects {}
1699
1700impl Focusable for RemoteServerProjects {
1701 fn focus_handle(&self, cx: &App) -> FocusHandle {
1702 match &self.mode {
1703 Mode::ProjectPicker(picker) => picker.focus_handle(cx),
1704 _ => self.focus_handle.clone(),
1705 }
1706 }
1707}
1708
1709impl EventEmitter<DismissEvent> for RemoteServerProjects {}
1710
1711impl Render for RemoteServerProjects {
1712 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1713 div()
1714 .elevation_3(cx)
1715 .w(rems(34.))
1716 .key_context("RemoteServerModal")
1717 .on_action(cx.listener(Self::cancel))
1718 .on_action(cx.listener(Self::confirm))
1719 .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
1720 this.focus_handle(cx).focus(window);
1721 }))
1722 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
1723 if matches!(this.mode, Mode::Default(_)) {
1724 cx.emit(DismissEvent)
1725 }
1726 }))
1727 .child(match &self.mode {
1728 Mode::Default(state) => self
1729 .render_default(state.clone(), window, cx)
1730 .into_any_element(),
1731 Mode::ViewServerOptions(state) => self
1732 .render_view_options(state.clone(), window, cx)
1733 .into_any_element(),
1734 Mode::ProjectPicker(element) => element.clone().into_any_element(),
1735 Mode::CreateRemoteServer(state) => self
1736 .render_create_remote_server(state, cx)
1737 .into_any_element(),
1738 Mode::EditNickname(state) => self
1739 .render_edit_nickname(state, window, cx)
1740 .into_any_element(),
1741 })
1742 }
1743}