logiguard fork: GPUI xdg-activation keyboard-focus serial fix
Some checks failed
Update All Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Triage Project Sync (#84) / Sync triage project (push) Has been cancelled
release_nightly / notify_on_failure (push) Has been cancelled
release_nightly / check_style (push) Has been cancelled
release_nightly / run_tests_windows (push) Has been cancelled
release_nightly / clippy_windows (push) Has been cancelled
release_nightly / bundle_linux_aarch64 (push) Has been cancelled
release_nightly / bundle_linux_x86_64 (push) Has been cancelled
release_nightly / bundle_mac_aarch64 (push) Has been cancelled
release_nightly / bundle_mac_x86_64 (push) Has been cancelled
release_nightly / bundle_windows_aarch64 (push) Has been cancelled
release_nightly / bundle_windows_x86_64 (push) Has been cancelled
release_nightly / build_nix_linux_x86_64 (push) Has been cancelled
release_nightly / build_nix_mac_aarch64 (push) Has been cancelled
release_nightly / update_nightly_tag (push) Has been cancelled
Hotfix Review Monitor / check-hotfix-reviews (push) Has been cancelled
Stale PR Review Reminder / check-stale-prs (push) Has been cancelled
Update Weekly Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Bump collab-staging Tag / update-collab-staging-tag (push) Has been cancelled
compliance_check / scheduled_compliance_check (push) Has been cancelled
Some checks failed
Update All Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Triage Project Sync (#84) / Sync triage project (push) Has been cancelled
release_nightly / notify_on_failure (push) Has been cancelled
release_nightly / check_style (push) Has been cancelled
release_nightly / run_tests_windows (push) Has been cancelled
release_nightly / clippy_windows (push) Has been cancelled
release_nightly / bundle_linux_aarch64 (push) Has been cancelled
release_nightly / bundle_linux_x86_64 (push) Has been cancelled
release_nightly / bundle_mac_aarch64 (push) Has been cancelled
release_nightly / bundle_mac_x86_64 (push) Has been cancelled
release_nightly / bundle_windows_aarch64 (push) Has been cancelled
release_nightly / bundle_windows_x86_64 (push) Has been cancelled
release_nightly / build_nix_linux_x86_64 (push) Has been cancelled
release_nightly / build_nix_mac_aarch64 (push) Has been cancelled
release_nightly / update_nightly_tag (push) Has been cancelled
Hotfix Review Monitor / check-hotfix-reviews (push) Has been cancelled
Stale PR Review Reminder / check-stale-prs (push) Has been cancelled
Update Weekly Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Bump collab-staging Tag / update-collab-staging-tag (push) Has been cancelled
compliance_check / scheduled_compliance_check (push) Has been cancelled
Single-commit orphan branch: full zed-industries/zed @ 8c74db0 source tree with a 3-file patch applied (no upstream history). Patch (crates/gpui_linux/src/linux/wayland/): - serial.rs: add SerialKind::KeyboardEnter - client.rs: store wl_keyboard.enter serial; add latest_serial_of() - window.rs: activate() uses keyboard-enter serial (Mutter focus gate) Mutter honors window activation only when the token carries the keyboard- focus serial from wl_keyboard.enter; GPUI used a stale mouse-press serial. See docs/tray-window-focus-wayland.md in logiguard. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
26
crates/snippet_provider/src/extension_snippet.rs
Normal file
26
crates/snippet_provider/src/extension_snippet.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use extension::{ExtensionHostProxy, ExtensionSnippetProxy};
|
||||
use gpui::App;
|
||||
|
||||
use crate::SnippetRegistry;
|
||||
|
||||
pub fn init(cx: &mut App) {
|
||||
let proxy = ExtensionHostProxy::default_global(cx);
|
||||
proxy.register_snippet_proxy(SnippetRegistryProxy {
|
||||
snippet_registry: SnippetRegistry::global(cx),
|
||||
});
|
||||
}
|
||||
|
||||
struct SnippetRegistryProxy {
|
||||
snippet_registry: Arc<SnippetRegistry>,
|
||||
}
|
||||
|
||||
impl ExtensionSnippetProxy for SnippetRegistryProxy {
|
||||
fn register_snippet(&self, path: &PathBuf, snippet_contents: &str) -> Result<()> {
|
||||
self.snippet_registry
|
||||
.register_snippets(path, snippet_contents)
|
||||
}
|
||||
}
|
||||
78
crates/snippet_provider/src/format.rs
Normal file
78
crates/snippet_provider/src/format.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use collections::HashMap;
|
||||
use schemars::{JsonSchema, json_schema};
|
||||
use serde::Deserialize;
|
||||
use std::borrow::Cow;
|
||||
use util::schemars::{AllowTrailingCommas, DefaultDenyUnknownFields};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct VsSnippetsFile {
|
||||
#[serde(flatten)]
|
||||
pub(crate) snippets: HashMap<String, VsCodeSnippet>,
|
||||
}
|
||||
|
||||
impl VsSnippetsFile {
|
||||
pub fn generate_json_schema() -> serde_json::Value {
|
||||
let schema = schemars::generate::SchemaSettings::draft2019_09()
|
||||
.with_transform(DefaultDenyUnknownFields)
|
||||
.with_transform(AllowTrailingCommas)
|
||||
.into_generator()
|
||||
.root_schema_for::<Self>();
|
||||
|
||||
serde_json::to_value(schema).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for VsSnippetsFile {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"VsSnippetsFile".into()
|
||||
}
|
||||
|
||||
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
let snippet_schema = generator.subschema_for::<VsCodeSnippet>();
|
||||
json_schema!({
|
||||
"type": "object",
|
||||
"additionalProperties": snippet_schema
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum ListOrDirect {
|
||||
Single(String),
|
||||
List(Vec<String>),
|
||||
}
|
||||
|
||||
impl From<ListOrDirect> for Vec<String> {
|
||||
fn from(list: ListOrDirect) -> Self {
|
||||
match list {
|
||||
ListOrDirect::Single(entry) => vec![entry],
|
||||
ListOrDirect::List(entries) => entries,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ListOrDirect {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
match self {
|
||||
Self::Single(v) => v.to_owned(),
|
||||
Self::List(v) => v.join("\n"),
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, JsonSchema)]
|
||||
pub(crate) struct VsCodeSnippet {
|
||||
/// The snippet prefix used to decide whether a completion menu should be shown.
|
||||
pub(crate) prefix: Option<ListOrDirect>,
|
||||
|
||||
/// The snippet content. Use `$1` and `${1:defaultText}` to define cursor positions and `$0` for final cursor position.
|
||||
pub(crate) body: ListOrDirect,
|
||||
|
||||
/// The snippet description displayed inside the completion menu.
|
||||
pub(crate) description: Option<ListOrDirect>,
|
||||
}
|
||||
303
crates/snippet_provider/src/lib.rs
Normal file
303
crates/snippet_provider/src/lib.rs
Normal file
@@ -0,0 +1,303 @@
|
||||
mod extension_snippet;
|
||||
pub mod format;
|
||||
mod registry;
|
||||
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use format::VsSnippetsFile;
|
||||
use fs::Fs;
|
||||
use futures::stream::StreamExt;
|
||||
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, Task, WeakEntity};
|
||||
pub use registry::*;
|
||||
use util::ResultExt;
|
||||
|
||||
pub fn init(cx: &mut App) {
|
||||
SnippetRegistry::init_global(cx);
|
||||
extension_snippet::init(cx);
|
||||
}
|
||||
|
||||
/// Language name, or `None` if the snippet file is global.
|
||||
type SnippetKind = Option<String>;
|
||||
fn file_stem_to_key(stem: &str) -> SnippetKind {
|
||||
if stem == "snippets" {
|
||||
None
|
||||
} else {
|
||||
Some(stem.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_to_snippets(
|
||||
file_contents: VsSnippetsFile,
|
||||
source: &Path,
|
||||
) -> impl Iterator<Item = Result<Arc<Snippet>>> {
|
||||
file_contents
|
||||
.snippets
|
||||
.into_iter()
|
||||
.map(move |(name, snippet)| {
|
||||
let snippet_name = name.clone();
|
||||
let prefixes = snippet
|
||||
.prefix
|
||||
.map_or_else(move || vec![snippet_name], |prefixes| prefixes.into());
|
||||
let description = snippet
|
||||
.description
|
||||
.map(|description| description.to_string());
|
||||
let body = snippet.body.to_string();
|
||||
match snippet::Snippet::parse(&body) {
|
||||
Ok(_) => Ok(Arc::new(Snippet {
|
||||
body,
|
||||
prefix: prefixes,
|
||||
description,
|
||||
name,
|
||||
})),
|
||||
Err(e) => Err(anyhow::anyhow!(
|
||||
"Invalid snippet '{name}' in {source:?}: {e:#}"
|
||||
)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Snippet with all of the metadata
|
||||
#[derive(Debug)]
|
||||
pub struct Snippet {
|
||||
pub prefix: Vec<String>,
|
||||
pub body: String,
|
||||
pub description: Option<String>,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
async fn process_updates(
|
||||
this: WeakEntity<SnippetProvider>,
|
||||
entries: Vec<PathBuf>,
|
||||
mut cx: AsyncApp,
|
||||
) -> Result<()> {
|
||||
let fs = this.read_with(&cx, |this, _| this.fs.clone())?;
|
||||
for entry_path in entries {
|
||||
if entry_path
|
||||
.extension()
|
||||
.is_none_or(|extension| extension != "json")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let entry_metadata = fs.metadata(&entry_path).await;
|
||||
// Entry could have been removed, in which case we should no longer show completions for it.
|
||||
let entry_exists = entry_metadata.is_ok();
|
||||
if entry_metadata.is_ok_and(|entry| entry.is_some_and(|e| e.is_dir)) {
|
||||
// Don't process dirs.
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = entry_path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
let key = file_stem_to_key(stem);
|
||||
|
||||
let contents = if entry_exists {
|
||||
fs.load(&entry_path).await.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
this.update(&mut cx, move |this, _| {
|
||||
let snippets_of_kind = this.snippets.entry(key).or_default();
|
||||
if entry_exists {
|
||||
let Some(file_contents) = contents else {
|
||||
return;
|
||||
};
|
||||
let Ok(as_json) = serde_json_lenient::from_str::<VsSnippetsFile>(&file_contents)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let snippets = file_to_snippets(as_json, entry_path.as_path());
|
||||
*snippets_of_kind.entry(entry_path).or_default() =
|
||||
snippets.filter_map(Result::log_err).collect();
|
||||
} else {
|
||||
snippets_of_kind.remove(&entry_path);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn initial_scan(
|
||||
this: WeakEntity<SnippetProvider>,
|
||||
path: Arc<Path>,
|
||||
cx: AsyncApp,
|
||||
) -> Result<()> {
|
||||
let fs = this.read_with(&cx, |this, _| this.fs.clone())?;
|
||||
let entries = fs.read_dir(&path).await;
|
||||
if let Ok(entries) = entries {
|
||||
let entries = entries
|
||||
.collect::<Vec<_>>()
|
||||
.await
|
||||
.into_iter()
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
process_updates(this, entries, cx).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct SnippetProvider {
|
||||
fs: Arc<dyn Fs>,
|
||||
snippets: HashMap<SnippetKind, BTreeMap<PathBuf, Vec<Arc<Snippet>>>>,
|
||||
watch_tasks: Vec<Task<Result<()>>>,
|
||||
}
|
||||
|
||||
// Watches global snippet directory, is created just once and reused across multiple projects
|
||||
struct GlobalSnippetWatcher(Entity<SnippetProvider>);
|
||||
|
||||
impl GlobalSnippetWatcher {
|
||||
fn new(fs: Arc<dyn Fs>, cx: &mut App) -> Self {
|
||||
let global_snippets_dir = paths::snippets_dir();
|
||||
let provider = cx.new(|_cx| SnippetProvider {
|
||||
fs,
|
||||
snippets: Default::default(),
|
||||
watch_tasks: vec![],
|
||||
});
|
||||
provider.update(cx, |this, cx| this.watch_directory(global_snippets_dir, cx));
|
||||
Self(provider)
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui::Global for GlobalSnippetWatcher {}
|
||||
|
||||
impl SnippetProvider {
|
||||
pub fn new(fs: Arc<dyn Fs>, dirs_to_watch: BTreeSet<PathBuf>, cx: &mut App) -> Entity<Self> {
|
||||
cx.new(move |cx| {
|
||||
if !cx.has_global::<GlobalSnippetWatcher>() {
|
||||
let global_watcher = GlobalSnippetWatcher::new(fs.clone(), cx);
|
||||
cx.set_global(global_watcher);
|
||||
}
|
||||
let mut this = Self {
|
||||
fs,
|
||||
watch_tasks: Vec::new(),
|
||||
snippets: Default::default(),
|
||||
};
|
||||
|
||||
for dir in dirs_to_watch {
|
||||
this.watch_directory(&dir, cx);
|
||||
}
|
||||
|
||||
this
|
||||
})
|
||||
}
|
||||
|
||||
/// Add directory to be watched for content changes
|
||||
fn watch_directory(&mut self, path: &Path, cx: &Context<Self>) {
|
||||
let path: Arc<Path> = Arc::from(path);
|
||||
|
||||
self.watch_tasks.push(cx.spawn(async move |this, cx| {
|
||||
let fs = this.read_with(cx, |this, _| this.fs.clone())?;
|
||||
let watched_path = path.clone();
|
||||
let watcher = fs.watch(&watched_path, Duration::from_secs(1));
|
||||
initial_scan(this.clone(), path, cx.clone()).await?;
|
||||
|
||||
let (mut entries, _) = watcher.await;
|
||||
while let Some(entries) = entries.next().await {
|
||||
process_updates(
|
||||
this.clone(),
|
||||
entries.into_iter().map(|event| event.path).collect(),
|
||||
cx.clone(),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
fn lookup_snippets<'a, const LOOKUP_GLOBALS: bool>(
|
||||
&'a self,
|
||||
language: &'a SnippetKind,
|
||||
cx: &App,
|
||||
) -> Vec<Arc<Snippet>> {
|
||||
let mut user_snippets: Vec<_> = self
|
||||
.snippets
|
||||
.get(language)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.into_values()
|
||||
.flat_map(|snippets| snippets.into_iter())
|
||||
.collect();
|
||||
if LOOKUP_GLOBALS {
|
||||
if let Some(global_watcher) = cx.try_global::<GlobalSnippetWatcher>() {
|
||||
user_snippets.extend(
|
||||
global_watcher
|
||||
.0
|
||||
.read(cx)
|
||||
.lookup_snippets::<false>(language, cx),
|
||||
);
|
||||
}
|
||||
|
||||
let Some(registry) = SnippetRegistry::try_global(cx) else {
|
||||
return user_snippets;
|
||||
};
|
||||
|
||||
let registry_snippets = registry.get_snippets(language);
|
||||
user_snippets.extend(registry_snippets);
|
||||
}
|
||||
|
||||
user_snippets
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn add_snippet_for_test(
|
||||
&mut self,
|
||||
language: SnippetKind,
|
||||
path: PathBuf,
|
||||
snippet: Vec<Arc<Snippet>>,
|
||||
) {
|
||||
self.snippets
|
||||
.entry(language)
|
||||
.or_default()
|
||||
.insert(path, snippet);
|
||||
}
|
||||
|
||||
pub fn snippets_for(&self, language: SnippetKind, cx: &App) -> Vec<Arc<Snippet>> {
|
||||
let mut requested_snippets = self.lookup_snippets::<true>(&language, cx);
|
||||
|
||||
if language.is_some() {
|
||||
// Look up global snippets as well.
|
||||
requested_snippets.extend(self.lookup_snippets::<true>(&None, cx));
|
||||
}
|
||||
requested_snippets
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use fs::FakeFs;
|
||||
use gpui;
|
||||
use gpui::TestAppContext;
|
||||
use indoc::indoc;
|
||||
|
||||
#[gpui::test]
|
||||
fn test_lookup_snippets_dup_registry_snippets(cx: &mut TestAppContext) {
|
||||
let fs = FakeFs::new(cx.background_executor.clone());
|
||||
cx.update(|cx| {
|
||||
SnippetRegistry::init_global(cx);
|
||||
SnippetRegistry::global(cx)
|
||||
.register_snippets(
|
||||
"ruby".as_ref(),
|
||||
indoc! {r#"
|
||||
{
|
||||
"Log to console": {
|
||||
"prefix": "log",
|
||||
"body": ["console.info(\"Hello, ${1:World}!\")", "$0"],
|
||||
"description": "Logs to console"
|
||||
}
|
||||
}
|
||||
"#},
|
||||
)
|
||||
.unwrap();
|
||||
let provider = SnippetProvider::new(fs.clone(), Default::default(), cx);
|
||||
cx.update_entity(&provider, |provider, cx| {
|
||||
assert_eq!(1, provider.snippets_for(Some("ruby".to_owned()), cx).len());
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
57
crates/snippet_provider/src/registry.rs
Normal file
57
crates/snippet_provider/src/registry.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
use anyhow::Result;
|
||||
use collections::HashMap;
|
||||
use gpui::{App, Global, ReadGlobal, UpdateGlobal};
|
||||
use parking_lot::RwLock;
|
||||
use util::ResultExt;
|
||||
|
||||
use crate::{Snippet, SnippetKind, file_stem_to_key};
|
||||
|
||||
struct GlobalSnippetRegistry(Arc<SnippetRegistry>);
|
||||
|
||||
impl Global for GlobalSnippetRegistry {}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SnippetRegistry {
|
||||
snippets: RwLock<HashMap<SnippetKind, Vec<Arc<Snippet>>>>,
|
||||
}
|
||||
|
||||
impl SnippetRegistry {
|
||||
pub fn global(cx: &App) -> Arc<Self> {
|
||||
GlobalSnippetRegistry::global(cx).0.clone()
|
||||
}
|
||||
|
||||
pub fn try_global(cx: &App) -> Option<Arc<Self>> {
|
||||
cx.try_global::<GlobalSnippetRegistry>()
|
||||
.map(|registry| registry.0.clone())
|
||||
}
|
||||
|
||||
pub fn init_global(cx: &mut App) {
|
||||
GlobalSnippetRegistry::set_global(cx, GlobalSnippetRegistry(Arc::new(Self::new())))
|
||||
}
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
snippets: RwLock::new(HashMap::default()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_snippets(&self, file_path: &Path, contents: &str) -> Result<()> {
|
||||
let snippets_in_file: crate::format::VsSnippetsFile =
|
||||
serde_json_lenient::from_str(contents)?;
|
||||
let kind = file_path
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str().and_then(file_stem_to_key));
|
||||
let snippets = crate::file_to_snippets(snippets_in_file, file_path);
|
||||
self.snippets
|
||||
.write()
|
||||
.insert(kind, snippets.filter_map(Result::log_err).collect());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_snippets(&self, kind: &SnippetKind) -> Vec<Arc<Snippet>> {
|
||||
self.snippets.read().get(kind).cloned().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user