906 lines · 34.0 KB · Rust
RawDownload
pub mod disconnected_overlay;mod remote_servers;mod ssh_connections;use remote::SshConnectionOptions;pub use ssh_connections::open_ssh_project; use client::{DevServerProjectId, ProjectId};use disconnected_overlay::DisconnectedOverlay;use fuzzy::{StringMatch, StringMatchCandidate};use gpui::{    Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,    Subscription, Task, View, ViewContext, WeakView,};use itertools::Itertools;use ordered_float::OrderedFloat;use picker::{    highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},    Picker, PickerDelegate,};use remote_servers::reconnect_to_dev_server_project;pub use remote_servers::RemoteServerProjects;use rpc::proto::DevServerStatus;use serde::Deserialize;use settings::Settings;pub use ssh_connections::SshSettings;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, CloseIntent, ModalView, OpenOptions, SerializedWorkspaceLocation, Workspace,    WorkspaceId, WORKSPACE_DB,}; #[derive(PartialEq, Clone, Deserialize, Default)]pub struct OpenRecent {    #[serde(default = "default_create_new_window")]    pub create_new_window: bool,} fn default_create_new_window() -> bool {    true} gpui::impl_actions!(projects, [OpenRecent]);gpui::actions!(projects, [OpenRemote]); pub fn init(cx: &mut AppContext) {    SshSettings::register(cx);    cx.observe_new_views(RecentProjects::register).detach();    cx.observe_new_views(RemoteServerProjects::register)        .detach();    cx.observe_new_views(DisconnectedOverlay::register).detach();} pub struct RecentProjects {    pub picker: View<Picker<RecentProjectsDelegate>>,    rem_width: f32,    _subscription: Subscription,} impl ModalView for RecentProjects {} impl RecentProjects {    fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {        let picker = cx.new_view(|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, cx)            } else {                Picker::uniform_list(delegate, 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(|this, mut cx| async move {            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.set_workspaces(workspaces);                    picker.update_matches(picker.query(cx), cx)                })            })            .ok()        })        .detach();        Self {            picker,            rem_width,            _subscription,        }    }     fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {        workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {            let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {                Self::open(workspace, open_recent.create_new_window, cx);                return;            };             recent_projects.update(cx, |recent_projects, cx| {                recent_projects                    .picker                    .update(cx, |picker, cx| picker.cycle_selection(cx))            });        });        if workspace            .project()            .read(cx)            .dev_server_project_id()            .is_some()        {            workspace.register_action(|workspace, _: &workspace::Open, cx| {                if workspace.active_modal::<Self>(cx).is_some() {                    cx.propagate();                } else {                    Self::open(workspace, true, cx);                }            });        }    }     pub fn open(        workspace: &mut Workspace,        create_new_window: bool,        cx: &mut ViewContext<Workspace>,    ) {        let weak = cx.view().downgrade();        workspace.toggle_modal(cx, |cx| {            let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);             Self::new(delegate, 34., cx)        })    }} impl EventEmitter<DismissEvent> for RecentProjects {} impl FocusableView for RecentProjects {    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {        self.picker.focus_handle(cx)    }} impl Render for RecentProjects {    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {        v_flex()            .w(rems(self.rem_width))            .child(self.picker.clone())            .on_mouse_down_out(cx.listener(|this, _, cx| {                this.picker.update(cx, |this, cx| {                    this.cancel(&Default::default(), cx);                })            }))    }} pub struct RecentProjectsDelegate {    workspace: WeakView<Workspace>,    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_non_local_projects: bool,} impl RecentProjectsDelegate {    fn new(workspace: WeakView<Workspace>, create_new_window: bool, render_paths: bool) -> 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,        }    }     pub fn set_workspaces(&mut self, workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>) {        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, cx: &mut WindowContext) -> Arc<str> {        let (create_window, reuse_window) = if self.create_new_window {            (                cx.keystroke_text_for(&menu::Confirm),                cx.keystroke_text_for(&menu::SecondaryConfirm),            )        } else {            (                cx.keystroke_text_for(&menu::SecondaryConfirm),                cx.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, _cx: &mut ViewContext<Picker<Self>>) {        self.selected_match_index = ix;    }     fn update_matches(        &mut self,        query: String,        cx: &mut ViewContext<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, (_, location))| {                let combined_string = match location {                    SerializedWorkspaceLocation::Local(paths, order) => order                        .order()                        .iter()                        .zip(paths.paths().iter())                        .sorted_by_key(|(i, _)| *i)                        .map(|(_, path)| path.compact().to_string_lossy().into_owned())                        .collect::<Vec<_>>()                        .join(""),                    SerializedWorkspaceLocation::DevServer(dev_server_project) => {                        format!(                            "{}{}",                            dev_server_project.dev_server_name,                            dev_server_project.paths.join("")                        )                    }                    SerializedWorkspaceLocation::Ssh(ssh_project) => ssh_project                        .ssh_urls()                        .iter()                        .map(|path| path.to_string_lossy().to_string())                        .collect::<Vec<_>>()                        .join(""),                };                 StringMatchCandidate::new(id, combined_string)            })            .collect::<Vec<_>>();        self.matches = smol::block_on(fuzzy::match_strings(            candidates.as_slice(),            query,            smart_case,            100,            &Default::default(),            cx.background_executor().clone(),        ));        self.matches.sort_unstable_by_key(|m| m.candidate_id);         if self.reset_selected_match_index {            self.selected_match_index = self                .matches                .iter()                .enumerate()                .rev()                .max_by_key(|(_, m)| OrderedFloat(m.score))                .map(|(ix, _)| ix)                .unwrap_or(0);        }        self.reset_selected_match_index = true;        Task::ready(())    }     fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {        if let Some((selected_match, workspace)) = self            .matches            .get(self.selected_index())            .zip(self.workspace.upgrade())        {            let (candidate_workspace_id, candidate_workspace_location) =                &self.workspaces[selected_match.candidate_id];            let replace_current_window = if self.create_new_window {                secondary            } else {                !secondary            };            workspace                .update(cx, |workspace, cx| {                    if workspace.database_id() == Some(*candidate_workspace_id) {                        Task::ready(Ok(()))                    } else {                        match candidate_workspace_location {                            SerializedWorkspaceLocation::Local(paths, _) => {                                let paths = paths.paths().to_vec();                                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(CloseIntent::ReplaceWindow, cx)                                            })?                                            .await?;                                        if continue_replacing {                                            workspace                                                .update(&mut cx, |workspace, cx| {                                                    workspace                                                        .open_workspace_for_paths(true, paths, cx)                                                })?                                                .await                                        } else {                                            Ok(())                                        }                                    })                                } else {                                    workspace.open_workspace_for_paths(false, paths, cx)                                }                            }                            SerializedWorkspaceLocation::DevServer(dev_server_project) => {                                let store = dev_server_projects::Store::global(cx);                                let Some(project_id) = store.read(cx)                                    .dev_server_project(dev_server_project.id)                                    .and_then(|p| p.project_id)                                else {                                    let server = store.read(cx).dev_server_for_project(dev_server_project.id);                                    if server.is_some_and(|server| server.ssh_connection_string.is_some()) {                                        return reconnect_to_dev_server_project(cx.view().clone(), server.unwrap().clone(), dev_server_project.id, replace_current_window, cx);                                    } else {                                        let dev_server_name = dev_server_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| {                                                    let handle = cx.view().downgrade();                                                    workspace.toggle_modal(cx, |cx| RemoteServerProjects::new(cx, handle))                                                })?;                                            } else {                                                workspace.update(&mut cx, |workspace, cx| {                                                    RecentProjects::open(workspace, true, cx);                                                })?;                                            }                                            Ok(())                                        })                                    }                                };                                open_dev_server_project(replace_current_window, dev_server_project.id, project_id, cx)                        }                        SerializedWorkspaceLocation::Ssh(ssh_project) => {                            let app_state = workspace.app_state().clone();                             let replace_window = if replace_current_window {                                cx.window_handle().downcast::<Workspace>()                            } else {                                None                            };                             let open_options = OpenOptions {                                replace_window,                                ..Default::default()                            };                             let args = SshSettings::get_global(cx).args_for(&ssh_project.host, ssh_project.port, &ssh_project.user);                            let nickname = SshSettings::get_global(cx).nickname_for(&ssh_project.host, ssh_project.port, &ssh_project.user);                            let connection_options = SshConnectionOptions {                                host: ssh_project.host.clone(),                                username: ssh_project.user.clone(),                                port: ssh_project.port,                                password: None,                                args,                            };                             let paths = ssh_project.paths.iter().map(PathBuf::from).collect();                             cx.spawn(|_, mut cx| async move {                                open_ssh_project(connection_options, paths, app_state, open_options, nickname, &mut cx).await                            })                        }                    }                }                })            .detach_and_log_err(cx);            cx.emit(DismissEvent);        }    }     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,        selected: bool,        cx: &mut ViewContext<Picker<Self>>,    ) -> Option<Self::ListItem> {        let hit = self.matches.get(ix)?;         let (_, location) = self.workspaces.get(hit.candidate_id)?;         let dev_server_status =            if let SerializedWorkspaceLocation::DevServer(dev_server_project) = location {                let store = dev_server_projects::Store::global(cx).read(cx);                Some(                    store                        .dev_server_project(dev_server_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 paths = match location {            SerializedWorkspaceLocation::Local(paths, order) => Arc::new(                order                    .order()                    .iter()                    .zip(paths.paths().iter())                    .sorted_by_key(|(i, _)| **i)                    .map(|(_, path)| path.compact())                    .collect(),            ),            SerializedWorkspaceLocation::Ssh(ssh_project) => Arc::new(ssh_project.ssh_urls()),            SerializedWorkspaceLocation::DevServer(dev_server_project) => {                Arc::new(vec![PathBuf::from(format!(                    "{}:{}",                    dev_server_project.dev_server_name,                    dev_server_project.paths.join(", ")                ))])            }        };         let (match_labels, paths): (Vec<_>, Vec<_>) = paths            .iter()            .map(|path| {                let highlighted_text =                    highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);                 path_start_offset += highlighted_text.1.char_count;                highlighted_text            })            .unzip();         let highlighted_match = HighlightedMatchWithPaths {            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)                .child(                    h_flex()                        .flex_grow()                        .gap_3()                        .when(self.has_any_non_local_projects, |this| {

Lines 1–500 of 906.