remote projects per user (#10594)

Release Notes:

- Made remote projects per-user instead of per-channel. If you'd like to
be part of the remote development alpha, please email hi@zed.dev.

---------

Co-authored-by: Bennet Bo Fenner <53836821+bennetbo@users.noreply.github.com>
Co-authored-by: Bennet <bennetbo@gmx.de>
Co-authored-by: Nate Butler <1714999+iamnbutler@users.noreply.github.com>
Co-authored-by: Nate Butler <iamnbutler@gmail.com>
This commit is contained in:
Conrad Irwin 2024-04-23 15:33:09 -06:00 committed by GitHub
parent 8ae4c3277f
commit e0c83a1d32
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
56 changed files with 2807 additions and 1625 deletions

View file

@ -1,6 +1,9 @@
mod remote_projects;
use feature_flags::FeatureFlagAppExt;
use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{
AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Result,
Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
Subscription, Task, View, ViewContext, WeakView,
};
use ordered_float::OrderedFloat;
@ -8,11 +11,21 @@ use picker::{
highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},
Picker, PickerDelegate,
};
use remote_projects::RemoteProjects;
use rpc::proto::DevServerStatus;
use serde::Deserialize;
use std::{path::Path, sync::Arc};
use ui::{prelude::*, tooltip_container, ListItem, ListItemSpacing, Tooltip};
use util::paths::PathExt;
use workspace::{ModalView, Workspace, WorkspaceId, WorkspaceLocation, WORKSPACE_DB};
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use ui::{
prelude::*, tooltip_container, ButtonLike, IconWithIndicator, Indicator, KeyBinding, ListItem,
ListItemSpacing, Tooltip,
};
use util::{paths::PathExt, ResultExt};
use workspace::{
AppState, ModalView, SerializedWorkspaceLocation, Workspace, WorkspaceId, WORKSPACE_DB,
};
#[derive(PartialEq, Clone, Deserialize, Default)]
pub struct OpenRecent {
@ -25,9 +38,12 @@ fn default_create_new_window() -> bool {
}
gpui::impl_actions!(projects, [OpenRecent]);
gpui::actions!(projects, [OpenRemote]);
pub fn init(cx: &mut AppContext) {
cx.observe_new_views(RecentProjects::register).detach();
cx.observe_new_views(remote_projects::RemoteProjects::register)
.detach();
}
pub struct RecentProjects {
@ -55,10 +71,11 @@ impl RecentProjects {
let workspaces = WORKSPACE_DB
.recent_workspaces_on_disk()
.await
.log_err()
.unwrap_or_default();
this.update(&mut cx, move |this, cx| {
this.picker.update(cx, move |picker, cx| {
picker.delegate.workspaces = workspaces;
picker.delegate.set_workspaces(workspaces);
picker.update_matches(picker.query(cx), cx)
})
})
@ -75,9 +92,7 @@ impl RecentProjects {
fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {
let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
if let Some(handler) = Self::open(workspace, open_recent.create_new_window, cx) {
handler.detach_and_log_err(cx);
}
Self::open(workspace, open_recent.create_new_window, cx);
return;
};
@ -89,24 +104,17 @@ impl RecentProjects {
});
}
fn open(
_: &mut Workspace,
pub fn open(
workspace: &mut Workspace,
create_new_window: bool,
cx: &mut ViewContext<Workspace>,
) -> Option<Task<Result<()>>> {
Some(cx.spawn(|workspace, mut cx| async move {
workspace.update(&mut cx, |workspace, cx| {
let weak_workspace = cx.view().downgrade();
workspace.toggle_modal(cx, |cx| {
let delegate =
RecentProjectsDelegate::new(weak_workspace, create_new_window, true);
let modal = Self::new(delegate, 34., cx);
modal
});
})?;
Ok(())
}))
) {
let weak = cx.view().downgrade();
workspace.toggle_modal(cx, |cx| {
let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);
let modal = Self::new(delegate, 34., cx);
modal
})
}
pub fn open_popover(workspace: WeakView<Workspace>, cx: &mut WindowContext<'_>) -> View<Self> {
@ -143,13 +151,14 @@ impl Render for RecentProjects {
pub struct RecentProjectsDelegate {
workspace: WeakView<Workspace>,
workspaces: Vec<(WorkspaceId, WorkspaceLocation)>,
workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>,
selected_match_index: usize,
matches: Vec<StringMatch>,
render_paths: bool,
create_new_window: bool,
// Flag to reset index when there is a new query vs not reset index when user delete an item
reset_selected_match_index: bool,
has_any_remote_projects: bool,
}
impl RecentProjectsDelegate {
@ -162,8 +171,17 @@ impl RecentProjectsDelegate {
create_new_window,
render_paths,
reset_selected_match_index: true,
has_any_remote_projects: false,
}
}
pub fn set_workspaces(&mut self, workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>) {
self.workspaces = workspaces;
self.has_any_remote_projects = self
.workspaces
.iter()
.any(|(_, location)| matches!(location, SerializedWorkspaceLocation::Remote(_)));
}
}
impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
impl PickerDelegate for RecentProjectsDelegate {
@ -210,12 +228,18 @@ impl PickerDelegate for RecentProjectsDelegate {
.iter()
.enumerate()
.map(|(id, (_, location))| {
let combined_string = location
.paths()
.iter()
.map(|path| path.compact().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join("");
let combined_string = match location {
SerializedWorkspaceLocation::Local(paths) => paths
.paths()
.iter()
.map(|path| path.compact().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(""),
SerializedWorkspaceLocation::Remote(remote_project) => {
format!("{}{}", remote_project.dev_server_name, remote_project.path)
}
};
StringMatchCandidate::new(id, combined_string)
})
.collect::<Vec<_>>();
@ -261,30 +285,69 @@ impl PickerDelegate for RecentProjectsDelegate {
if workspace.database_id() == *candidate_workspace_id {
Task::ready(Ok(()))
} else {
let candidate_paths = candidate_workspace_location.paths().as_ref().clone();
if replace_current_window {
cx.spawn(move |workspace, mut cx| async move {
let continue_replacing = workspace
.update(&mut cx, |workspace, cx| {
workspace.prepare_to_close(true, cx)
})?
.await?;
if continue_replacing {
workspace
.update(&mut cx, |workspace, cx| {
workspace.open_workspace_for_paths(
true,
candidate_paths,
cx,
)
})?
.await
match candidate_workspace_location {
SerializedWorkspaceLocation::Local(paths) => {
let paths = paths.paths().as_ref().clone();
if replace_current_window {
cx.spawn(move |workspace, mut cx| async move {
let continue_replacing = workspace
.update(&mut cx, |workspace, cx| {
workspace.prepare_to_close(true, cx)
})?
.await?;
if continue_replacing {
workspace
.update(&mut cx, |workspace, cx| {
workspace
.open_workspace_for_paths(true, paths, cx)
})?
.await
} else {
Ok(())
}
})
} else {
Ok(())
workspace.open_workspace_for_paths(false, paths, cx)
}
})
} else {
workspace.open_workspace_for_paths(false, candidate_paths, cx)
}
//TODO support opening remote projects in the same window
SerializedWorkspaceLocation::Remote(remote_project) => {
let store = ::remote_projects::Store::global(cx).read(cx);
let Some(project_id) = store
.remote_project(remote_project.id)
.and_then(|p| p.project_id)
else {
let dev_server_name = remote_project.dev_server_name.clone();
return cx.spawn(|workspace, mut cx| async move {
let response =
cx.prompt(gpui::PromptLevel::Warning,
"Dev Server is offline",
Some(format!("Cannot connect to {}. To debug open the remote project settings.", dev_server_name).as_str()),
&["Ok", "Open Settings"]
).await?;
if response == 1 {
workspace.update(&mut cx, |workspace, cx| {
workspace.toggle_modal(cx, |cx| RemoteProjects::new(cx))
})?;
} else {
workspace.update(&mut cx, |workspace, cx| {
RecentProjects::open(workspace, true, cx);
})?;
}
Ok(())
})
};
if let Some(app_state) = AppState::global(cx).upgrade() {
let task =
workspace::join_remote_project(project_id, app_state, cx);
cx.spawn(|_, _| async move {
task.await?;
Ok(())
})
} else {
Task::ready(Err(anyhow::anyhow!("App state not found")))
}
}
}
}
})
@ -295,6 +358,14 @@ impl PickerDelegate for RecentProjectsDelegate {
fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
fn no_matches_text(&self, _cx: &mut WindowContext) -> SharedString {
if self.workspaces.is_empty() {
"Recently opened projects will show up here".into()
} else {
"No matches".into()
}
}
fn render_match(
&self,
ix: usize,
@ -308,9 +379,30 @@ impl PickerDelegate for RecentProjectsDelegate {
let (workspace_id, location) = &self.workspaces[hit.candidate_id];
let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
let is_remote = matches!(location, SerializedWorkspaceLocation::Remote(_));
let dev_server_status =
if let SerializedWorkspaceLocation::Remote(remote_project) = location {
let store = ::remote_projects::Store::global(cx).read(cx);
Some(
store
.remote_project(remote_project.id)
.and_then(|p| store.dev_server(p.dev_server_id))
.map(|s| s.status)
.unwrap_or_default(),
)
} else {
None
};
let mut path_start_offset = 0;
let (match_labels, paths): (Vec<_>, Vec<_>) = location
.paths()
let paths = match location {
SerializedWorkspaceLocation::Local(paths) => paths.paths(),
SerializedWorkspaceLocation::Remote(remote_project) => Arc::new(vec![PathBuf::from(
format!("{}:{}", remote_project.dev_server_name, remote_project.path),
)]),
};
let (match_labels, paths): (Vec<_>, Vec<_>) = paths
.iter()
.map(|path| {
let path = path.compact();
@ -323,22 +415,58 @@ impl PickerDelegate for RecentProjectsDelegate {
.unzip();
let highlighted_match = HighlightedMatchWithPaths {
match_label: HighlightedText::join(match_labels.into_iter().flatten(), ", "),
match_label: HighlightedText::join(match_labels.into_iter().flatten(), ", ").color(
if matches!(dev_server_status, Some(DevServerStatus::Offline)) {
Color::Disabled
} else {
Color::Default
},
),
paths,
};
Some(
ListItem::new(ix)
.selected(selected)
.inset(true)
.spacing(ListItemSpacing::Sparse)
.selected(selected)
.child({
let mut highlighted = highlighted_match.clone();
if !self.render_paths {
highlighted.paths.clear();
}
highlighted.render(cx)
})
.child(
h_flex()
.flex_grow()
.gap_3()
.when(self.has_any_remote_projects, |this| {
this.child(if is_remote {
// if disabled, Color::Disabled
let indicator_color = match dev_server_status {
Some(DevServerStatus::Online) => Color::Created,
Some(DevServerStatus::Offline) => Color::Hidden,
_ => unreachable!(),
};
IconWithIndicator::new(
Icon::new(IconName::Server).color(Color::Muted),
Some(Indicator::dot()),
)
.indicator_color(indicator_color)
.indicator_border_color(if selected {
Some(cx.theme().colors().element_selected)
} else {
None
})
.into_any_element()
} else {
Icon::new(IconName::Screen)
.color(Color::Muted)
.into_any_element()
})
})
.child({
let mut highlighted = highlighted_match.clone();
if !self.render_paths {
highlighted.paths.clear();
}
highlighted.render(cx)
}),
)
.when(!is_current_workspace, |el| {
let delete_button = div()
.child(
@ -369,6 +497,39 @@ impl PickerDelegate for RecentProjectsDelegate {
}),
)
}
fn render_footer(&self, cx: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
if !cx.has_flag::<feature_flags::Remoting>() {
return None;
}
Some(
h_flex()
.border_t_1()
.py_2()
.pr_2()
.border_color(cx.theme().colors().border)
.justify_end()
.gap_4()
.child(
ButtonLike::new("remote")
.when_some(KeyBinding::for_action(&OpenRemote, cx), |button, key| {
button.child(key)
})
.child(Label::new("Connect remote…").color(Color::Muted))
.on_click(|_, cx| cx.dispatch_action(OpenRemote.boxed_clone())),
)
.child(
ButtonLike::new("local")
.when_some(
KeyBinding::for_action(&workspace::Open, cx),
|button, key| button.child(key),
)
.child(Label::new("Open folder…").color(Color::Muted))
.on_click(|_, cx| cx.dispatch_action(workspace::Open.boxed_clone())),
)
.into_any(),
)
}
}
// Compute the highlighted text for the name and path
@ -406,6 +567,7 @@ fn highlights_for_path(
text: text.to_string(),
highlight_positions,
char_count,
color: Color::Default,
}
});
@ -415,6 +577,7 @@ fn highlights_for_path(
text: path_string.to_string(),
highlight_positions: path_positions,
char_count: path_char_count,
color: Color::Default,
},
)
}
@ -430,7 +593,7 @@ impl RecentProjectsDelegate {
.await
.unwrap_or_default();
this.update(&mut cx, move |picker, cx| {
picker.delegate.workspaces = workspaces;
picker.delegate.set_workspaces(workspaces);
picker.delegate.set_selected_index(ix - 1, cx);
picker.delegate.reset_selected_match_index = false;
picker.update_matches(picker.query(cx), cx)
@ -475,7 +638,7 @@ mod tests {
use gpui::{TestAppContext, WindowHandle};
use project::Project;
use serde_json::json;
use workspace::{open_paths, AppState};
use workspace::{open_paths, AppState, LocalPaths};
use super::*;
@ -539,10 +702,10 @@ mod tests {
positions: Vec::new(),
string: "fake candidate".to_string(),
}];
delegate.workspaces = vec![(
delegate.set_workspaces(vec![(
WorkspaceId::default(),
WorkspaceLocation::new(vec!["/test/path/"]),
)];
LocalPaths::new(vec!["/test/path/"]).into(),
)]);
});
})
.unwrap();