1059 lines · 37.4 KB · Rust
RawDownload
mod dev_container;mod dev_container_suggest;pub mod disconnected_overlay;mod remote_connections;mod remote_servers;mod ssh_config; use std::path::PathBuf; #[cfg(target_os = "windows")]mod wsl_picker; use remote::RemoteConnectionOptions;pub use remote_connections::{RemoteConnectionModal, connect, open_remote_project}; use disconnected_overlay::DisconnectedOverlay;use fuzzy::{StringMatch, StringMatchCandidate};use gpui::{    Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,    Subscription, Task, WeakEntity, Window,};use ordered_float::OrderedFloat;use picker::{    Picker, PickerDelegate,    highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths},};pub use remote_connections::RemoteSettings;pub use remote_servers::RemoteServerProjects;use settings::Settings;use std::{path::Path, sync::Arc};use ui::{KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*, tooltip_container};use util::{ResultExt, paths::PathExt};use workspace::{    CloseIntent, HistoryManager, ModalView, OpenOptions, PathList, SerializedWorkspaceLocation,    WORKSPACE_DB, Workspace, WorkspaceId, notifications::DetachAndPromptErr,    with_active_or_new_workspace,};use zed_actions::{OpenDevContainer, OpenRecent, OpenRemote}; pub fn init(cx: &mut App) {    #[cfg(target_os = "windows")]    cx.on_action(|open_wsl: &zed_actions::wsl_actions::OpenFolderInWsl, cx| {        let create_new_window = open_wsl.create_new_window;        with_active_or_new_workspace(cx, move |workspace, window, cx| {            use gpui::PathPromptOptions;            use project::DirectoryLister;             let paths = workspace.prompt_for_open_path(                PathPromptOptions {                    files: true,                    directories: true,                    multiple: false,                    prompt: None,                },                DirectoryLister::Local(                    workspace.project().clone(),                    workspace.app_state().fs.clone(),                ),                window,                cx,            );             cx.spawn_in(window, async move |workspace, cx| {                use util::paths::SanitizedPath;                 let Some(paths) = paths.await.log_err().flatten() else {                    return;                };                 let paths = paths                    .into_iter()                    .filter_map(|path| SanitizedPath::new(&path).local_to_wsl())                    .collect::<Vec<_>>();                 if paths.is_empty() {                    let message = indoc::indoc! { r#"                        Invalid path specified when trying to open a folder inside WSL.                         Please note that Zed currently does not support opening network share folders inside wsl.                    "#};                     let _ = cx.prompt(gpui::PromptLevel::Critical, "Invalid path", Some(&message), &["Ok"]).await;                    return;                }                 workspace.update_in(cx, |workspace, window, cx| {                    workspace.toggle_modal(window, cx, |window, cx| {                        crate::wsl_picker::WslOpenModal::new(paths, create_new_window, window, cx)                    });                }).log_err();            })            .detach();        });    });     #[cfg(target_os = "windows")]    cx.on_action(|open_wsl: &zed_actions::wsl_actions::OpenWsl, cx| {        let create_new_window = open_wsl.create_new_window;        with_active_or_new_workspace(cx, move |workspace, window, cx| {            let handle = cx.entity().downgrade();            let fs = workspace.project().read(cx).fs().clone();            workspace.toggle_modal(window, cx, |window, cx| {                RemoteServerProjects::wsl(create_new_window, fs, window, handle, cx)            });        });    });     #[cfg(target_os = "windows")]    cx.on_action(|open_wsl: &remote::OpenWslPath, cx| {        let open_wsl = open_wsl.clone();        with_active_or_new_workspace(cx, move |workspace, window, cx| {            let fs = workspace.project().read(cx).fs().clone();            add_wsl_distro(fs, &open_wsl.distro, cx);            let open_options = OpenOptions {                replace_window: window.window_handle().downcast::<Workspace>(),                ..Default::default()            };             let app_state = workspace.app_state().clone();             cx.spawn_in(window, async move |_, cx| {                open_remote_project(                    RemoteConnectionOptions::Wsl(open_wsl.distro.clone()),                    open_wsl.paths,                    app_state,                    open_options,                    cx,                )                .await            })            .detach();        });    });     cx.on_action(|open_recent: &OpenRecent, cx| {        let create_new_window = open_recent.create_new_window;        with_active_or_new_workspace(cx, move |workspace, window, cx| {            let Some(recent_projects) = workspace.active_modal::<RecentProjects>(cx) else {                let focus_handle = workspace.focus_handle(cx);                RecentProjects::open(workspace, create_new_window, window, focus_handle, cx);                return;            };             recent_projects.update(cx, |recent_projects, cx| {                recent_projects                    .picker                    .update(cx, |picker, cx| picker.cycle_selection(window, cx))            });        });    });    cx.on_action(|open_remote: &OpenRemote, cx| {        let from_existing_connection = open_remote.from_existing_connection;        let create_new_window = open_remote.create_new_window;        with_active_or_new_workspace(cx, move |workspace, window, cx| {            if from_existing_connection {                cx.propagate();                return;            }            let handle = cx.entity().downgrade();            let fs = workspace.project().read(cx).fs().clone();            workspace.toggle_modal(window, cx, |window, cx| {                RemoteServerProjects::new(create_new_window, fs, window, handle, cx)            })        });    });     cx.observe_new(DisconnectedOverlay::register).detach();     cx.on_action(|_: &OpenDevContainer, cx| {        with_active_or_new_workspace(cx, move |workspace, window, cx| {            let app_state = workspace.app_state().clone();            let replace_window = window.window_handle().downcast::<Workspace>();             cx.spawn_in(window, async move |_, mut cx| {                let (connection, starting_dir) = match dev_container::start_dev_container(                    &mut cx,                    app_state.node_runtime.clone(),                )                .await                {                    Ok((c, s)) => (c, s),                    Err(e) => {                        log::error!("Failed to start Dev Container: {:?}", e);                        cx.prompt(                            gpui::PromptLevel::Critical,                            "Failed to start Dev Container",                            Some(&format!("{:?}", e)),                            &["Ok"],                        )                        .await                        .ok();                        return;                    }                };                 let result = open_remote_project(                    connection.into(),                    vec![starting_dir].into_iter().map(PathBuf::from).collect(),                    app_state,                    OpenOptions {                        replace_window,                        ..OpenOptions::default()                    },                    &mut cx,                )                .await;                 if let Err(e) = result {                    log::error!("Failed to connect: {e:#}");                    cx.prompt(                        gpui::PromptLevel::Critical,                        "Failed to connect",                        Some(&e.to_string()),                        &["Ok"],                    )                    .await                    .ok();                }            })            .detach();             let fs = workspace.project().read(cx).fs().clone();            let handle = cx.entity().downgrade();            workspace.toggle_modal(window, cx, |window, cx| {                RemoteServerProjects::new_dev_container(fs, window, handle, cx)            });        });    });     // Subscribe to worktree additions to suggest opening the project in a dev container    cx.observe_new(        |workspace: &mut Workspace, window: Option<&mut Window>, cx: &mut Context<Workspace>| {            let Some(window) = window else {                return;            };            cx.subscribe_in(                workspace.project(),                window,                move |_, project, event, window, cx| {                    if let project::Event::WorktreeUpdatedEntries(worktree_id, updated_entries) =                        event                    {                        dev_container_suggest::suggest_on_worktree_updated(                            *worktree_id,                            updated_entries,                            project,                            window,                            cx,                        );                    }                },            )            .detach();        },    )    .detach();} #[cfg(target_os = "windows")]pub fn add_wsl_distro(    fs: Arc<dyn project::Fs>,    connection_options: &remote::WslConnectionOptions,    cx: &App,) {    use gpui::ReadGlobal;    use settings::SettingsStore;     let distro_name = SharedString::from(&connection_options.distro_name);    let user = connection_options.user.clone();    SettingsStore::global(cx).update_settings_file(fs, move |setting, _| {        let connections = setting            .remote            .wsl_connections            .get_or_insert(Default::default());         if !connections            .iter()            .any(|conn| conn.distro_name == distro_name && conn.user == user)        {            use std::collections::BTreeSet;             connections.push(settings::WslConnection {                distro_name,                user,                projects: BTreeSet::new(),            })        }    });} pub struct RecentProjects {    pub picker: Entity<Picker<RecentProjectsDelegate>>,    rem_width: f32,    _subscription: Subscription,} impl ModalView for RecentProjects {} impl RecentProjects {    fn new(        delegate: RecentProjectsDelegate,        rem_width: f32,        window: &mut Window,        cx: &mut Context<Self>,    ) -> Self {        let picker = cx.new(|cx| {            // We want to use a list when we render paths, because the items can have different heights (multiple paths).            if delegate.render_paths {                Picker::list(delegate, window, cx)            } else {                Picker::uniform_list(delegate, window, cx)            }        });        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));        // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap        // out workspace locations once the future runs to completion.        cx.spawn_in(window, async move |this, cx| {            let workspaces = WORKSPACE_DB                .recent_workspaces_on_disk()                .await                .log_err()                .unwrap_or_default();            this.update_in(cx, move |this, window, cx| {                this.picker.update(cx, move |picker, cx| {                    picker.delegate.set_workspaces(workspaces);                    picker.update_matches(picker.query(cx), window, cx)                })            })            .ok()        })        .detach();        Self {            picker,            rem_width,            _subscription,        }    }     pub fn open(        workspace: &mut Workspace,        create_new_window: bool,        window: &mut Window,        focus_handle: FocusHandle,        cx: &mut Context<Workspace>,    ) {        let weak = cx.entity().downgrade();        workspace.toggle_modal(window, cx, |window, cx| {            let delegate = RecentProjectsDelegate::new(weak, create_new_window, true, focus_handle);             Self::new(delegate, 34., window, cx)        })    }     pub fn popover(        workspace: WeakEntity<Workspace>,        create_new_window: bool,        focus_handle: FocusHandle,        window: &mut Window,        cx: &mut App,    ) -> Entity<Self> {        cx.new(|cx| {            let delegate =                RecentProjectsDelegate::new(workspace, create_new_window, true, focus_handle);            let list = Self::new(delegate, 34., window, cx);            list.picker.focus_handle(cx).focus(window, cx);            list        })    }} impl EventEmitter<DismissEvent> for RecentProjects {} impl Focusable for RecentProjects {    fn focus_handle(&self, cx: &App) -> FocusHandle {        self.picker.focus_handle(cx)    }} impl Render for RecentProjects {    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {        v_flex()            .key_context("RecentProjects")            .w(rems(self.rem_width))            .child(self.picker.clone())            .on_mouse_down_out(cx.listener(|this, _, window, cx| {                this.picker.update(cx, |this, cx| {                    this.cancel(&Default::default(), window, cx);                })            }))    }} pub struct RecentProjectsDelegate {    workspace: WeakEntity<Workspace>,    workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation, PathList)>,    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_non_local_projects: bool,    focus_handle: FocusHandle,} impl RecentProjectsDelegate {    fn new(        workspace: WeakEntity<Workspace>,        create_new_window: bool,        render_paths: bool,        focus_handle: FocusHandle,    ) -> Self {        Self {            workspace,            workspaces: Vec::new(),            selected_match_index: 0,            matches: Default::default(),            create_new_window,            render_paths,            reset_selected_match_index: true,            has_any_non_local_projects: false,            focus_handle,        }    }     pub fn set_workspaces(        &mut self,        workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation, PathList)>,    ) {        self.workspaces = workspaces;        self.has_any_non_local_projects = !self            .workspaces            .iter()            .all(|(_, location, _)| matches!(location, SerializedWorkspaceLocation::Local));    }}impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}impl PickerDelegate for RecentProjectsDelegate {    type ListItem = ListItem;     fn placeholder_text(&self, window: &mut Window, _: &mut App) -> Arc<str> {        let (create_window, reuse_window) = if self.create_new_window {            (                window.keystroke_text_for(&menu::Confirm),                window.keystroke_text_for(&menu::SecondaryConfirm),            )        } else {            (                window.keystroke_text_for(&menu::SecondaryConfirm),                window.keystroke_text_for(&menu::Confirm),            )        };        Arc::from(format!(            "{reuse_window} reuses this window, {create_window} opens a new one",        ))    }     fn match_count(&self) -> usize {        self.matches.len()    }     fn selected_index(&self) -> usize {        self.selected_match_index    }     fn set_selected_index(        &mut self,        ix: usize,        _window: &mut Window,        _cx: &mut Context<Picker<Self>>,    ) {        self.selected_match_index = ix;    }     fn update_matches(        &mut self,        query: String,        _: &mut Window,        cx: &mut Context<Picker<Self>>,    ) -> gpui::Task<()> {        let query = query.trim_start();        let smart_case = query.chars().any(|c| c.is_uppercase());        let candidates = self            .workspaces            .iter()            .enumerate()            .filter(|(_, (id, _, _))| !self.is_current_workspace(*id, cx))            .map(|(id, (_, _, paths))| {                let combined_string = paths                    .ordered_paths()                    .map(|path| path.compact().to_string_lossy().into_owned())                    .collect::<Vec<_>>()                    .join("");                StringMatchCandidate::new(id, &combined_string)            })            .collect::<Vec<_>>();        self.matches = smol::block_on(fuzzy::match_strings(            candidates.as_slice(),            query,            smart_case,

Lines 1–500 of 1059.