1use std::collections::BTreeSet;
2use std::{path::PathBuf, sync::Arc, time::Duration};
3
4use anyhow::{Result, anyhow};
5use auto_update::AutoUpdater;
6use editor::Editor;
7use extension_host::ExtensionStore;
8use futures::channel::oneshot;
9use gpui::{
10 Animation, AnimationExt, AnyWindowHandle, App, AsyncApp, DismissEvent, Entity, EventEmitter,
11 Focusable, FontFeatures, ParentElement as _, PromptLevel, Render, SemanticVersion,
12 SharedString, Task, TextStyleRefinement, Transformation, WeakEntity, percentage,
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 ActiveTheme, Color, Context, Icon, IconName, IconSize, InteractiveElement, IntoElement, Label,
26 LabelCommon, Styled, Window, prelude::*,
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> + use<> {
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<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<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(cx).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 = cx.new(|cx| Markdown::new_text(prompt.into(), markdown_style, cx));
211 self.prompt = Some((markdown, tx));
212 self.status_message.take();
213 window.focus(&self.editor.focus_handle(cx));
214 cx.notify();
215 }
216
217 pub fn set_status(&mut self, status: Option<String>, cx: &mut Context<Self>) {
218 self.status_message = status.map(|s| s.into());
219 cx.notify();
220 }
221
222 pub fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
223 if let Some((_, tx)) = self.prompt.take() {
224 self.status_message = Some("Connecting".into());
225 self.editor.update(cx, |editor, cx| {
226 tx.send(editor.text(cx)).ok();
227 editor.clear(window, cx);
228 });
229 }
230 }
231}
232
233impl Render for SshPrompt {
234 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
235 v_flex()
236 .key_context("PasswordPrompt")
237 .py_2()
238 .px_3()
239 .size_full()
240 .text_buffer(cx)
241 .when_some(self.status_message.clone(), |el, status_message| {
242 el.child(
243 h_flex()
244 .gap_1()
245 .child(
246 Icon::new(IconName::ArrowCircle)
247 .size(IconSize::Medium)
248 .with_animation(
249 "arrow-circle",
250 Animation::new(Duration::from_secs(2)).repeat(),
251 |icon, delta| {
252 icon.transform(Transformation::rotate(percentage(delta)))
253 },
254 ),
255 )
256 .child(
257 div()
258 .text_ellipsis()
259 .overflow_x_hidden()
260 .child(format!("{}…", status_message)),
261 ),
262 )
263 })
264 .when_some(self.prompt.as_ref(), |el, prompt| {
265 el.child(
266 div()
267 .size_full()
268 .overflow_hidden()
269 .child(prompt.0.clone())
270 .child(self.editor.clone()),
271 )
272 })
273 }
274}
275
276impl SshConnectionModal {
277 pub(crate) fn new(
278 connection_options: &SshConnectionOptions,
279 paths: Vec<PathBuf>,
280 window: &mut Window,
281 cx: &mut Context<Self>,
282 ) -> Self {
283 Self {
284 prompt: cx.new(|cx| SshPrompt::new(connection_options, window, cx)),
285 finished: false,
286 paths,
287 }
288 }
289
290 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
291 self.prompt
292 .update(cx, |prompt, cx| prompt.confirm(window, cx))
293 }
294
295 pub fn finished(&mut self, cx: &mut Context<Self>) {
296 self.finished = true;
297 cx.emit(DismissEvent);
298 }
299
300 fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
301 if let Some(tx) = self
302 .prompt
303 .update(cx, |prompt, _cx| prompt.cancellation.take())
304 {
305 tx.send(()).ok();
306 }
307 self.finished(cx);
308 }
309}
310
311pub(crate) struct SshConnectionHeader {
312 pub(crate) connection_string: SharedString,
313 pub(crate) paths: Vec<PathBuf>,
314 pub(crate) nickname: Option<SharedString>,
315}
316
317impl RenderOnce for SshConnectionHeader {
318 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
319 let theme = cx.theme();
320
321 let mut header_color = theme.colors().text;
322 header_color.fade_out(0.96);
323
324 let (main_label, meta_label) = if let Some(nickname) = self.nickname {
325 (nickname, Some(format!("({})", self.connection_string)))
326 } else {
327 (self.connection_string, None)
328 };
329
330 h_flex()
331 .px(DynamicSpacing::Base12.rems(cx))
332 .pt(DynamicSpacing::Base08.rems(cx))
333 .pb(DynamicSpacing::Base04.rems(cx))
334 .rounded_t_sm()
335 .w_full()
336 .gap_1p5()
337 .child(Icon::new(IconName::Server).size(IconSize::XSmall))
338 .child(
339 h_flex()
340 .gap_1()
341 .overflow_x_hidden()
342 .child(
343 div()
344 .max_w_96()
345 .overflow_x_hidden()
346 .text_ellipsis()
347 .child(Headline::new(main_label).size(HeadlineSize::XSmall)),
348 )
349 .children(
350 meta_label.map(|label| {
351 Label::new(label).color(Color::Muted).size(LabelSize::Small)
352 }),
353 )
354 .child(div().overflow_x_hidden().text_ellipsis().children(
355 self.paths.into_iter().map(|path| {
356 Label::new(path.to_string_lossy().to_string())
357 .size(LabelSize::Small)
358 .color(Color::Muted)
359 }),
360 )),
361 )
362 }
363}
364
365impl Render for SshConnectionModal {
366 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
367 let nickname = self.prompt.read(cx).nickname.clone();
368 let connection_string = self.prompt.read(cx).connection_string.clone();
369
370 let theme = cx.theme().clone();
371 let body_color = theme.colors().editor_background;
372
373 v_flex()
374 .elevation_3(cx)
375 .w(rems(34.))
376 .border_1()
377 .border_color(theme.colors().border)
378 .key_context("SshConnectionModal")
379 .track_focus(&self.focus_handle(cx))
380 .on_action(cx.listener(Self::dismiss))
381 .on_action(cx.listener(Self::confirm))
382 .child(
383 SshConnectionHeader {
384 paths: self.paths.clone(),
385 connection_string,
386 nickname,
387 }
388 .render(window, cx),
389 )
390 .child(
391 div()
392 .w_full()
393 .rounded_b_lg()
394 .bg(body_color)
395 .border_t_1()
396 .border_color(theme.colors().border_variant)
397 .child(self.prompt.clone()),
398 )
399 }
400}
401
402impl Focusable for SshConnectionModal {
403 fn focus_handle(&self, cx: &gpui::App) -> gpui::FocusHandle {
404 self.prompt.read(cx).editor.focus_handle(cx)
405 }
406}
407
408impl EventEmitter<DismissEvent> for SshConnectionModal {}
409
410impl ModalView for SshConnectionModal {
411 fn on_before_dismiss(
412 &mut self,
413 _window: &mut Window,
414 _: &mut Context<Self>,
415 ) -> workspace::DismissDecision {
416 return workspace::DismissDecision::Dismiss(self.finished);
417 }
418
419 fn fade_out_background(&self) -> bool {
420 true
421 }
422}
423
424#[derive(Clone)]
425pub struct SshClientDelegate {
426 window: AnyWindowHandle,
427 ui: WeakEntity<SshPrompt>,
428 known_password: Option<String>,
429}
430
431impl remote::SshClientDelegate for SshClientDelegate {
432 fn ask_password(&self, prompt: String, tx: oneshot::Sender<String>, cx: &mut AsyncApp) {
433 let mut known_password = self.known_password.clone();
434 if let Some(password) = known_password.take() {
435 tx.send(password).ok();
436 } else {
437 self.window
438 .update(cx, |_, window, cx| {
439 self.ui.update(cx, |modal, cx| {
440 modal.set_prompt(prompt, tx, window, cx);
441 })
442 })
443 .ok();
444 }
445 }
446
447 fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
448 self.update_status(status, cx)
449 }
450
451 fn download_server_binary_locally(
452 &self,
453 platform: SshPlatform,
454 release_channel: ReleaseChannel,
455 version: Option<SemanticVersion>,
456 cx: &mut AsyncApp,
457 ) -> Task<anyhow::Result<PathBuf>> {
458 cx.spawn(async move |cx| {
459 let binary_path = AutoUpdater::download_remote_server_release(
460 platform.os,
461 platform.arch,
462 release_channel,
463 version,
464 cx,
465 )
466 .await
467 .map_err(|e| {
468 anyhow!(
469 "Failed to download remote server binary (version: {}, os: {}, arch: {}): {}",
470 version
471 .map(|v| format!("{}", v))
472 .unwrap_or("unknown".to_string()),
473 platform.os,
474 platform.arch,
475 e
476 )
477 })?;
478 Ok(binary_path)
479 })
480 }
481
482 fn get_download_params(
483 &self,
484 platform: SshPlatform,
485 release_channel: ReleaseChannel,
486 version: Option<SemanticVersion>,
487 cx: &mut AsyncApp,
488 ) -> Task<Result<Option<(String, String)>>> {
489 cx.spawn(async move |cx| {
490 AutoUpdater::get_remote_server_release_url(
491 platform.os,
492 platform.arch,
493 release_channel,
494 version,
495 cx,
496 )
497 .await
498 })
499 }
500}
501
502impl SshClientDelegate {
503 fn update_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
504 self.window
505 .update(cx, |_, _, cx| {
506 self.ui.update(cx, |modal, cx| {
507 modal.set_status(status.map(|s| s.to_string()), cx);
508 })
509 })
510 .ok();
511 }
512}
513
514pub fn is_connecting_over_ssh(workspace: &Workspace, cx: &App) -> bool {
515 workspace.active_modal::<SshConnectionModal>(cx).is_some()
516}
517
518pub fn connect_over_ssh(
519 unique_identifier: ConnectionIdentifier,
520 connection_options: SshConnectionOptions,
521 ui: Entity<SshPrompt>,
522 window: &mut Window,
523 cx: &mut App,
524) -> Task<Result<Option<Entity<SshRemoteClient>>>> {
525 let window = window.window_handle();
526 let known_password = connection_options.password.clone();
527 let (tx, rx) = oneshot::channel();
528 ui.update(cx, |ui, _cx| ui.set_cancellation_tx(tx));
529
530 remote::SshRemoteClient::new(
531 unique_identifier,
532 connection_options,
533 rx,
534 Arc::new(SshClientDelegate {
535 window,
536 ui: ui.downgrade(),
537 known_password,
538 }),
539 cx,
540 )
541}
542
543pub async fn open_ssh_project(
544 connection_options: SshConnectionOptions,
545 paths: Vec<PathBuf>,
546 app_state: Arc<AppState>,
547 open_options: workspace::OpenOptions,
548 cx: &mut AsyncApp,
549) -> Result<()> {
550 let window = if let Some(window) = open_options.replace_window {
551 window
552 } else {
553 let options = cx.update(|cx| (app_state.build_window_options)(None, cx))?;
554 cx.open_window(options, |window, cx| {
555 let project = project::Project::local(
556 app_state.client.clone(),
557 app_state.node_runtime.clone(),
558 app_state.user_store.clone(),
559 app_state.languages.clone(),
560 app_state.debug_adapters.clone(),
561 app_state.fs.clone(),
562 None,
563 cx,
564 );
565 cx.new(|cx| Workspace::new(None, project, app_state.clone(), window, cx))
566 })?
567 };
568
569 loop {
570 let (cancel_tx, cancel_rx) = oneshot::channel();
571 let delegate = window.update(cx, {
572 let connection_options = connection_options.clone();
573 let paths = paths.clone();
574 move |workspace, window, cx| {
575 window.activate_window();
576 workspace.toggle_modal(window, cx, |window, cx| {
577 SshConnectionModal::new(&connection_options, paths, window, cx)
578 });
579
580 let ui = workspace
581 .active_modal::<SshConnectionModal>(cx)?
582 .read(cx)
583 .prompt
584 .clone();
585
586 ui.update(cx, |ui, _cx| {
587 ui.set_cancellation_tx(cancel_tx);
588 });
589
590 Some(Arc::new(SshClientDelegate {
591 window: window.window_handle(),
592 ui: ui.downgrade(),
593 known_password: connection_options.password.clone(),
594 }))
595 }
596 })?;
597
598 let Some(delegate) = delegate else { break };
599
600 let did_open_ssh_project = cx
601 .update(|cx| {
602 workspace::open_ssh_project_with_new_connection(
603 window,
604 connection_options.clone(),
605 cancel_rx,
606 delegate.clone(),
607 app_state.clone(),
608 paths.clone(),
609 cx,
610 )
611 })?
612 .await;
613
614 window
615 .update(cx, |workspace, _, cx| {
616 if let Some(ui) = workspace.active_modal::<SshConnectionModal>(cx) {
617 ui.update(cx, |modal, cx| modal.finished(cx))
618 }
619 })
620 .ok();
621
622 if let Err(e) = did_open_ssh_project {
623 log::error!("Failed to open project: {:?}", e);
624 let response = window
625 .update(cx, |_, window, cx| {
626 window.prompt(
627 PromptLevel::Critical,
628 "Failed to connect over SSH",
629 Some(&e.to_string()),
630 &["Retry", "Ok"],
631 cx,
632 )
633 })?
634 .await;
635
636 if response == Ok(0) {
637 continue;
638 }
639 }
640
641 window
642 .update(cx, |workspace, _, cx| {
643 if let Some(client) = workspace.project().read(cx).ssh_client().clone() {
644 ExtensionStore::global(cx)
645 .update(cx, |store, cx| store.register_ssh_client(client, cx));
646 }
647 })
648 .ok();
649
650 break;
651 }
652
653 // Already showed the error to the user
654 Ok(())
655}