1use std::collections::BTreeSet;
2use std::{path::PathBuf, sync::Arc, time::Duration};
3
4use anyhow::{anyhow, Result};
5use auto_update::AutoUpdater;
6use editor::Editor;
7use extension_host::ExtensionStore;
8use futures::channel::oneshot;
9use gpui::{
10 percentage, Animation, AnimationExt, AnyWindowHandle, App, AsyncApp, DismissEvent, Entity,
11 EventEmitter, Focusable, FontFeatures, ParentElement as _, PromptLevel, Render,
12 SemanticVersion, SharedString, Task, TextStyleRefinement, Transformation, WeakEntity,
13};
14
15use language::CursorShape;
16use markdown::{Markdown, MarkdownStyle};
17use release_channel::ReleaseChannel;
18use remote::ssh_session::{ConnectionIdentifier, SshPortForwardOption};
19use remote::{SshConnectionOptions, SshPlatform, SshRemoteClient};
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22use settings::{Settings, SettingsSources};
23use theme::ThemeSettings;
24use ui::{
25 prelude::*, ActiveTheme, Color, Context, Icon, IconName, IconSize, InteractiveElement,
26 IntoElement, Label, LabelCommon, Styled, Window,
27};
28use workspace::{AppState, ModalView, Workspace};
29
30#[derive(Deserialize)]
31pub struct SshSettings {
32 pub ssh_connections: Option<Vec<SshConnection>>,
33}
34
35impl SshSettings {
36 pub fn ssh_connections(&self) -> impl Iterator<Item = SshConnection> {
37 self.ssh_connections.clone().into_iter().flatten()
38 }
39
40 pub fn connection_options_for(
41 &self,
42 host: String,
43 port: Option<u16>,
44 username: Option<String>,
45 ) -> SshConnectionOptions {
46 for conn in self.ssh_connections() {
47 if conn.host == host && conn.username == username && conn.port == port {
48 return SshConnectionOptions {
49 nickname: conn.nickname,
50 upload_binary_over_ssh: conn.upload_binary_over_ssh.unwrap_or_default(),
51 args: Some(conn.args),
52 host,
53 port,
54 username,
55 port_forwards: conn.port_forwards,
56 password: None,
57 };
58 }
59 }
60 SshConnectionOptions {
61 host,
62 port,
63 username,
64 ..Default::default()
65 }
66 }
67}
68
69#[derive(Clone, Default, Serialize, Deserialize, PartialEq, JsonSchema)]
70pub struct SshConnection {
71 pub host: SharedString,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 pub username: Option<String>,
74 #[serde(skip_serializing_if = "Option::is_none")]
75 pub port: Option<u16>,
76 #[serde(skip_serializing_if = "Vec::is_empty")]
77 #[serde(default)]
78 pub args: Vec<String>,
79 #[serde(default)]
80 pub projects: BTreeSet<SshProject>,
81 /// Name to use for this server in UI.
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub nickname: Option<String>,
84 // By default Zed will download the binary to the host directly.
85 // If this is set to true, Zed will download the binary to your local machine,
86 // and then upload it over the SSH connection. Useful if your SSH server has
87 // limited outbound internet access.
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub upload_binary_over_ssh: Option<bool>,
90
91 #[serde(skip_serializing_if = "Option::is_none")]
92 pub port_forwards: Option<Vec<SshPortForwardOption>>,
93}
94
95impl From<SshConnection> for SshConnectionOptions {
96 fn from(val: SshConnection) -> Self {
97 SshConnectionOptions {
98 host: val.host.into(),
99 username: val.username,
100 port: val.port,
101 password: None,
102 args: Some(val.args),
103 nickname: val.nickname,
104 upload_binary_over_ssh: val.upload_binary_over_ssh.unwrap_or_default(),
105 port_forwards: val.port_forwards,
106 }
107 }
108}
109
110#[derive(Clone, Default, Serialize, PartialEq, Eq, PartialOrd, Ord, Deserialize, JsonSchema)]
111pub struct SshProject {
112 pub paths: Vec<String>,
113}
114
115#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
116pub struct RemoteSettingsContent {
117 pub ssh_connections: Option<Vec<SshConnection>>,
118}
119
120impl Settings for SshSettings {
121 const KEY: Option<&'static str> = None;
122
123 type FileContent = RemoteSettingsContent;
124
125 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
126 sources.json_merge()
127 }
128}
129
130pub struct SshPrompt {
131 connection_string: SharedString,
132 nickname: Option<SharedString>,
133 status_message: Option<SharedString>,
134 prompt: Option<(Entity<Markdown>, oneshot::Sender<Result<String>>)>,
135 cancellation: Option<oneshot::Sender<()>>,
136 editor: Entity<Editor>,
137}
138
139impl Drop for SshPrompt {
140 fn drop(&mut self) {
141 if let Some(cancel) = self.cancellation.take() {
142 cancel.send(()).ok();
143 }
144 }
145}
146
147pub struct SshConnectionModal {
148 pub(crate) prompt: Entity<SshPrompt>,
149 paths: Vec<PathBuf>,
150 finished: bool,
151}
152
153impl SshPrompt {
154 pub(crate) fn new(
155 connection_options: &SshConnectionOptions,
156 window: &mut Window,
157 cx: &mut Context<Self>,
158 ) -> Self {
159 let connection_string = connection_options.connection_string().into();
160 let nickname = connection_options.nickname.clone().map(|s| s.into());
161
162 Self {
163 connection_string,
164 nickname,
165 editor: cx.new(|cx| Editor::single_line(window, cx)),
166 status_message: None,
167 cancellation: None,
168 prompt: None,
169 }
170 }
171
172 pub fn set_cancellation_tx(&mut self, tx: oneshot::Sender<()>) {
173 self.cancellation = Some(tx);
174 }
175
176 pub fn set_prompt(
177 &mut self,
178 prompt: String,
179 tx: oneshot::Sender<Result<String>>,
180 window: &mut Window,
181 cx: &mut Context<Self>,
182 ) {
183 let theme = ThemeSettings::get_global(cx);
184
185 let mut text_style = window.text_style();
186 let refinement = TextStyleRefinement {
187 font_family: Some(theme.buffer_font.family.clone()),
188 font_features: Some(FontFeatures::disable_ligatures()),
189 font_size: Some(theme.buffer_font_size.into()),
190 color: Some(cx.theme().colors().editor_foreground),
191 background_color: Some(gpui::transparent_black()),
192 ..Default::default()
193 };
194
195 text_style.refine(&refinement);
196 self.editor.update(cx, |editor, cx| {
197 if prompt.contains("yes/no") {
198 editor.set_masked(false, cx);
199 } else {
200 editor.set_masked(true, cx);
201 }
202 editor.set_text_style_refinement(refinement);
203 editor.set_cursor_shape(CursorShape::Block, cx);
204 });
205 let markdown_style = MarkdownStyle {
206 base_text_style: text_style,
207 selection_background_color: cx.theme().players().local().selection,
208 ..Default::default()
209 };
210 let markdown =
211 cx.new(|cx| Markdown::new_text(prompt, markdown_style, None, None, window, cx));
212 self.prompt = Some((markdown, tx));
213 self.status_message.take();
214 window.focus(&self.editor.focus_handle(cx));
215 cx.notify();
216 }
217
218 pub fn set_status(&mut self, status: Option<String>, cx: &mut Context<Self>) {
219 self.status_message = status.map(|s| s.into());
220 cx.notify();
221 }
222
223 pub fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
224 if let Some((_, tx)) = self.prompt.take() {
225 self.status_message = Some("Connecting".into());
226 self.editor.update(cx, |editor, cx| {
227 tx.send(Ok(editor.text(cx))).ok();
228 editor.clear(window, cx);
229 });
230 }
231 }
232}
233
234impl Render for SshPrompt {
235 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
236 v_flex()
237 .key_context("PasswordPrompt")
238 .py_2()
239 .px_3()
240 .size_full()
241 .text_buffer(cx)
242 .when_some(self.status_message.clone(), |el, status_message| {
243 el.child(
244 h_flex()
245 .gap_1()
246 .child(
247 Icon::new(IconName::ArrowCircle)
248 .size(IconSize::Medium)
249 .with_animation(
250 "arrow-circle",
251 Animation::new(Duration::from_secs(2)).repeat(),
252 |icon, delta| {
253 icon.transform(Transformation::rotate(percentage(delta)))
254 },
255 ),
256 )
257 .child(
258 div()
259 .text_ellipsis()
260 .overflow_x_hidden()
261 .child(format!("{}…", status_message)),
262 ),
263 )
264 })
265 .when_some(self.prompt.as_ref(), |el, prompt| {
266 el.child(
267 div()
268 .size_full()
269 .overflow_hidden()
270 .child(prompt.0.clone())
271 .child(self.editor.clone()),
272 )
273 })
274 }
275}
276
277impl SshConnectionModal {
278 pub(crate) fn new(
279 connection_options: &SshConnectionOptions,
280 paths: Vec<PathBuf>,
281 window: &mut Window,
282 cx: &mut Context<Self>,
283 ) -> Self {
284 Self {
285 prompt: cx.new(|cx| SshPrompt::new(connection_options, window, cx)),
286 finished: false,
287 paths,
288 }
289 }
290
291 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
292 self.prompt
293 .update(cx, |prompt, cx| prompt.confirm(window, cx))
294 }
295
296 pub fn finished(&mut self, cx: &mut Context<Self>) {
297 self.finished = true;
298 cx.emit(DismissEvent);
299 }
300
301 fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
302 if let Some(tx) = self
303 .prompt
304 .update(cx, |prompt, _cx| prompt.cancellation.take())
305 {
306 tx.send(()).ok();
307 }
308 self.finished(cx);
309 }
310}
311
312pub(crate) struct SshConnectionHeader {
313 pub(crate) connection_string: SharedString,
314 pub(crate) paths: Vec<PathBuf>,
315 pub(crate) nickname: Option<SharedString>,
316}
317
318impl RenderOnce for SshConnectionHeader {
319 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
320 let theme = cx.theme();
321
322 let mut header_color = theme.colors().text;
323 header_color.fade_out(0.96);
324
325 let (main_label, meta_label) = if let Some(nickname) = self.nickname {
326 (nickname, Some(format!("({})", self.connection_string)))
327 } else {
328 (self.connection_string, None)
329 };
330
331 h_flex()
332 .px(DynamicSpacing::Base12.rems(cx))
333 .pt(DynamicSpacing::Base08.rems(cx))
334 .pb(DynamicSpacing::Base04.rems(cx))
335 .rounded_t_md()
336 .w_full()
337 .gap_1p5()
338 .child(Icon::new(IconName::Server).size(IconSize::XSmall))
339 .child(
340 h_flex()
341 .gap_1()
342 .overflow_x_hidden()
343 .child(
344 div()
345 .max_w_96()
346 .overflow_x_hidden()
347 .text_ellipsis()
348 .child(Headline::new(main_label).size(HeadlineSize::XSmall)),
349 )
350 .children(
351 meta_label.map(|label| {
352 Label::new(label).color(Color::Muted).size(LabelSize::Small)
353 }),
354 )
355 .child(div().overflow_x_hidden().text_ellipsis().children(
356 self.paths.into_iter().map(|path| {
357 Label::new(path.to_string_lossy().to_string())
358 .size(LabelSize::Small)
359 .color(Color::Muted)
360 }),
361 )),
362 )
363 }
364}
365
366impl Render for SshConnectionModal {
367 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
368 let nickname = self.prompt.read(cx).nickname.clone();
369 let connection_string = self.prompt.read(cx).connection_string.clone();
370
371 let theme = cx.theme().clone();
372 let body_color = theme.colors().editor_background;
373
374 v_flex()
375 .elevation_3(cx)
376 .w(rems(34.))
377 .border_1()
378 .border_color(theme.colors().border)
379 .key_context("SshConnectionModal")
380 .track_focus(&self.focus_handle(cx))
381 .on_action(cx.listener(Self::dismiss))
382 .on_action(cx.listener(Self::confirm))
383 .child(
384 SshConnectionHeader {
385 paths: self.paths.clone(),
386 connection_string,
387 nickname,
388 }
389 .render(window, cx),
390 )
391 .child(
392 div()
393 .w_full()
394 .rounded_b_lg()
395 .bg(body_color)
396 .border_t_1()
397 .border_color(theme.colors().border_variant)
398 .child(self.prompt.clone()),
399 )
400 }
401}
402
403impl Focusable for SshConnectionModal {
404 fn focus_handle(&self, cx: &gpui::App) -> gpui::FocusHandle {
405 self.prompt.read(cx).editor.focus_handle(cx)
406 }
407}
408
409impl EventEmitter<DismissEvent> for SshConnectionModal {}
410
411impl ModalView for SshConnectionModal {
412 fn on_before_dismiss(
413 &mut self,
414 _window: &mut Window,
415 _: &mut Context<Self>,
416 ) -> workspace::DismissDecision {
417 return workspace::DismissDecision::Dismiss(self.finished);
418 }
419
420 fn fade_out_background(&self) -> bool {
421 true
422 }
423}
424
425#[derive(Clone)]
426pub struct SshClientDelegate {
427 window: AnyWindowHandle,
428 ui: WeakEntity<SshPrompt>,
429 known_password: Option<String>,
430}
431
432impl remote::SshClientDelegate for SshClientDelegate {
433 fn ask_password(&self, prompt: String, cx: &mut AsyncApp) -> oneshot::Receiver<Result<String>> {
434 let (tx, rx) = oneshot::channel();
435 let mut known_password = self.known_password.clone();
436 if let Some(password) = known_password.take() {
437 tx.send(Ok(password)).ok();
438 } else {
439 self.window
440 .update(cx, |_, window, cx| {
441 self.ui.update(cx, |modal, cx| {
442 modal.set_prompt(prompt, tx, window, cx);
443 })
444 })
445 .ok();
446 }
447 rx
448 }
449
450 fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
451 self.update_status(status, cx)
452 }
453
454 fn download_server_binary_locally(
455 &self,
456 platform: SshPlatform,
457 release_channel: ReleaseChannel,
458 version: Option<SemanticVersion>,
459 cx: &mut AsyncApp,
460 ) -> Task<anyhow::Result<PathBuf>> {
461 cx.spawn(|mut cx| async move {
462 let binary_path = AutoUpdater::download_remote_server_release(
463 platform.os,
464 platform.arch,
465 release_channel,
466 version,
467 &mut cx,
468 )
469 .await
470 .map_err(|e| {
471 anyhow!(
472 "Failed to download remote server binary (version: {}, os: {}, arch: {}): {}",
473 version
474 .map(|v| format!("{}", v))
475 .unwrap_or("unknown".to_string()),
476 platform.os,
477 platform.arch,
478 e
479 )
480 })?;
481 Ok(binary_path)
482 })
483 }
484
485 fn get_download_params(
486 &self,
487 platform: SshPlatform,
488 release_channel: ReleaseChannel,
489 version: Option<SemanticVersion>,
490 cx: &mut AsyncApp,
491 ) -> Task<Result<Option<(String, String)>>> {
492 cx.spawn(|mut cx| async move {
493 AutoUpdater::get_remote_server_release_url(
494 platform.os,
495 platform.arch,
496 release_channel,
497 version,
498 &mut cx,
499 )
500 .await
501 })
502 }
503}
504
505impl SshClientDelegate {
506 fn update_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
507 self.window
508 .update(cx, |_, _, cx| {
509 self.ui.update(cx, |modal, cx| {
510 modal.set_status(status.map(|s| s.to_string()), cx);
511 })
512 })
513 .ok();
514 }
515}
516
517pub fn is_connecting_over_ssh(workspace: &Workspace, cx: &App) -> bool {
518 workspace.active_modal::<SshConnectionModal>(cx).is_some()
519}
520
521pub fn connect_over_ssh(
522 unique_identifier: ConnectionIdentifier,
523 connection_options: SshConnectionOptions,
524 ui: Entity<SshPrompt>,
525 window: &mut Window,
526 cx: &mut App,
527) -> Task<Result<Option<Entity<SshRemoteClient>>>> {
528 let window = window.window_handle();
529 let known_password = connection_options.password.clone();
530 let (tx, rx) = oneshot::channel();
531 ui.update(cx, |ui, _cx| ui.set_cancellation_tx(tx));
532
533 remote::SshRemoteClient::new(
534 unique_identifier,
535 connection_options,
536 rx,
537 Arc::new(SshClientDelegate {
538 window,
539 ui: ui.downgrade(),
540 known_password,
541 }),
542 cx,
543 )
544}
545
546pub async fn open_ssh_project(
547 connection_options: SshConnectionOptions,
548 paths: Vec<PathBuf>,
549 app_state: Arc<AppState>,
550 open_options: workspace::OpenOptions,
551 cx: &mut AsyncApp,
552) -> Result<()> {
553 let window = if let Some(window) = open_options.replace_window {
554 window
555 } else {
556 let options = cx.update(|cx| (app_state.build_window_options)(None, cx))?;
557 cx.open_window(options, |window, cx| {
558 let project = project::Project::local(
559 app_state.client.clone(),
560 app_state.node_runtime.clone(),
561 app_state.user_store.clone(),
562 app_state.languages.clone(),
563 app_state.fs.clone(),
564 None,
565 cx,
566 );
567 cx.new(|cx| Workspace::new(None, project, app_state.clone(), window, cx))
568 })?
569 };
570
571 loop {
572 let (cancel_tx, cancel_rx) = oneshot::channel();
573 let delegate = window.update(cx, {
574 let connection_options = connection_options.clone();
575 let paths = paths.clone();
576 move |workspace, window, cx| {
577 window.activate_window();
578 workspace.toggle_modal(window, cx, |window, cx| {
579 SshConnectionModal::new(&connection_options, paths, window, cx)
580 });
581
582 let ui = workspace
583 .active_modal::<SshConnectionModal>(cx)?
584 .read(cx)
585 .prompt
586 .clone();
587
588 ui.update(cx, |ui, _cx| {
589 ui.set_cancellation_tx(cancel_tx);
590 });
591
592 Some(Arc::new(SshClientDelegate {
593 window: window.window_handle(),
594 ui: ui.downgrade(),
595 known_password: connection_options.password.clone(),
596 }))
597 }
598 })?;
599
600 let Some(delegate) = delegate else { break };
601
602 let did_open_ssh_project = cx
603 .update(|cx| {
604 workspace::open_ssh_project(
605 window,
606 connection_options.clone(),
607 cancel_rx,
608 delegate.clone(),
609 app_state.clone(),
610 paths.clone(),
611 cx,
612 )
613 })?
614 .await;
615
616 window
617 .update(cx, |workspace, _, cx| {
618 if let Some(ui) = workspace.active_modal::<SshConnectionModal>(cx) {
619 ui.update(cx, |modal, cx| modal.finished(cx))
620 }
621 })
622 .ok();
623
624 if let Err(e) = did_open_ssh_project {
625 log::error!("Failed to open project: {:?}", e);
626 let response = window
627 .update(cx, |_, window, cx| {
628 window.prompt(
629 PromptLevel::Critical,
630 "Failed to connect over SSH",
631 Some(&e.to_string()),
632 &["Retry", "Ok"],
633 cx,
634 )
635 })?
636 .await;
637
638 if response == Ok(0) {
639 continue;
640 }
641 }
642
643 window
644 .update(cx, |workspace, _, cx| {
645 if let Some(client) = workspace.project().read(cx).ssh_client().clone() {
646 ExtensionStore::global(cx)
647 .update(cx, |store, cx| store.register_ssh_client(client, cx));
648 }
649 })
650 .ok();
651
652 break;
653 }
654
655 // Already showed the error to the user
656 Ok(())
657}