дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-25 02:44:37 +02:00
Порівняти коміти
13
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
84abdc1885 | ||
|
|
3100aa2c00 | ||
|
|
52360c72d2 | ||
|
|
7fd330912a | ||
|
|
eaca68f263 | ||
|
|
4b5ef7069c | ||
|
|
2cd16a723d | ||
|
|
71c0515af6 | ||
|
|
b473876d59 | ||
|
|
d7886bab45 | ||
|
|
dd370654cb | ||
|
|
e3c7f362c4 | ||
|
|
02addfa2c5 |
No files matched your search
@@ -22,4 +22,4 @@ tempfile.workspace = true
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_Security", "Win32_System_Registry", "Win32_Foundation"] }
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_Security", "Win32_System_Registry", "Win32_Foundation", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Threading"] }
|
||||
@@ -43,19 +43,21 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
/// - Windows: `taskkill /T /F`, which walks the tree from the child's process id.
|
||||
/// - Windows: `taskkill /T /F`, which walks the tree from the child's process id, then a
|
||||
/// wait for what the child started to be gone.
|
||||
pub fn kill_tree(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
signal_group(child, libc::SIGKILL);
|
||||
#[cfg(windows)]
|
||||
taskkill_tree(child);
|
||||
taskkill_tree_of(child.id());
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// [`kill_tree`] for a child known by its process id (a `tokio` child): `SIGKILL` to its
|
||||
/// process group (spawn it with [`own_group`]) or `taskkill /T /F`. Call it before the child
|
||||
/// is reaped, so the id still names it. The child itself is left to its owner to kill and reap.
|
||||
/// process group (spawn it with [`own_group`]) or `taskkill /T /F` and a wait for what the
|
||||
/// child started to be gone. Call it before the child is reaped, so the id still names it.
|
||||
/// The child itself is left to its owner to kill and reap.
|
||||
pub fn kill_tree_of(pid: u32) {
|
||||
#[cfg(unix)]
|
||||
if let Ok(pid) = libc::pid_t::try_from(pid) {
|
||||
@@ -65,15 +67,7 @@ pub fn kill_tree_of(pid: u32) {
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut taskkill = Command::new("taskkill");
|
||||
prepare(&mut taskkill)
|
||||
.args(["/T", "/F", "/PID", &pid.to_string()])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let _ = taskkill.status();
|
||||
}
|
||||
taskkill_tree_of(pid);
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let _ = pid;
|
||||
}
|
||||
@@ -106,15 +100,107 @@ fn signal_group(child: &Child, signal: libc::c_int) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long killing a tree waits for the processes the child started to be gone.
|
||||
#[cfg(windows)]
|
||||
fn taskkill_tree(child: &Child) {
|
||||
const TREE_EXIT_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// `taskkill /T /F` from `pid`, then waits (up to [`TREE_EXIT_WAIT`]) until what the child
|
||||
/// started is gone: termination is asynchronous, and until a process is gone the files it
|
||||
/// holds open can't be opened or deleted. The child itself is left to its owner to reap.
|
||||
#[cfg(windows)]
|
||||
fn taskkill_tree_of(pid: u32) {
|
||||
let started = windows_tree::descendants(pid);
|
||||
let mut taskkill = Command::new("taskkill");
|
||||
prepare(&mut taskkill)
|
||||
.args(["/T", "/F", "/PID", &child.id().to_string()])
|
||||
.args(["/T", "/F", "/PID", &pid.to_string()])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let _ = taskkill.status();
|
||||
windows_tree::wait_all(&started, TREE_EXIT_WAIT);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_tree {
|
||||
use std::collections::HashSet;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
use windows_sys::Win32::Foundation::{FILETIME, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject,
|
||||
};
|
||||
|
||||
/// Every process `root` started, directly or not, opened so it can be waited for. A
|
||||
/// parent's id is reused once it is gone, so a process counts only if it started after
|
||||
/// its parent.
|
||||
pub(super) fn descendants(root: u32) -> Vec<OwnedHandle> {
|
||||
let Some(root_started) = open(root).as_ref().and_then(started) else { return Vec::new() };
|
||||
let processes = processes();
|
||||
let mut seen = HashSet::from([root]);
|
||||
let mut parents = vec![(root, root_started)];
|
||||
let mut found = Vec::new();
|
||||
while let Some((parent, parent_started)) = parents.pop() {
|
||||
for &(pid, ppid) in &processes {
|
||||
if ppid != parent || !seen.insert(pid) {
|
||||
continue;
|
||||
}
|
||||
let Some(handle) = open(pid) else { continue };
|
||||
if let Some(at) = started(&handle).filter(|&at| at >= parent_started) {
|
||||
parents.push((pid, at));
|
||||
found.push(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
pub(super) fn wait_all(processes: &[OwnedHandle], within: Duration) {
|
||||
let until = Instant::now() + within;
|
||||
for process in processes {
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
// SAFETY: a live process handle opened with SYNCHRONIZE access.
|
||||
unsafe { WaitForSingleObject(process.as_raw_handle(), left.as_millis().min(u32::MAX as u128 - 1) as u32) };
|
||||
}
|
||||
}
|
||||
|
||||
/// (process id, parent process id) of every running process.
|
||||
fn processes() -> Vec<(u32, u32)> {
|
||||
let mut out = Vec::new();
|
||||
// SAFETY: a snapshot handle owned here and an entry sized as the API requires.
|
||||
unsafe {
|
||||
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||
if snapshot.is_null() || snapshot == INVALID_HANDLE_VALUE {
|
||||
return out;
|
||||
}
|
||||
let snapshot = OwnedHandle::from_raw_handle(snapshot);
|
||||
let mut entry = PROCESSENTRY32W { dwSize: size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
|
||||
let mut more = Process32FirstW(snapshot.as_raw_handle(), &mut entry);
|
||||
while more != 0 {
|
||||
out.push((entry.th32ProcessID, entry.th32ParentProcessID));
|
||||
more = Process32NextW(snapshot.as_raw_handle(), &mut entry);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn open(pid: u32) -> Option<OwnedHandle> {
|
||||
// SAFETY: plain call; a non-null result is a process handle owned by the caller.
|
||||
let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
|
||||
// SAFETY: as above.
|
||||
(!handle.is_null()).then(|| unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
|
||||
/// When the process started, in 100 ns ticks since 1601.
|
||||
fn started(process: &OwnedHandle) -> Option<u64> {
|
||||
let (mut created, mut exited, mut kernel, mut user) =
|
||||
(FILETIME::default(), FILETIME::default(), FILETIME::default(), FILETIME::default());
|
||||
// SAFETY: a live process handle opened with query access; four out-parameters.
|
||||
let ok = unsafe { GetProcessTimes(process.as_raw_handle(), &mut created, &mut exited, &mut kernel, &mut user) };
|
||||
(ok != 0).then(|| (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime))
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives `cmd` the host's environment back when the IDE runs from an AppImage. `AppRun` and
|
||||
|
||||
@@ -923,6 +923,7 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegist
|
||||
ui_mode: None,
|
||||
framework_ui_modes: Vec::new(),
|
||||
formatter: None,
|
||||
scratch_template: None,
|
||||
tree_sitter: None,
|
||||
language_servers: vec![],
|
||||
debugger: Some(ide_language::DebuggerConfig {
|
||||
|
||||
@@ -33,7 +33,9 @@ usage: openidea-plugin <command> [options]
|
||||
|
||||
commands:
|
||||
new <dir> [--template T] [--id ID] [--name NAME] [--sdk PATH]
|
||||
create a plugin; T = command (default), theme, icon-theme, language
|
||||
create a plugin; T = command (default), theme, icon-theme, language. A Rust
|
||||
plugin depends on the SDK of this tool's release (git); --sdk PATH uses a
|
||||
local sdk/rust/openidea-plugin instead
|
||||
build [dir] [--debug] compile a Rust plugin to dist/plugin.wasm and check it
|
||||
check [dir|package] validate the package (folder or .oiplugin) as the IDE would install it
|
||||
link [dir] load the folder in the IDE without installing it
|
||||
@@ -177,7 +179,7 @@ fn cmd_new(args: &[String]) -> Result<(), String> {
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let dir = canonical(&dir)?;
|
||||
let sdk = match template {
|
||||
templates::Template::Command => Some(sdk_path(a.value("sdk"), &dir)?),
|
||||
templates::Template::Command => Some(sdk_dependency(a.value("sdk"), &dir)?),
|
||||
_ => None,
|
||||
};
|
||||
let vars = templates::Vars { id: &id, name: &name, sdk: sdk.as_deref() };
|
||||
@@ -232,12 +234,16 @@ fn title_case(s: &str) -> String {
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// The SDK dependency path written into a new plugin's Cargo.toml: `--sdk`,
|
||||
/// or the SDK of the source tree this tool was built from.
|
||||
fn sdk_path(explicit: Option<&str>, plugin_dir: &Path) -> Result<String, String> {
|
||||
/// The SDK dependency written into a new plugin's Cargo.toml: by path with `--sdk`, or
|
||||
/// when the plugin is inside the source tree this tool was built from; otherwise the
|
||||
/// repository at this tool's release tag.
|
||||
fn sdk_dependency(explicit: Option<&str>, plugin_dir: &Path) -> Result<String, String> {
|
||||
let sdk = match explicit {
|
||||
Some(p) => PathBuf::from(p),
|
||||
None => PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/rust/openidea-plugin")),
|
||||
None => match dunce::canonicalize(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")) {
|
||||
Ok(tree) if plugin_dir.starts_with(&tree) => tree.join("sdk/rust/openidea-plugin"),
|
||||
_ => return Ok(format!("{{ git = \"{REPOSITORY}\", tag = \"v{}\" }}", env!("CARGO_PKG_VERSION"))),
|
||||
},
|
||||
};
|
||||
let sdk = dunce::canonicalize(&sdk).map_err(|_| {
|
||||
format!("the plugin SDK was not found at {}; pass --sdk <path to sdk/rust/openidea-plugin>", sdk.display())
|
||||
@@ -246,9 +252,11 @@ fn sdk_path(explicit: Option<&str>, plugin_dir: &Path) -> Result<String, String>
|
||||
return Err(format!("{} is not the openidea-plugin SDK (no Cargo.toml)", sdk.display()));
|
||||
}
|
||||
let path = relative(plugin_dir, &sdk).unwrap_or(sdk);
|
||||
Ok(path.to_string_lossy().replace('\\', "/"))
|
||||
Ok(format!("{{ path = \"{}\" }}", path.to_string_lossy().replace('\\', "/")))
|
||||
}
|
||||
|
||||
const REPOSITORY: &str = "https://github.com/l0ng-ai/openidea";
|
||||
|
||||
/// `to` relative to `from` when they share a root (keeps packages in a repo movable).
|
||||
fn relative(from: &Path, to: &Path) -> Option<PathBuf> {
|
||||
let (f, t): (Vec<_>, Vec<_>) = (from.components().collect(), to.components().collect());
|
||||
@@ -781,6 +789,27 @@ mod tests {
|
||||
assert_eq!(relative(Path::new("/x/y"), Path::new("/z")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_plugins_depend_on_the_sdk_by_path_only_in_its_source_tree() {
|
||||
let tree = dunce::canonicalize(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")).unwrap();
|
||||
assert_eq!(
|
||||
sdk_dependency(None, &tree.join("plugins/official/new")).unwrap(),
|
||||
"{ path = \"../../../sdk/rust/openidea-plugin\" }"
|
||||
);
|
||||
let outside = dunce::canonicalize(std::env::temp_dir()).unwrap().join("my-plugin");
|
||||
assert_eq!(
|
||||
sdk_dependency(None, &outside).unwrap(),
|
||||
format!("{{ git = \"https://github.com/l0ng-ai/openidea\", tag = \"v{}\" }}", env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
let sdk = tree.join("sdk/rust/openidea-plugin");
|
||||
assert!(sdk_dependency(Some(sdk.to_str().unwrap()), &outside).unwrap().starts_with("{ path = "));
|
||||
assert!(
|
||||
sdk_dependency(Some(tree.join("wit").to_str().unwrap()), &outside)
|
||||
.unwrap_err()
|
||||
.contains("not the openidea-plugin SDK")
|
||||
);
|
||||
}
|
||||
|
||||
/// A theme package `id` signed by `publisher` with `key`, packed into `out`.
|
||||
fn signed_theme(tmp: &Path, id: &str, publisher: &str, key: &str, out: &Path) {
|
||||
signed_theme_version(tmp, id, "0.1.0", "^1.0", publisher, key, out);
|
||||
@@ -901,13 +930,44 @@ mod tests {
|
||||
assert!(err.contains("unknown publisher"), "{err}");
|
||||
}
|
||||
|
||||
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
|
||||
#[test]
|
||||
fn the_command_template_builds_against_the_sdk() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-plugin-template-build-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dir = dunce::canonicalize(&dir).unwrap();
|
||||
let plugin = dir.join("plugin");
|
||||
let sdk = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/rust/openidea-plugin");
|
||||
let sdk = sdk_dependency(Some(sdk), &plugin).unwrap();
|
||||
let vars = templates::Vars { id: "acme.sample", name: "Sample", sdk: Some(&sdk) };
|
||||
for (rel, content) in templates::render(templates::Template::Command, &vars) {
|
||||
let path = plugin.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, content).unwrap();
|
||||
}
|
||||
let out = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()))
|
||||
.args(["test", "--offline", "--manifest-path"])
|
||||
.arg(plugin.join("Cargo.toml"))
|
||||
.env("CARGO_TARGET_DIR", dir.join("target"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_template_is_a_valid_package() {
|
||||
for t in templates::Template::ALL {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("openidea-plugin-template-{}-{}", t.label(), std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let vars = templates::Vars { id: "acme.sample", name: "Sample", sdk: Some("../sdk") };
|
||||
let vars = templates::Vars { id: "acme.sample", name: "Sample", sdk: Some("{ path = \"../sdk\" }") };
|
||||
for (rel, content) in templates::render(t, &vars) {
|
||||
let path = dir.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
|
||||
@@ -32,6 +32,7 @@ impl Template {
|
||||
pub struct Vars<'a> {
|
||||
pub id: &'a str,
|
||||
pub name: &'a str,
|
||||
/// The SDK dependency, as a TOML value (`{ path = "…" }`).
|
||||
pub sdk: Option<&'a str>,
|
||||
}
|
||||
|
||||
@@ -118,7 +119,7 @@ publish = false
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "__SDK__" }
|
||||
openidea-plugin = __SDK__
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
@@ -130,7 +131,7 @@ panic = "abort"
|
||||
|
||||
const COMMAND_LIB: &str = r#"//! __NAME__: an OpenIDEA plugin.
|
||||
|
||||
use openidea_plugin::{Invocation, NotificationLevel, Plugin, host, register_plugin};
|
||||
use openidea_plugin::{Error, Invocation, NotificationLevel, Plugin, host, register_plugin};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Main {
|
||||
@@ -138,7 +139,7 @@ pub struct Main {
|
||||
}
|
||||
|
||||
impl Plugin for Main {
|
||||
fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result<Option<String>, String> {
|
||||
fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result<Option<String>, Error> {
|
||||
match id {
|
||||
"say-hello" => {
|
||||
// Instance state lasts until the plugin is idle for a while;
|
||||
@@ -153,7 +154,7 @@ impl Plugin for Main {
|
||||
let text = editor.document()?.text;
|
||||
Ok(Some(format!("{} lines in {}", text.lines().count(), editor.path())))
|
||||
}
|
||||
_ => Err(format!("unknown command {id}")),
|
||||
_ => Err(format!("unknown command {id}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,9 +76,17 @@ async fn plugin_call<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static)
|
||||
tokio::task::spawn_blocking(f).await.ok()
|
||||
}
|
||||
|
||||
/// Items from plugins carry no server (resolve and commands don't apply).
|
||||
/// Items from plugins carry no server: commands don't apply, and a code
|
||||
/// action is resolved by the plugin named in its `data` ([`PluginActionRef`]).
|
||||
const PLUGIN_SERVER: ServerId = ServerId(0);
|
||||
|
||||
/// `data` of a plugin's code action whose edits it computes when picked.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct PluginActionRef {
|
||||
plugin: String,
|
||||
data: String,
|
||||
}
|
||||
|
||||
/// A plugin's `completion-item.kind` (wit/providers.wit lists them).
|
||||
fn plugin_completion_kind(kind: &str) -> Option<CompletionKind> {
|
||||
Some(match kind {
|
||||
@@ -120,14 +128,14 @@ fn plugin_completion(item: ide_plugin::CompletionItem) -> CompletionItem {
|
||||
kind,
|
||||
documentation: item.documentation.map(|value| Markup { kind: "markdown".into(), value }),
|
||||
sort_text: item.sort_text,
|
||||
filter_text: None,
|
||||
filter_text: item.filter_text,
|
||||
preselect: false,
|
||||
deprecated: false,
|
||||
insert_text: item.insert_text,
|
||||
is_snippet: false,
|
||||
is_snippet: item.snippet,
|
||||
replace_range: item.replace,
|
||||
replace_range_tab: None,
|
||||
additional_edits: Vec::new(),
|
||||
additional_edits: item.additional_edits,
|
||||
commit_characters: Vec::new(),
|
||||
command: None,
|
||||
data: None,
|
||||
@@ -314,7 +322,7 @@ pub async fn lsp_code_actions(
|
||||
};
|
||||
let plugin_actions: Vec<CodeAction> = plugin_actions
|
||||
.into_iter()
|
||||
.map(|(_, a)| plugin_code_action(a))
|
||||
.map(|(plugin, a)| plugin_code_action(&plugin, a))
|
||||
.filter(|a| {
|
||||
only.is_empty()
|
||||
|| a.kind.as_ref().is_some_and(|k| only.iter().any(|o| k == o || k.starts_with(&format!("{o}."))))
|
||||
@@ -330,24 +338,53 @@ pub async fn lsp_code_actions(
|
||||
prepare_actions(project, doc, version, actions).await
|
||||
}
|
||||
|
||||
fn plugin_code_action(a: ide_plugin::CodeAction) -> CodeAction {
|
||||
let files = a
|
||||
fn plugin_code_action(plugin: &str, a: ide_plugin::CodeAction) -> CodeAction {
|
||||
// With `data` and no edits, the plugin computes them when the action is picked.
|
||||
let lazy = a.edits.is_empty() && a.data.is_some();
|
||||
let files: Vec<_> = a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|(path, edits)| ide_core::FileEdit::Edit { path: path.into(), edits, version: None })
|
||||
.collect();
|
||||
let data = a
|
||||
.data
|
||||
.filter(|_| lazy)
|
||||
.and_then(|data| serde_json::to_value(PluginActionRef { plugin: plugin.to_owned(), data }).ok());
|
||||
CodeAction {
|
||||
title: a.title,
|
||||
kind: a.kind,
|
||||
is_preferred: a.preferred,
|
||||
disabled_reason: None,
|
||||
edit: Some(WorkspaceEdit { files, preconditions: Vec::new() }),
|
||||
edit: (!lazy).then(|| WorkspaceEdit { files, preconditions: Vec::new() }),
|
||||
command: None,
|
||||
data: None,
|
||||
data,
|
||||
server: PLUGIN_SERVER,
|
||||
}
|
||||
}
|
||||
|
||||
/// A code action resolved by whoever offered it: its language server, or
|
||||
/// the plugin its `data` names.
|
||||
async fn resolve_action(host: &Host, window: &str, doc: DocId, action: CodeAction) -> IdeResult<CodeAction> {
|
||||
if action.server != PLUGIN_SERVER {
|
||||
return host.project(window)?.lsp.resolve_code_action(doc, action).await;
|
||||
}
|
||||
let Some(r) = action.data.clone().and_then(|d| serde_json::from_value::<PluginActionRef>(d).ok()) else {
|
||||
return Ok(action);
|
||||
};
|
||||
let (plugins, d) = plugin_providers(host, window, doc, ProviderKind::CodeActions)
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("the plugin that offered this action is gone"))?;
|
||||
let pending = ide_plugin::CodeAction {
|
||||
title: action.title.clone(),
|
||||
kind: action.kind.clone(),
|
||||
preferred: action.is_preferred,
|
||||
edits: Vec::new(),
|
||||
data: Some(r.data),
|
||||
};
|
||||
let plugin = r.plugin.clone();
|
||||
let resolved = blocking(move || plugins.resolve_code_action(&plugin, &d, pending)).await?;
|
||||
Ok(plugin_code_action(&r.plugin, ide_plugin::CodeAction { data: None, ..resolved }))
|
||||
}
|
||||
|
||||
/// Cancellable code actions with the kinds the servers advertise (Refactor This, refactoring availability).
|
||||
pub async fn lsp_code_action_query(
|
||||
host: &Host,
|
||||
@@ -381,7 +418,7 @@ pub async fn lsp_resolve_code_action(
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = project.lsp.resolve_code_action(doc, action).await?;
|
||||
let action = resolve_action(host, window, doc, action).await?;
|
||||
Ok(prepare_actions(project, doc, version, vec![action]).await?.remove(0))
|
||||
}
|
||||
|
||||
@@ -391,7 +428,7 @@ pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action
|
||||
let action = if action.edit.is_none() && action.command.is_none() {
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = project.lsp.resolve_code_action(doc, action).await?;
|
||||
let action = resolve_action(host, window, doc, action).await?;
|
||||
prepare_actions(project.clone(), doc, version, vec![action]).await?.remove(0)
|
||||
} else {
|
||||
action
|
||||
@@ -801,6 +838,25 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_plugin_action_with_data_and_no_edits_is_resolved_by_its_plugin() {
|
||||
let action = |edits: Vec<(std::path::PathBuf, Vec<TextEdit>)>, data: Option<&str>| ide_plugin::CodeAction {
|
||||
title: "Fix".into(),
|
||||
kind: None,
|
||||
preferred: false,
|
||||
edits,
|
||||
data: data.map(str::to_owned),
|
||||
};
|
||||
let lazy = plugin_code_action("acme.x", action(Vec::new(), Some("ref")));
|
||||
assert!(lazy.edit.is_none());
|
||||
let r: PluginActionRef = serde_json::from_value(lazy.data.unwrap()).unwrap();
|
||||
assert_eq!((r.plugin.as_str(), r.data.as_str()), ("acme.x", "ref"));
|
||||
// With edits, `data` is the plugin's business: applied as is.
|
||||
let edit = TextEdit { range: Range::default(), new_text: "x".into() };
|
||||
let eager = plugin_code_action("acme.x", action(vec![("/a".into(), vec![edit])], Some("ref")));
|
||||
assert!(eager.edit.is_some() && eager.data.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_completion_kind_the_plugin_api_documents_is_understood() {
|
||||
let wit = include_str!("../../../../wit/providers.wit");
|
||||
|
||||
@@ -36,6 +36,10 @@ pub fn find_files(host: &Host, window: &str, query: String, limit: u32) -> IdeRe
|
||||
Ok(host.project(window)?.index.find_files(&query, limit as usize))
|
||||
}
|
||||
|
||||
pub fn find_dirs(host: &Host, window: &str, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
|
||||
Ok(host.project(window)?.index.find_dirs(&query, limit as usize))
|
||||
}
|
||||
|
||||
pub fn find_symbols(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -157,6 +161,7 @@ pub async fn web_unresolved_references(host: &Host, window: &str, doc: DocId) ->
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("index_status", |c| async move { index_status(&c.host, &c.window) });
|
||||
d.add("find_files", |c| async move { find_files(&c.host, &c.window, c.arg("query")?, c.arg("limit")?) });
|
||||
d.add("find_dirs", |c| async move { find_dirs(&c.host, &c.window, c.arg("query")?, c.arg("limit")?) });
|
||||
d.add("find_symbols", |c| async move {
|
||||
find_symbols(&c.host, &c.window, c.arg("query")?, c.arg("filter")?, c.arg("limit")?)
|
||||
});
|
||||
|
||||
@@ -292,6 +292,21 @@ impl PluginHost {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The edits of an action `plugin_id` returned with `data`, now that the
|
||||
/// user picked it: a call with the command budget, not the edit path's.
|
||||
pub fn resolve_code_action(
|
||||
&self,
|
||||
plugin_id: &str,
|
||||
doc: &ProviderDocument,
|
||||
action: CodeAction,
|
||||
) -> ide_core::IdeResult<CodeAction> {
|
||||
let d = Arc::new(doc.clone());
|
||||
let timeout = self.limits.timeout;
|
||||
self.code_call(plugin_id, ide_plugin::Invocation::default(), "resolving the code action", move |rt, _| {
|
||||
rt.resolve_code_action(&d, &action, timeout)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn provide_definition(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec<Location> {
|
||||
let d = Arc::new(doc.clone());
|
||||
self.edit_calls(ProviderKind::Definition, &doc.language, move |rt, timeout| {
|
||||
|
||||
@@ -56,6 +56,9 @@ pub struct Project {
|
||||
pub(crate) watcher: Watcher,
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
/// Watchers of folders outside the project that language servers registered file
|
||||
/// watchers for (a virtualenv elsewhere, a path dependency).
|
||||
lsp_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
pub(crate) _scratch_watcher: Option<Watcher>,
|
||||
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
|
||||
/// nothing indexed, no language servers, repositories or project services.
|
||||
@@ -305,7 +308,7 @@ impl Host {
|
||||
index.update(&changed, &batch.removed);
|
||||
kotlin_bridge.files_changed(changed.iter().chain(&batch.removed));
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed);
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
// Atomic saves by external tools surface as `created`.
|
||||
documents.on_disk_changed(&changed);
|
||||
// A framework's root marker (`angular.json`) created or deleted: its
|
||||
@@ -458,6 +461,7 @@ impl Host {
|
||||
kotlin_bridge: Some(kotlin_bridge),
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: scratch_watcher,
|
||||
light: false,
|
||||
});
|
||||
@@ -467,6 +471,14 @@ impl Host {
|
||||
weak.upgrade().map(|p| p.reference_candidates(q, cancel)).unwrap_or_default()
|
||||
}));
|
||||
}
|
||||
{
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.lsp.set_file_watch_roots_hook(Box::new(move |roots| {
|
||||
if let Some(p) = weak.upgrade() {
|
||||
p.watch_for_language_servers(roots);
|
||||
}
|
||||
}));
|
||||
}
|
||||
{
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.lsp.set_project_excludes_hook(Box::new(move || {
|
||||
@@ -582,6 +594,7 @@ impl Host {
|
||||
kotlin_bridge: None,
|
||||
watcher,
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: None,
|
||||
light: true,
|
||||
root: dir,
|
||||
@@ -991,6 +1004,30 @@ fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cac
|
||||
|
||||
/// Watches a content root outside the project: the index, open documents and
|
||||
/// Local History follow its changes like the project folder's.
|
||||
impl Project {
|
||||
/// Watches `roots` (outside the project) for the language servers that asked to.
|
||||
fn watch_for_language_servers(&self, roots: Vec<PathBuf>) {
|
||||
let mut watchers = self.lsp_watchers.lock();
|
||||
watchers.retain(|(r, _)| roots.contains(r));
|
||||
for root in roots {
|
||||
if watchers.iter().any(|(r, _)| *r == root) || !root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let lsp = Arc::downgrade(&self.lsp);
|
||||
let on_change = Box::new(move |batch: &ide_vfs::FsBatch| {
|
||||
if let Some(lsp) = lsp.upgrade() {
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
}
|
||||
});
|
||||
// Not project files: nothing else hears of them.
|
||||
match Watcher::start(&root, Vec::new(), Arc::new(ide_core::NullSink), on_change) {
|
||||
Ok(w) => watchers.push((root, w)),
|
||||
Err(e) => tracing::warn!("language server watcher {}: {e}", root.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn content_root_watcher(
|
||||
dir: &Path,
|
||||
excludes: &[String],
|
||||
|
||||
@@ -226,6 +226,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "deploy_coverage"
|
||||
| "deploy_test_connection"
|
||||
| "find_files"
|
||||
| "find_dirs"
|
||||
| "find_symbols"
|
||||
| "mark_recent"
|
||||
| "remove_recent"
|
||||
@@ -274,6 +275,15 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "plugin_set_theme_frame"
|
||||
| "plugin_catalog"
|
||||
| "plugin_assets"
|
||||
| "plugin_market"
|
||||
| "plugin_market_url"
|
||||
| "plugin_set_market_url"
|
||||
| "plugin_market_download"
|
||||
| "plugin_unpack_package"
|
||||
| "plugin_stage_package"
|
||||
| "plugin_preview_install"
|
||||
| "plugin_read_intellij_theme"
|
||||
| "plugin_installed_intellij_themes"
|
||||
| "notebook_open"
|
||||
| "notebook_get"
|
||||
| "notebook_edit"
|
||||
@@ -319,12 +329,31 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
) || cmd.starts_with("plugin:")
|
||||
}
|
||||
|
||||
/// Commands that change which plugin code runs: allowed where no project is open (the
|
||||
/// welcome screen), otherwise only in a trusted project.
|
||||
pub fn projectless_command_allowed(cmd: &str) -> bool {
|
||||
matches!(
|
||||
cmd,
|
||||
"plugin_install_dir"
|
||||
| "plugin_uninstall"
|
||||
| "plugin_set_enabled"
|
||||
| "plugin_grant"
|
||||
| "plugin_set_capability"
|
||||
| "plugin_roll_back"
|
||||
| "plugin_reload"
|
||||
)
|
||||
}
|
||||
|
||||
impl crate::Host {
|
||||
pub fn authorize_command(&self, window: &str, command: &str) -> IdeResult<()> {
|
||||
if restricted_command_allowed(command) {
|
||||
return Ok(());
|
||||
}
|
||||
self.project(window)?.require_trust()
|
||||
match self.project(window) {
|
||||
Ok(project) => project.require_trust(),
|
||||
Err(_) if projectless_command_allowed(command) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -493,12 +493,15 @@ fn running_calls_can_be_cancelled() {
|
||||
let f = f.clone();
|
||||
std::thread::spawn(move || f.run("misbehave", "spin", None))
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
let started = Instant::now();
|
||||
f.host.cancel("misbehave");
|
||||
// A cancel before the call runs (the instance may still be starting) does nothing: repeat it.
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while !spinning.is_finished() {
|
||||
assert!(Instant::now() < until, "the running call wasn't interrupted");
|
||||
f.host.cancel("misbehave");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let err = spinning.join().unwrap().unwrap_err();
|
||||
assert!(err.contains("was cancelled"), "{err}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
assert_eq!(f.run("misbehave", "echo", Some("x")).unwrap().as_deref(), Some("x"), "no backoff");
|
||||
let stats = f.host.info_of("misbehave").unwrap().stats;
|
||||
assert_eq!((stats.crashes, stats.activations), (0, 2));
|
||||
@@ -606,8 +609,9 @@ fn providers_of_several_plugins_run_concurrently() {
|
||||
text: text.into(),
|
||||
};
|
||||
let at = ide_core::Pos::new(0, 0);
|
||||
// Activation is not what is measured.
|
||||
assert_eq!(host.provide_completion(&doc("fast"), at, None).len(), 2);
|
||||
// Activation is not what is measured: a first call that starts an instance
|
||||
// can run past the edit-path budget, and its answer is dropped.
|
||||
assert!(eventually(|| host.provide_completion(&doc("fast"), at, None).len() == 2));
|
||||
|
||||
let started = Instant::now();
|
||||
let items = host.provide_completion(&doc("sleep:500"), at, None);
|
||||
@@ -635,7 +639,7 @@ fn idle_instances_are_reclaimed_and_schedules_reactivate() {
|
||||
assert_eq!(f.host.instances(), 0);
|
||||
let info = f.host.info_of("misbehave").unwrap();
|
||||
assert_eq!((info.status, info.stats.reclaims), (PluginStatus::Inactive, 1));
|
||||
assert_eq!(f.command_titles("misbehave").len(), 8, "contributions stay");
|
||||
assert_eq!(f.command_titles("misbehave").len(), 10, "contributions stay");
|
||||
assert_eq!(f.run("misbehave", "echo", Some("y")).unwrap().as_deref(), Some("y"));
|
||||
assert_eq!(f.host.info_of("misbehave").unwrap().stats.activations, 2);
|
||||
|
||||
@@ -1673,22 +1677,21 @@ fn official_ai_completion_cancels_superseded_requests() {
|
||||
};
|
||||
let at = ide_core::Pos::new(1, 4);
|
||||
let host = Arc::new(f);
|
||||
// A slow request, superseded 200 ms later by the next keystroke's.
|
||||
// A slow request, superseded by the next keystroke's once the server has it
|
||||
// (starting the instance comes first, and takes longer on a slow runner).
|
||||
let first = ide_core::CancellationToken::new();
|
||||
let slow = {
|
||||
let (host, doc, first) = (host.clone(), doc.clone(), first.clone());
|
||||
std::thread::spawn(move || {
|
||||
let started = Instant::now();
|
||||
let r = host.host.provide_inline_completion(&doc, at, &first);
|
||||
(r, started.elapsed())
|
||||
})
|
||||
std::thread::spawn(move || (host.host.provide_inline_completion(&doc, at, &first), Instant::now()))
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
assert!(eventually(|| seen.lock().len() == 1), "the first request reaches the server");
|
||||
let cancelled = Instant::now();
|
||||
first.cancel();
|
||||
let started = Instant::now();
|
||||
let second = host.host.provide_inline_completion(&doc, at, &ide_core::CancellationToken::new());
|
||||
let took = started.elapsed();
|
||||
let (old, old_took) = slow.join().unwrap();
|
||||
let (old, old_done) = slow.join().unwrap();
|
||||
let old_took = old_done.saturating_duration_since(cancelled);
|
||||
assert!(old.is_none(), "the superseded request yields nothing");
|
||||
assert!(old_took < Duration::from_secs(1), "cancelled, not waited out: {old_took:?}");
|
||||
assert_eq!(second.map(|(_, s)| s.insert_text).as_deref(), Some("a + b"));
|
||||
@@ -1866,7 +1869,12 @@ fn official_mybatis_navigates_between_interface_and_xml() {
|
||||
assert_eq!((target.path, target.range.start), (xml_path.clone(), ide_core::Pos::new(1, 14)));
|
||||
|
||||
let xdoc = doc(&xml_path, "xml", xml);
|
||||
let to_java = f.host.provide_definition(&xdoc, ide_core::Pos::new(1, 16));
|
||||
// Reads the interface from disk: on a slow machine that too can run past the budget.
|
||||
let mut to_java = Vec::new();
|
||||
assert!(eventually(|| {
|
||||
to_java = f.host.provide_definition(&xdoc, ide_core::Pos::new(1, 16));
|
||||
!to_java.is_empty()
|
||||
}));
|
||||
assert_eq!(
|
||||
to_java.iter().map(|l| (l.path.clone(), l.range.start)).collect::<Vec<_>>(),
|
||||
[(java_path.clone(), ide_core::Pos::new(3, 9))]
|
||||
@@ -2410,3 +2418,61 @@ fn uninstalling_deletes_the_plugins_secrets() {
|
||||
f.host.uninstall("openidea.ai-completion").unwrap();
|
||||
assert!(keychain.0.lock().is_empty(), "{:?}", keychain.0.lock().keys().collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// Plugin API 1.0 leaves room to grow: event kinds are names, and the editor
|
||||
/// providers carry snippets, imports, lazily computed quick fixes and tagged
|
||||
/// problems.
|
||||
#[test]
|
||||
fn completion_quick_fixes_problems_and_event_kinds_of_api_1() {
|
||||
let f = fixture(Limits::default());
|
||||
let pkg = f._tmp.path().join("misbehave-providers");
|
||||
copy_dir(&misbehave_pkg(), &pkg);
|
||||
let manifest = std::fs::read_to_string(pkg.join("plugin.toml")).unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
format!("{manifest}\n[[contributes.providers]]\nkinds = [\"completion\", \"code-actions\"]\nlanguages = [\"text\"]\n"),
|
||||
)
|
||||
.unwrap();
|
||||
f.install(&pkg);
|
||||
let doc = |text: &str| ide_plugin::ProviderDocument {
|
||||
path: f.project.join("a.txt"),
|
||||
language: "text".into(),
|
||||
version: 1,
|
||||
text: text.into(),
|
||||
};
|
||||
let at = ide_core::Pos::new(0, 0);
|
||||
|
||||
// The first call starts the instance, which may take longer than the edit-path budget.
|
||||
let mut items = Vec::new();
|
||||
assert!(eventually(|| {
|
||||
items = f.host.provide_completion(&doc("rich"), at, None);
|
||||
!items.is_empty()
|
||||
}));
|
||||
let item = &items[0].1;
|
||||
assert_eq!(
|
||||
(item.insert_text.as_str(), item.snippet, item.filter_text.as_deref()),
|
||||
("f(${1:x})$0", true, Some("fun"))
|
||||
);
|
||||
assert_eq!(item.additional_edits[0].new_text, "use f;\n");
|
||||
|
||||
// Offered without edits; computed when picked.
|
||||
let actions = f.host.provide_code_actions(&doc("lazy"), ide_core::Range::default());
|
||||
let (plugin, action) = actions.into_iter().next().expect("offered");
|
||||
assert!(action.edits.is_empty() && action.data.as_deref() == Some("fix"));
|
||||
let resolved = f.host.resolve_code_action(&plugin, &doc("lazy"), action.clone()).unwrap();
|
||||
assert_eq!(resolved.edits[0].1[0].new_text, "fixed ");
|
||||
let foreign = ide_plugin::CodeAction { data: Some("other".into()), ..action };
|
||||
assert!(f.host.resolve_code_action(&plugin, &doc("lazy"), foreign).is_err());
|
||||
|
||||
// A kind this IDE doesn't know is refused, not a trap.
|
||||
let err = f.host.run_command("misbehave", "subscribe", Some("file-deleted"), f.inv()).unwrap_err();
|
||||
assert!(err.message.contains("no event kind"), "{}", err.message);
|
||||
let err = f.host.run_command("misbehave", "subscribe", Some("file-saved"), f.inv()).unwrap_err();
|
||||
assert!(err.message.contains("events"), "known, but not granted: {}", err.message);
|
||||
|
||||
// Tags the IDE knows, the tool that found it.
|
||||
let path = f.project.join("a.txt");
|
||||
f.host.run_command("misbehave", "diagnose", Some(&path.to_string_lossy()), f.inv()).unwrap();
|
||||
let d = f.workspace.diagnostics.lock().get(&("misbehave".into(), path)).cloned().unwrap();
|
||||
assert_eq!((d[0].unnecessary, d[0].deprecated, d[0].source.as_deref()), (true, false, Some("lint")));
|
||||
}
|
||||
@@ -58,6 +58,11 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
|
||||
"vcs_write_patch",
|
||||
"remote_bootstrap_list",
|
||||
"deploy_test_connection",
|
||||
"plugin_market",
|
||||
"plugin_market_url",
|
||||
"plugin_set_market_url",
|
||||
"plugin_market_download",
|
||||
"plugin_preview_install",
|
||||
] {
|
||||
assert!(ide_host::trust::restricted_command_allowed(command), "{command}");
|
||||
for window in ["main", "welcome"] {
|
||||
@@ -72,8 +77,6 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
|
||||
"tools_list",
|
||||
"tools_install",
|
||||
"tools_uninstall",
|
||||
"plugin_install_dir",
|
||||
"plugin_reload",
|
||||
"vcs_git_version",
|
||||
"docker_compose_op",
|
||||
"db_execute",
|
||||
@@ -93,6 +96,12 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
|
||||
assert!(host.authorize_command(window, command).is_err(), "{window}: {command}");
|
||||
}
|
||||
}
|
||||
// Plugin installs run plugin code: from the welcome screen, but not in an untrusted project.
|
||||
for command in ["plugin_install_dir", "plugin_uninstall", "plugin_set_enabled", "plugin_reload"] {
|
||||
assert!(!ide_host::trust::restricted_command_allowed(command), "{command}");
|
||||
assert!(host.authorize_command("main", command).is_err(), "{command}");
|
||||
assert!(host.authorize_command("welcome", command).is_ok(), "{command}");
|
||||
}
|
||||
// These requests validate the vendor before any network access, independently of project trust.
|
||||
for window in ["main", "welcome"] {
|
||||
let error = ide_host::ops::tools::jdk_download_releases(
|
||||
|
||||
@@ -14,6 +14,9 @@ fn bench(c: &mut Criterion) {
|
||||
for q in ["ordcon", "src/user", "PaymentService", "zzzz", "a"] {
|
||||
g.bench_function(format!("find_files/{q}"), |b| b.iter(|| black_box(index.find_files(q, 50).len())));
|
||||
}
|
||||
for q in ["util", "src/ui", "a"] {
|
||||
g.bench_function(format!("find_dirs/{q}"), |b| b.iter(|| black_box(index.find_dirs(q, 50).len())));
|
||||
}
|
||||
for q in ["OCo", "invoiceRepo", "renderView", "q"] {
|
||||
g.bench_function(format!("find_symbols/{q}"), |b| {
|
||||
b.iter(|| black_box(index.find_symbols(q, SymbolFilter::All, 50).len()))
|
||||
|
||||
@@ -134,6 +134,9 @@ impl FileEntry {
|
||||
pub(crate) struct IndexData {
|
||||
pub files: Vec<Option<FileEntry>>,
|
||||
by_path: HashMap<PathBuf, u32>,
|
||||
/// Every folder holding an indexed file at any depth, keyed by its `rel` with a
|
||||
/// trailing `/`: its absolute path and the number of files below it.
|
||||
pub dirs: HashMap<Box<str>, (PathBuf, u32)>,
|
||||
free: Vec<u32>,
|
||||
pub file_count: u32,
|
||||
pub symbol_count: u32,
|
||||
@@ -167,6 +170,11 @@ impl IndexData {
|
||||
}
|
||||
};
|
||||
let path = self.files[slot as usize].as_ref().map(|e| e.path.clone()).unwrap_or_default();
|
||||
if let Some(e) = &self.files[slot as usize] {
|
||||
for (rel, abs) in ancestors(e) {
|
||||
self.dirs.entry(rel.into()).or_insert_with(|| (abs.to_owned(), 0)).1 += 1;
|
||||
}
|
||||
}
|
||||
self.by_path.insert(path, slot);
|
||||
self.file_count += 1;
|
||||
self.symbol_count += symbols;
|
||||
@@ -176,6 +184,14 @@ impl IndexData {
|
||||
let slot = self.by_path.remove(path)?;
|
||||
let old = self.files[slot as usize].take()?;
|
||||
self.free.push(slot);
|
||||
for (rel, _) in ancestors(&old) {
|
||||
if let Some(d) = self.dirs.get_mut(rel) {
|
||||
d.1 -= 1;
|
||||
if d.1 == 0 {
|
||||
self.dirs.remove(rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.file_count -= 1;
|
||||
self.symbol_count -= old.symbols.len() as u32;
|
||||
Some(old)
|
||||
@@ -197,6 +213,7 @@ impl IndexData {
|
||||
self.files.shrink_to_fit();
|
||||
self.free.shrink_to_fit();
|
||||
self.by_path.shrink_to_fit();
|
||||
self.dirs.shrink_to_fit();
|
||||
}
|
||||
|
||||
pub(crate) fn paths(&self) -> impl Iterator<Item = &PathBuf> {
|
||||
@@ -204,6 +221,19 @@ impl IndexData {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders holding `e` (`rel` with a trailing `/`, absolute path), innermost first.
|
||||
fn ancestors(e: &FileEntry) -> impl Iterator<Item = (&str, &Path)> {
|
||||
let mut rel = e.dir();
|
||||
let mut abs = e.path.parent();
|
||||
std::iter::from_fn(move || {
|
||||
let path = abs.filter(|_| !rel.is_empty())?;
|
||||
let here = rel;
|
||||
rel = rel[..rel.len() - 1].rfind('/').map_or("", |i| &rel[..=i]);
|
||||
abs = path.parent();
|
||||
Some((here, path))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -223,6 +253,23 @@ mod tests {
|
||||
FileEntry::new(PathBuf::from("/r").join(path), path.to_owned(), record)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirs_follow_inserts_and_removals() {
|
||||
let mut d = IndexData::default();
|
||||
d.insert(entry("a/b/c.rs", 0));
|
||||
d.insert(entry("a/d.rs", 0));
|
||||
d.insert(entry("a/d.rs", 0));
|
||||
d.insert(entry("top.rs", 0));
|
||||
let mut dirs: Vec<_> = d.dirs.iter().map(|(k, v)| (k.to_string(), v.1)).collect();
|
||||
dirs.sort();
|
||||
assert_eq!(dirs, [("a/".into(), 2), ("a/b/".into(), 1)]);
|
||||
assert_eq!(d.dirs["a/b/"].0, PathBuf::from("/r/a/b"));
|
||||
d.remove(Path::new("/r/a/b/c.rs"));
|
||||
assert!(!d.dirs.contains_key("a/b/"));
|
||||
d.remove_tree(Path::new("/r/a"));
|
||||
assert!(d.dirs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_replace_remove_keep_counts() {
|
||||
let mut d = IndexData::default();
|
||||
|
||||
@@ -167,6 +167,11 @@ impl ProjectIndex {
|
||||
matching::find_files(&d, &matching::Recents { paths: &recent }, query, limit)
|
||||
}
|
||||
|
||||
/// Fuzzy search for folders that hold indexed files; `rel_path` ends in `/`.
|
||||
pub fn find_dirs(&self, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
matching::find_dirs(&self.shared.data.read(), query, limit)
|
||||
}
|
||||
|
||||
/// Fuzzy symbol search; CamelHump aware (`OCo` → `OrderController`).
|
||||
pub fn find_symbols(&self, query: &str, filter: SymbolFilter, limit: usize) -> Vec<SymbolMatch> {
|
||||
let recent = self.shared.recent.lock().clone();
|
||||
@@ -366,6 +371,10 @@ pub mod bench_support {
|
||||
matching::find_files(&self.data, &matching::Recents { paths: &self.recent }, query, limit)
|
||||
}
|
||||
|
||||
pub fn find_dirs(&self, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
matching::find_dirs(&self.data, query, limit)
|
||||
}
|
||||
|
||||
pub fn find_symbols(&self, query: &str, filter: SymbolFilter, limit: usize) -> Vec<SymbolMatch> {
|
||||
matching::find_symbols(&self.data, &matching::Recents { paths: &self.recent }, query, filter, limit)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use nucleo_matcher::{Config, Matcher, Utf32Str, Utf32String};
|
||||
use rayon::prelude::*;
|
||||
use std::cell::RefCell;
|
||||
use std::cmp::Ordering;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const TIER_NAME: u32 = 1 << 20;
|
||||
const EXACT: u32 = 4000;
|
||||
@@ -251,6 +251,76 @@ pub(crate) fn find_files(data: &IndexData, recents: &Recents, query: &str, limit
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fuzzy folder search over the folders holding indexed files: folder-name matches beat
|
||||
/// path matches; `/` in the query matches the whole path. `rel_path` ends in `/`.
|
||||
pub(crate) fn find_dirs(data: &IndexData, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
let q = normalize_file_query(query);
|
||||
if limit == 0 || q.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let by_path = q.contains('/');
|
||||
let needle = Needle::new(q.trim_end_matches('/'));
|
||||
// (score, rel without the trailing `/`, char offset of the name when it matched by name)
|
||||
let score = |m: &mut Matcher, buf: &mut Vec<char>, rel: &str| -> Option<(u32, Option<u32>)> {
|
||||
let trimmed = &rel[..rel.len() - 1];
|
||||
let start = trimmed.rfind('/').map_or(0, |i| i + 1);
|
||||
let name = &trimmed[start..];
|
||||
if !by_path
|
||||
&& needle.mask & char_mask(name) == needle.mask
|
||||
&& let Some(s) = needle.score(m, name, buf)
|
||||
{
|
||||
return Some((TIER_NAME + s * 4 + needle.name_boost(name), Some(trimmed[..start].chars().count() as u32)));
|
||||
}
|
||||
if needle.mask & char_mask(trimmed) != needle.mask {
|
||||
return None;
|
||||
}
|
||||
needle.score(m, trimmed, buf).map(|s| (s, None))
|
||||
};
|
||||
let mut best: Vec<(u32, &str, &Path, Option<u32>)> = data
|
||||
.dirs
|
||||
.par_iter()
|
||||
.filter_map(|(rel, (path, _))| {
|
||||
let mut buf = Vec::new();
|
||||
with_matcher(|m| score(m, &mut buf, rel)).map(|(s, at)| (s, &**rel, path.as_path(), at))
|
||||
})
|
||||
.collect();
|
||||
let order = |a: &(u32, &str, &Path, Option<u32>), b: &(u32, &str, &Path, Option<u32>)| {
|
||||
b.0.cmp(&a.0).then_with(|| a.1.len().cmp(&b.1.len())).then_with(|| a.1.cmp(b.1))
|
||||
};
|
||||
if best.len() > limit {
|
||||
best.select_nth_unstable_by(limit, order);
|
||||
best.truncate(limit);
|
||||
}
|
||||
// Match indices and the CamelHump bonus `find_files` gives, so equal matches rank alike.
|
||||
let mut out: Vec<FileMatch> = with_matcher(|m| {
|
||||
let (mut buf, mut idx) = (Vec::new(), Vec::new());
|
||||
best.into_iter()
|
||||
.map(|(score, rel, path, name_at)| {
|
||||
let trimmed = &rel[..rel.len() - 1];
|
||||
let (bonus, indices) = match name_at {
|
||||
Some(at) => {
|
||||
let name = &trimmed[trimmed.rfind('/').map_or(0, |i| i + 1)..];
|
||||
needle.indices(m, name, &mut buf, &mut idx);
|
||||
(hump_bonus(name, &idx), idx.iter().map(|i| i + at).collect())
|
||||
}
|
||||
None => {
|
||||
needle.indices(m, trimmed, &mut buf, &mut idx);
|
||||
(hump_bonus(trimmed, &idx), idx.clone())
|
||||
}
|
||||
};
|
||||
FileMatch { path: path.to_path_buf().into(), rel_path: rel.to_owned(), score: score + bonus, indices }
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
out.sort_by(|a, b| {
|
||||
b.score
|
||||
.cmp(&a.score)
|
||||
.then_with(|| a.rel_path.len().cmp(&b.rel_path.len()))
|
||||
.then_with(|| a.rel_path.cmp(&b.rel_path))
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn file(data: &IndexData, slot: u32) -> &FileEntry {
|
||||
data.files[slot as usize].as_ref().expect("candidate slots are live")
|
||||
}
|
||||
|
||||
@@ -138,6 +138,23 @@ fn file_ranking_is_idea_like() {
|
||||
assert_eq!(shown.to_lowercase(), "uibtn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_dirs_ranks_folder_names() {
|
||||
let f = sample();
|
||||
let idx = f.open();
|
||||
let dirs = |q: &str| idx.find_dirs(q, 20).into_iter().map(|m| m.rel_path).collect::<Vec<_>>();
|
||||
assert_eq!(dirs("order"), ["src/order/"]);
|
||||
assert_eq!(dirs("src")[0], "src/");
|
||||
assert!(dirs("src").contains(&"src/ui/".to_owned()), "{:?}", dirs("src"));
|
||||
assert_eq!(dirs("src/ui/"), ["src/ui/"]);
|
||||
assert!(dirs("").is_empty());
|
||||
assert!(dirs("main").is_empty());
|
||||
|
||||
let m = &idx.find_dirs("ui", 1)[0];
|
||||
assert_eq!(m.path.0, f.root.join("src/ui"));
|
||||
assert_eq!(m.indices, vec![4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shorter_paths_win_ties_and_recent_files_boost() {
|
||||
let fx = Fixture::new(&[("a/b/c/util.rs", ""), ("x/util.rs", ""), ("y/util.rs", "")]);
|
||||
|
||||
@@ -60,6 +60,9 @@ pub struct LanguageConfig {
|
||||
/// External formatter used when no language server can format, or selected in settings.
|
||||
#[serde(default)]
|
||||
pub formatter: Option<FormatterConfig>,
|
||||
/// Content of a new scratch file; `$END$` marks where the caret goes.
|
||||
#[serde(default)]
|
||||
pub scratch_template: Option<String>,
|
||||
}
|
||||
|
||||
/// An external formatting tool and its language-specific parser.
|
||||
@@ -242,6 +245,10 @@ pub struct LanguageInfo {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub first_line: Option<String>,
|
||||
/// Content of a new scratch file; `$END$` marks where the caret goes.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub scratch_template: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&LanguageConfig> for LanguageInfo {
|
||||
@@ -258,6 +265,7 @@ impl From<&LanguageConfig> for LanguageInfo {
|
||||
language_servers: c.language_servers.iter().map(|s| s.name.clone()).collect(),
|
||||
filenames: c.filenames.clone(),
|
||||
first_line: c.first_line.clone(),
|
||||
scratch_template: c.scratch_template.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -772,6 +772,10 @@ mod tests {
|
||||
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
|
||||
}
|
||||
}
|
||||
if let Some(t) = &cfg.scratch_template {
|
||||
assert_eq!(t.matches("$END$").count(), 1, "{name}: scratch-template needs one $END$");
|
||||
assert!(!cfg.extensions.is_empty(), "{name}: scratch-template without an extension");
|
||||
}
|
||||
for ext in &cfg.extensions {
|
||||
assert_eq!(ext, &ext.to_ascii_lowercase(), "{name}: extensions must be lower case");
|
||||
assert!(!ext.starts_with('.'), "{name}: extension {ext} must not start with a dot");
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn client_capabilities() -> Value {
|
||||
"fileOperations": { "dynamicRegistration": true, "willRename": true, "didRename": true },
|
||||
"configuration": true,
|
||||
"didChangeConfiguration": { "dynamicRegistration": false },
|
||||
"didChangeWatchedFiles": { "dynamicRegistration": false, "relativePatternSupport": false },
|
||||
"didChangeWatchedFiles": { "dynamicRegistration": true, "relativePatternSupport": true },
|
||||
"symbol": {
|
||||
"dynamicRegistration": false,
|
||||
"symbolKind": { "valueSet": symbol_kinds },
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! `workspace/didChangeWatchedFiles` registrations: which changes on disk a
|
||||
//! server asked to hear of (its globs, relative patterns and change kinds).
|
||||
|
||||
use crate::uri;
|
||||
use globset::{GlobBuilder, GlobMatcher};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `FileChangeType`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
Created = 1,
|
||||
Changed = 2,
|
||||
Deleted = 3,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
/// The `WatchKind` bit.
|
||||
fn kind_bit(self) -> u64 {
|
||||
match self {
|
||||
Self::Created => 1,
|
||||
Self::Changed => 2,
|
||||
Self::Deleted => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Watcher {
|
||||
/// Relative pattern's base; `None` for a plain glob, matched below the server's root.
|
||||
base: Option<PathBuf>,
|
||||
/// A plain glob that is an absolute path pattern.
|
||||
absolute: bool,
|
||||
glob: GlobMatcher,
|
||||
kind: u64,
|
||||
}
|
||||
|
||||
/// A server's registrations, by registration id.
|
||||
#[derive(Default)]
|
||||
pub struct FileWatchers(BTreeMap<String, Vec<Watcher>>);
|
||||
|
||||
impl FileWatchers {
|
||||
pub fn register(&mut self, id: &str, options: Option<&Value>) {
|
||||
let watchers = options
|
||||
.and_then(|o| o.get("watchers"))
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(parse)
|
||||
.collect();
|
||||
self.0.insert(id.to_owned(), watchers);
|
||||
}
|
||||
|
||||
pub fn unregister(&mut self, id: &str) {
|
||||
self.0.remove(id);
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// Whether a server rooted at `root` wants to hear of `change` to `path`.
|
||||
pub fn wants(&self, root: &Path, path: &Path, change: Change) -> bool {
|
||||
self.0.values().flatten().any(|w| {
|
||||
if w.kind & change.kind_bit() == 0 {
|
||||
return false;
|
||||
}
|
||||
match &w.base {
|
||||
Some(base) => path.strip_prefix(base).is_ok_and(|rel| w.glob.is_match(rel)),
|
||||
None if w.absolute => w.glob.is_match(path),
|
||||
None => path.strip_prefix(root).is_ok_and(|rel| w.glob.is_match(rel)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Bases of relative patterns, which may lie outside the project (a virtualenv's
|
||||
/// `site-packages`, a path dependency): the client watches them for the server.
|
||||
pub fn bases(&self) -> impl Iterator<Item = &Path> {
|
||||
self.0.values().flatten().filter_map(|w| w.base.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(watcher: &Value) -> Option<Watcher> {
|
||||
let kind = watcher.get("kind").and_then(Value::as_u64).unwrap_or(7);
|
||||
let (base, pattern) = match watcher.get("globPattern")? {
|
||||
Value::String(p) => (None, p.as_str()),
|
||||
relative => {
|
||||
let base = relative.get("baseUri")?;
|
||||
// A `WorkspaceFolder` or a URI.
|
||||
let base = base.get("uri").unwrap_or(base).as_str()?;
|
||||
let base = uri::uri_to_path(base)?;
|
||||
// Changes are reported for canonical paths (`/tmp` is `/private/tmp` on macOS).
|
||||
(Some(dunce::canonicalize(&base).unwrap_or(base)), relative.get("pattern")?.as_str()?)
|
||||
}
|
||||
};
|
||||
let glob = GlobBuilder::new(pattern).literal_separator(true).build().ok()?.compile_matcher();
|
||||
let absolute = base.is_none() && Path::new(pattern).is_absolute();
|
||||
Some(Watcher { base, absolute, glob, kind })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn watchers(list: Value) -> FileWatchers {
|
||||
let mut w = FileWatchers::default();
|
||||
w.register("1", Some(&json!({ "watchers": list })));
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_globs_relative_patterns_and_kinds() {
|
||||
let root = Path::new("/p");
|
||||
let venv = uri::path_to_uri(Path::new("/opt/venv/lib/site-packages"));
|
||||
let w = watchers(json!([
|
||||
{ "globPattern": "**/*.{go,mod,sum}" },
|
||||
{ "globPattern": "**/pyrightconfig.json", "kind": 2 },
|
||||
{ "globPattern": { "baseUri": venv, "pattern": "**" } },
|
||||
{ "globPattern": { "baseUri": { "uri": uri::path_to_uri(Path::new("/shared")), "name": "s" }, "pattern": "*.toml" } },
|
||||
]));
|
||||
let cases = [
|
||||
("/p/go.mod", Change::Changed, true),
|
||||
("/p/sub/main.go", Change::Created, true),
|
||||
("/elsewhere/main.go", Change::Created, false),
|
||||
("/p/pyrightconfig.json", Change::Changed, true),
|
||||
("/p/pyrightconfig.json", Change::Created, false),
|
||||
("/opt/venv/lib/site-packages/idna/__init__.py", Change::Created, true),
|
||||
("/opt/venv/lib/site-packages", Change::Deleted, true),
|
||||
("/shared/Cargo.toml", Change::Changed, true),
|
||||
("/shared/nested/Cargo.toml", Change::Changed, false),
|
||||
("/p/readme.md", Change::Changed, false),
|
||||
];
|
||||
for (path, change, expected) in cases {
|
||||
assert_eq!(w.wants(root, Path::new(path), change), expected, "{path} {change:?}");
|
||||
}
|
||||
let mut bases: Vec<_> = w.bases().collect();
|
||||
bases.sort();
|
||||
assert_eq!(bases, [Path::new("/opt/venv/lib/site-packages"), Path::new("/shared")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistering_drops_the_watchers() {
|
||||
let mut w = watchers(json!([{ "globPattern": "**" }]));
|
||||
assert!(w.wants(Path::new("/p"), Path::new("/p/a"), Change::Created));
|
||||
w.unregister("1");
|
||||
assert!(w.is_empty());
|
||||
assert!(!w.wants(Path::new("/p"), Path::new("/p/a"), Change::Created));
|
||||
}
|
||||
}
|
||||
@@ -206,19 +206,33 @@ impl ClientHandler {
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
fn registration(&self, params: &Value, register: bool) {
|
||||
let Some(run) = self.server.running_gen(self.generation) else { return };
|
||||
fn registration(&self, mgr: &LspManager, params: &Value, register: bool) {
|
||||
let Some(run) = self.server.initialized_gen(self.generation) else { return };
|
||||
let key = if register { "registrations" } else { "unregisterations" };
|
||||
let list = params.get(key).or_else(|| params.get("unregistrations")).and_then(Value::as_array);
|
||||
let mut caps = run.caps.write();
|
||||
let mut watchers_changed = false;
|
||||
for reg in list.into_iter().flatten() {
|
||||
let Some(method) = reg.get("method").and_then(Value::as_str) else { continue };
|
||||
if register {
|
||||
if method == "workspace/didChangeWatchedFiles" {
|
||||
let id = reg.get("id").and_then(Value::as_str).unwrap_or_default();
|
||||
let mut watchers = run.watchers.write();
|
||||
if register {
|
||||
watchers.register(id, reg.get("registerOptions"));
|
||||
} else {
|
||||
watchers.unregister(id);
|
||||
}
|
||||
watchers_changed = true;
|
||||
} else if register {
|
||||
caps.register(method, reg.get("registerOptions"));
|
||||
} else {
|
||||
caps.unregister(method);
|
||||
}
|
||||
}
|
||||
drop(caps);
|
||||
if watchers_changed {
|
||||
mgr.file_watch_roots_changed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -278,11 +292,11 @@ impl Handler for ClientHandler {
|
||||
"workspace/configuration" => Ok(self.configuration(¶ms)),
|
||||
"workspace/workspaceFolders" => Ok(mgr.workspace_folders(&self.server)),
|
||||
"client/registerCapability" => {
|
||||
self.registration(¶ms, true);
|
||||
self.registration(&mgr, ¶ms, true);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"client/unregisterCapability" => {
|
||||
self.registration(¶ms, false);
|
||||
self.registration(&mgr, ¶ms, false);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"workspace/applyEdit" => self.apply_edit(&mgr, params),
|
||||
|
||||
@@ -12,6 +12,7 @@ mod clang_tidy;
|
||||
mod convert;
|
||||
mod external_project;
|
||||
mod file_ops;
|
||||
mod file_watch;
|
||||
mod handler;
|
||||
mod inspect;
|
||||
pub mod jdtls;
|
||||
@@ -160,6 +161,9 @@ impl DocSnap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives the folders outside the project that servers want watched.
|
||||
pub type WatchRootsFn = dyn Fn(Vec<PathBuf>) + Send + Sync;
|
||||
|
||||
pub struct LspManager {
|
||||
me: Weak<LspManager>,
|
||||
project_root: PathBuf,
|
||||
@@ -177,6 +181,7 @@ pub struct LspManager {
|
||||
servers_hook: RwLock<Option<Arc<ServersFn>>>,
|
||||
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
|
||||
excludes_hook: RwLock<Option<Arc<external_project::ExcludesFn>>>,
|
||||
watch_roots_hook: RwLock<Option<Arc<WatchRootsFn>>>,
|
||||
shutting_down: AtomicBool,
|
||||
execution_allowed: AtomicBool,
|
||||
java_usages_warned: AtomicBool,
|
||||
@@ -336,6 +341,7 @@ impl LspManager {
|
||||
servers_hook: RwLock::new(None),
|
||||
candidates_hook: RwLock::new(None),
|
||||
excludes_hook: RwLock::new(None),
|
||||
watch_roots_hook: RwLock::new(None),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
execution_allowed: AtomicBool::new(true),
|
||||
java_usages_warned: AtomicBool::new(false),
|
||||
@@ -587,6 +593,9 @@ impl LspManager {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let run =
|
||||
Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)), watchers: Default::default() };
|
||||
server.set_initializing(Some(run.clone()));
|
||||
if let Err(e) = peer.notify("initialized", json!({})) {
|
||||
tracing::warn!("{}: {e}", server.name);
|
||||
}
|
||||
@@ -598,7 +607,6 @@ impl LspManager {
|
||||
{
|
||||
tracing::debug!("{}: didChangeConfiguration: {e}", server.name);
|
||||
}
|
||||
let run = Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)) };
|
||||
|
||||
self.refresh_external_project(&server, &run).await;
|
||||
|
||||
@@ -607,6 +615,7 @@ impl LspManager {
|
||||
let mut docs = self.docs.lock();
|
||||
if !server.mark_ready(generation, run.clone()) {
|
||||
drop(docs);
|
||||
server.set_initializing(None);
|
||||
peer.kill();
|
||||
return;
|
||||
}
|
||||
@@ -644,6 +653,7 @@ impl LspManager {
|
||||
None => return, // superseded instance
|
||||
};
|
||||
self.clear_server_state(&server);
|
||||
self.file_watch_roots_changed();
|
||||
if intentional {
|
||||
server.announce_down();
|
||||
return;
|
||||
@@ -1973,29 +1983,78 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Files that changed on disk, outside the editor too (a checkout, another tool): each running
|
||||
/// server hears of those of its languages under its root through `workspace/didChangeWatchedFiles`.
|
||||
/// Without it jdtls's incremental build never sees them, so a launch runs stale classes.
|
||||
pub fn watched_files_changed(&self, created: &[PathBuf], modified: &[PathBuf], removed: &[PathBuf]) {
|
||||
/// Files that changed on disk, outside the editor too (a checkout, another tool), sent to
|
||||
/// running servers through `workspace/didChangeWatchedFiles`. A server that registered file
|
||||
/// watchers hears of what they match, including `excluded_dirs` (folders in excluded or
|
||||
/// ignored trees whose entries came or went, reported as created): a package installed
|
||||
/// into `.venv` or a `go.mod` rewritten by `go get` is picked up without a restart. Other
|
||||
/// servers hear of their languages' files under their root; without it jdtls's incremental
|
||||
/// build never sees them, so a launch runs stale classes.
|
||||
pub fn watched_files_changed(
|
||||
&self,
|
||||
created: &[PathBuf],
|
||||
modified: &[PathBuf],
|
||||
removed: &[PathBuf],
|
||||
excluded_dirs: &[PathBuf],
|
||||
) {
|
||||
use file_watch::Change;
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
for s in servers {
|
||||
let Some(run) = s.running() else { continue };
|
||||
let languages = s.languages();
|
||||
let changes: Vec<Value> = [(created, 1), (modified, 2), (removed, 3)]
|
||||
let all = [(created, Change::Created), (modified, Change::Changed), (removed, Change::Deleted)]
|
||||
.into_iter()
|
||||
.flat_map(|(paths, kind)| paths.iter().map(move |p| (p, kind)))
|
||||
.filter(|(p, _)| p.starts_with(&s.root) && languages.contains(&self.languages.detect(p, None)))
|
||||
.map(|(p, kind)| json!({ "uri": uri::path_to_uri(p), "type": kind }))
|
||||
.collect();
|
||||
.flat_map(|(paths, change)| paths.iter().map(move |p| (p, change)));
|
||||
let watchers = run.watchers.read();
|
||||
let changes: Vec<(&PathBuf, Change)> = if watchers.is_empty() {
|
||||
let languages = s.languages();
|
||||
all.filter(|(p, _)| p.starts_with(&s.root) && languages.contains(&self.languages.detect(p, None)))
|
||||
.collect()
|
||||
} else {
|
||||
all.chain(excluded_dirs.iter().map(|p| (p, Change::Created)))
|
||||
.filter(|(p, change)| watchers.wants(&s.root, p, *change))
|
||||
.collect()
|
||||
};
|
||||
drop(watchers);
|
||||
if changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let changes: Vec<Value> =
|
||||
changes.iter().map(|(p, c)| json!({ "uri": uri::path_to_uri(p), "type": *c as u8 })).collect();
|
||||
if let Err(e) = run.peer.notify("workspace/didChangeWatchedFiles", json!({ "changes": changes })) {
|
||||
tracing::debug!("{}: didChangeWatchedFiles: {e}", s.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Called with the folders outside the project that servers registered file watchers
|
||||
/// for (a virtualenv elsewhere, a path dependency), whenever they change. Changes
|
||||
/// below them go to [`Self::watched_files_changed`].
|
||||
pub fn set_file_watch_roots_hook(&self, hook: Box<WatchRootsFn>) {
|
||||
*self.watch_roots_hook.write() = Some(Arc::from(hook));
|
||||
self.file_watch_roots_changed();
|
||||
}
|
||||
|
||||
pub(crate) fn file_watch_roots_changed(&self) {
|
||||
let Some(hook) = self.watch_roots_hook.read().clone() else { return };
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
let mut roots: Vec<PathBuf> = Vec::new();
|
||||
for run in servers.iter().filter_map(|s| s.instance()) {
|
||||
roots.extend(
|
||||
run.watchers.read().bases().filter(|b| !b.starts_with(&self.project_root)).map(Path::to_path_buf),
|
||||
);
|
||||
}
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
// Sorted, so a folder's subfolders follow it.
|
||||
let mut outer: Vec<PathBuf> = Vec::new();
|
||||
for r in roots {
|
||||
if !outer.last().is_some_and(|o| r.starts_with(o)) {
|
||||
outer.push(r);
|
||||
}
|
||||
}
|
||||
hook(outer);
|
||||
}
|
||||
|
||||
/// Checks initialized capabilities, including dynamic registrations, before choosing a formatter.
|
||||
pub async fn can_format(&self, doc: DocId) -> IdeResult<bool> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
|
||||
@@ -27,6 +27,8 @@ pub struct Running {
|
||||
pub generation: u64,
|
||||
pub peer: Peer,
|
||||
pub caps: Arc<RwLock<ServerCaps>>,
|
||||
/// `workspace/didChangeWatchedFiles` registrations.
|
||||
pub watchers: Arc<RwLock<crate::file_watch::FileWatchers>>,
|
||||
}
|
||||
|
||||
pub enum Conn {
|
||||
@@ -82,6 +84,9 @@ pub struct Server {
|
||||
pub resolved_binary: RwLock<Option<PathBuf>>,
|
||||
languages: Mutex<Vec<LanguageId>>,
|
||||
state: Mutex<State>,
|
||||
/// The instance being initialized, from `initialized` until ready: registrations
|
||||
/// sent right after `initialized` must not be lost.
|
||||
initializing: Mutex<Option<Running>>,
|
||||
/// Fired when the instance being started is abandoned (stop / restart while starting).
|
||||
start_cancel: Mutex<CancellationToken>,
|
||||
phase: watch::Sender<Phase>,
|
||||
@@ -118,6 +123,7 @@ impl Server {
|
||||
resolved_binary: RwLock::new(None),
|
||||
languages: Mutex::new(vec![language]),
|
||||
state: Mutex::new(State { generation: 0, conn: Conn::Idle }),
|
||||
initializing: Mutex::new(None),
|
||||
start_cancel: Mutex::new(CancellationToken::new()),
|
||||
phase: watch::channel(Phase::Down).0,
|
||||
status: Mutex::new((ServerStatus::Stopped, None)),
|
||||
@@ -210,6 +216,8 @@ impl Server {
|
||||
return false;
|
||||
}
|
||||
st.conn = Conn::Ready(run);
|
||||
drop(st);
|
||||
self.set_initializing(None);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -234,6 +242,20 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance told `initialized`, ready or not.
|
||||
pub fn instance(&self) -> Option<Running> {
|
||||
self.running().or_else(|| self.initializing.lock().clone())
|
||||
}
|
||||
|
||||
/// Generation `generation` once it was told `initialized`, ready or not.
|
||||
pub fn initialized_gen(&self, generation: u64) -> Option<Running> {
|
||||
self.instance().filter(|r| r.generation == generation)
|
||||
}
|
||||
|
||||
pub fn set_initializing(&self, run: Option<Running>) {
|
||||
*self.initializing.lock() = run;
|
||||
}
|
||||
|
||||
/// The running instance if it is still generation `generation`.
|
||||
pub fn running_gen(&self, generation: u64) -> Option<Running> {
|
||||
self.running().filter(|r| r.generation == generation)
|
||||
|
||||
@@ -269,6 +269,7 @@ fn harness_configured(
|
||||
ui_mode: None,
|
||||
framework_ui_modes: Vec::new(),
|
||||
formatter: None,
|
||||
scratch_template: None,
|
||||
tree_sitter: None,
|
||||
language_servers: servers
|
||||
.iter()
|
||||
@@ -419,6 +420,7 @@ async fn files_changed_on_disk_reach_the_servers_of_their_language() {
|
||||
&[created.clone(), other],
|
||||
&[modified.clone(), outside],
|
||||
std::slice::from_ref(&removed),
|
||||
&[h.root.join(".venv/lib/site-packages")],
|
||||
);
|
||||
eventually(|| !s.notified("workspace/didChangeWatchedFiles").is_empty()).await;
|
||||
assert_eq!(
|
||||
@@ -430,12 +432,81 @@ async fn files_changed_on_disk_reach_the_servers_of_their_language() {
|
||||
])
|
||||
);
|
||||
// Nothing of its languages: no notification.
|
||||
h.mgr.watched_files_changed(&[h.root.join("b.txt")], &[], &[]);
|
||||
h.mgr.watched_files_changed(&[h.root.join("b.txt")], &[], &[], &[]);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert_eq!(s.notified("workspace/didChangeWatchedFiles").len(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// A server that registers file watchers hears of what they match, inside excluded folders
|
||||
/// too (`uv add` into `.venv`, `go get` rewriting `go.mod`); folders outside the project
|
||||
/// that relative patterns name are reported for watching; unregistered, it falls back to
|
||||
/// its languages' files.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn registered_file_watchers_choose_the_changes_a_server_hears_of() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let roots = Arc::new(Mutex::new(Vec::<Vec<PathBuf>>::new()));
|
||||
{
|
||||
let roots = roots.clone();
|
||||
h.mgr.set_file_watch_roots_hook(Box::new(move |r| roots.lock().push(r)));
|
||||
}
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let outside = dunce::canonicalize(outside.path()).unwrap();
|
||||
let external = outside.join("venv/lib/site-packages");
|
||||
s.peer()
|
||||
.request::<_, Value>(
|
||||
"client/registerCapability",
|
||||
json!({ "registrations": [{ "id": "w", "method": "workspace/didChangeWatchedFiles", "registerOptions": { "watchers": [
|
||||
{ "globPattern": "**/*.{mk,mod}" },
|
||||
{ "globPattern": "**/pyrightconfig.json", "kind": 2 },
|
||||
{ "globPattern": "**/site-packages/**" },
|
||||
{ "globPattern": { "baseUri": uri_of(&external), "pattern": "**" } },
|
||||
{ "globPattern": { "baseUri": uri_of(&h.root.join("sub")), "pattern": "**" } },
|
||||
] } }] }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(roots.lock().last(), Some(&vec![external.clone()]), "only folders outside the project");
|
||||
|
||||
let sp = h.root.join(".venv/lib/python3.14/site-packages");
|
||||
let notified = || s.notified("workspace/didChangeWatchedFiles");
|
||||
h.mgr.watched_files_changed(
|
||||
&[h.root.join("go.mod"), h.root.join("notes.txt"), h.root.join("pyrightconfig.json")],
|
||||
&[h.root.join("pyrightconfig.json"), external.join("idna/core.py")],
|
||||
&[h.root.join("old.mk")],
|
||||
&[sp.join("idna"), h.root.join("node_modules/x")],
|
||||
);
|
||||
eventually(|| !notified().is_empty()).await;
|
||||
assert_eq!(
|
||||
notified()[0]["changes"],
|
||||
json!([
|
||||
{ "uri": uri_of(&h.root.join("go.mod")), "type": 1 },
|
||||
{ "uri": uri_of(&h.root.join("pyrightconfig.json")), "type": 2 },
|
||||
{ "uri": uri_of(&external.join("idna/core.py")), "type": 2 },
|
||||
{ "uri": uri_of(&h.root.join("old.mk")), "type": 3 },
|
||||
{ "uri": uri_of(&sp.join("idna")), "type": 1 },
|
||||
])
|
||||
);
|
||||
|
||||
s.peer()
|
||||
.request::<_, Value>(
|
||||
"client/unregisterCapability",
|
||||
json!({ "unregisterations": [{ "id": "w", "method": "workspace/didChangeWatchedFiles" }] }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(roots.lock().last(), Some(&vec![]));
|
||||
h.mgr.watched_files_changed(&[h.root.join("go.mod"), h.root.join("b.mk")], &[], &[], &[sp.join("idna")]);
|
||||
eventually(|| notified().len() == 2).await;
|
||||
assert_eq!(notified()[1]["changes"], json!([{ "uri": uri_of(&h.root.join("b.mk")), "type": 1 }]));
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn initialize_and_incremental_sync() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -56,6 +56,7 @@ fn lang(id: &str, ext: &str, server: LanguageServerConfig) -> LanguageConfig {
|
||||
ui_mode: None,
|
||||
framework_ui_modes: Vec::new(),
|
||||
formatter: None,
|
||||
scratch_template: None,
|
||||
tree_sitter: None,
|
||||
language_servers: vec![server],
|
||||
debugger: None,
|
||||
|
||||
@@ -467,7 +467,6 @@ const MAX_SYNTAX_ITEMS: usize = 200_000;
|
||||
const MAX_BATCH: usize = 1000;
|
||||
|
||||
fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
|
||||
use crate::types::ActionSource as S;
|
||||
match e {
|
||||
WorkbenchEvent::FileOpened(p) => wit_events::Event::FileOpened(p),
|
||||
WorkbenchEvent::FileSaved(p) => wit_events::Event::FileSaved(p),
|
||||
@@ -477,14 +476,7 @@ fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
|
||||
WorkbenchEvent::ActionPerformed(a) => wit_events::Event::ActionPerformed(wit_events::ActionPerformed {
|
||||
action: a.action,
|
||||
title: a.title,
|
||||
source: match a.source {
|
||||
S::Keyboard => wit_events::ActionSource::Keyboard,
|
||||
S::Menu => wit_events::ActionSource::Menu,
|
||||
S::Toolbar => wit_events::ActionSource::Toolbar,
|
||||
S::ContextMenu => wit_events::ActionSource::ContextMenu,
|
||||
S::Search => wit_events::ActionSource::Search,
|
||||
S::Other => wit_events::ActionSource::Other,
|
||||
},
|
||||
source: a.source.name().to_owned(),
|
||||
shortcut: a.shortcut,
|
||||
}),
|
||||
}
|
||||
@@ -670,9 +662,17 @@ impl Runtime {
|
||||
detail: i.detail.map(|d| clip(d, MAX_TITLE)),
|
||||
kind: i.kind.map(|k| clip(k, 32)),
|
||||
insert_text: clip(i.insert_text, 64 << 10),
|
||||
snippet: i.snippet,
|
||||
replace: i.replace.map(range_from_wit),
|
||||
sort_text: i.sort_text.map(|t| clip(t, 64)),
|
||||
filter_text: i.filter_text.map(|t| clip(t, MAX_TITLE)),
|
||||
documentation: i.documentation.map(|d| clip(d, 16 << 10)),
|
||||
additional_edits: i
|
||||
.additional_edits
|
||||
.into_iter()
|
||||
.take(MAX_ADDITIONAL_EDITS)
|
||||
.map(edit_from_wit)
|
||||
.collect(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -699,27 +699,20 @@ impl Runtime {
|
||||
) -> Result<Vec<CodeAction>, CallError> {
|
||||
let d = doc_to_wit(doc);
|
||||
let actions = self.provider_call(timeout, |p, s| p.call_code_actions(s, &d, range_to_wit(selection)))?;
|
||||
Ok(actions
|
||||
.into_iter()
|
||||
.take(MAX_PROVIDER_ITEMS)
|
||||
.map(|a| CodeAction {
|
||||
title: clip(a.title, MAX_TITLE),
|
||||
kind: a.kind.map(|k| clip(k, 64)),
|
||||
preferred: a.preferred,
|
||||
edits: a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let edits = f
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|e| ide_core::TextEdit { range: range_from_wit(e.range), new_text: e.text })
|
||||
.collect();
|
||||
(std::path::PathBuf::from(f.path), edits)
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect())
|
||||
Ok(actions.into_iter().take(MAX_PROVIDER_ITEMS).map(code_action_from_wit).collect())
|
||||
}
|
||||
|
||||
/// The edits of an action `provide_code_actions` returned with `data`.
|
||||
pub fn resolve_code_action(
|
||||
&mut self,
|
||||
doc: &ProviderDocument,
|
||||
action: &CodeAction,
|
||||
timeout: Duration,
|
||||
) -> Result<CodeAction, CallError> {
|
||||
let d = doc_to_wit(doc);
|
||||
let a = code_action_to_wit(action);
|
||||
let resolved = self.provider_call(timeout, |p, s| p.call_resolve_code_action(s, &d, &a))?;
|
||||
resolved.map(code_action_from_wit).map_err(|e| CallError::Guest(e.into()))
|
||||
}
|
||||
|
||||
pub fn provide_definition(
|
||||
@@ -968,6 +961,47 @@ const MAX_VIEW_ITEMS: usize = 20_000;
|
||||
const MAX_CELL: usize = 64 << 10;
|
||||
const MAX_HTML: usize = 4 << 20;
|
||||
|
||||
/// Most additional edits of a completion item.
|
||||
const MAX_ADDITIONAL_EDITS: usize = 100;
|
||||
|
||||
fn edit_from_wit(e: wit_types::TextEdit) -> ide_core::TextEdit {
|
||||
ide_core::TextEdit { range: range_from_wit(e.range), new_text: e.text }
|
||||
}
|
||||
|
||||
fn code_action_from_wit(a: wit_prov::CodeAction) -> CodeAction {
|
||||
CodeAction {
|
||||
title: clip(a.title, MAX_TITLE),
|
||||
kind: a.kind.map(|k| clip(k, 64)),
|
||||
preferred: a.preferred,
|
||||
edits: a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|f| (std::path::PathBuf::from(f.path), f.edits.into_iter().map(edit_from_wit).collect()))
|
||||
.collect(),
|
||||
data: a.data.map(|d| clip(d, 64 << 10)),
|
||||
}
|
||||
}
|
||||
|
||||
fn code_action_to_wit(a: &CodeAction) -> wit_prov::CodeAction {
|
||||
wit_prov::CodeAction {
|
||||
title: a.title.clone(),
|
||||
kind: a.kind.clone(),
|
||||
preferred: a.preferred,
|
||||
edits: a
|
||||
.edits
|
||||
.iter()
|
||||
.map(|(path, edits)| wit_prov::FileEdit {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
edits: edits
|
||||
.iter()
|
||||
.map(|e| wit_types::TextEdit { range: range_to_wit(e.range), text: e.new_text.clone() })
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
data: a.data.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_clip(s: Option<String>, max: usize) -> Option<String> {
|
||||
s.map(|s| clip(s, max))
|
||||
}
|
||||
@@ -975,6 +1009,9 @@ fn opt_clip(s: Option<String>, max: usize) -> Option<String> {
|
||||
fn view_from_wit(v: wit_vt::View) -> View {
|
||||
let body = match v.body {
|
||||
wit_vt::Body::Message(m) => ViewBody::Message(clip(m, 16 << 10)),
|
||||
wit_vt::Body::Other(e) => {
|
||||
ViewBody::Message(format!("This view needs a newer version of OpenIDEA ({}).", clip(e.kind, 64)))
|
||||
}
|
||||
wit_vt::Body::Tree(items) => ViewBody::Tree(
|
||||
items
|
||||
.into_iter()
|
||||
@@ -1006,10 +1043,8 @@ fn view_from_wit(v: wit_vt::View) -> View {
|
||||
fields
|
||||
.into_iter()
|
||||
.take(MAX_VIEW_ITEMS)
|
||||
.map(|f| ViewField {
|
||||
key: clip(f.key, 128),
|
||||
label: clip(f.label, MAX_TITLE),
|
||||
value: match f.value {
|
||||
.filter_map(|f| {
|
||||
let value = match f.value {
|
||||
wit_vt::FieldValue::Text(t) => FieldValue::Text(clip(t, MAX_CELL)),
|
||||
wit_vt::FieldValue::Multiline(t) => FieldValue::Multiline(clip(t, 1 << 20)),
|
||||
wit_vt::FieldValue::Checkbox(b) => FieldValue::Checkbox(b),
|
||||
@@ -1017,7 +1052,10 @@ fn view_from_wit(v: wit_vt::View) -> View {
|
||||
options: options.into_iter().take(1000).map(|o| clip(o, MAX_TITLE)).collect(),
|
||||
selected: clip(selected, MAX_TITLE),
|
||||
},
|
||||
},
|
||||
// A field type of a newer API: left out.
|
||||
wit_vt::FieldValue::Other(_) => return None,
|
||||
};
|
||||
Some(ViewField { key: clip(f.key, 128), label: clip(f.label, MAX_TITLE), value })
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
@@ -1067,3 +1105,26 @@ fn event_to_wit_view(e: ViewEvent) -> wit_vt::ViewEvent {
|
||||
ViewEvent::Message { text } => W::Message(text),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ext(kind: &str) -> wit_types::Extension {
|
||||
wit_types::Extension { kind: kind.into(), data: "{}".into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bodies_and_fields_of_a_newer_api_degrade() {
|
||||
let view = |body| wit_vt::View { toolbar: Vec::new(), body, status: None };
|
||||
let shown = view_from_wit(view(wit_vt::Body::Other(ext("markdown"))));
|
||||
assert_eq!(shown.body, ViewBody::Message("This view needs a newer version of OpenIDEA (markdown).".into()));
|
||||
let field = |key: &str, value| wit_vt::Field { key: key.into(), label: key.into(), value };
|
||||
let form = view_from_wit(view(wit_vt::Body::Form(vec![
|
||||
field("color", wit_vt::FieldValue::Other(ext("color"))),
|
||||
field("name", wit_vt::FieldValue::Text("n".into())),
|
||||
])));
|
||||
let ViewBody::Form(fields) = form.body else { panic!("a form") };
|
||||
assert_eq!(fields.iter().map(|f| f.key.as_str()).collect::<Vec<_>>(), ["name"], "unknown fields are left out");
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,20 @@ pub enum ActionSource {
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ActionSource {
|
||||
/// As plugins see it.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Keyboard => "keyboard",
|
||||
Self::Menu => "menu",
|
||||
Self::Toolbar => "toolbar",
|
||||
Self::ContextMenu => "context-menu",
|
||||
Self::Search => "search",
|
||||
Self::Other => "other",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActionPerformed {
|
||||
@@ -348,9 +362,14 @@ pub struct CompletionItem {
|
||||
/// WIT `completion-kind` name (`method`, `keyword`, …).
|
||||
pub kind: Option<String>,
|
||||
pub insert_text: String,
|
||||
/// `insert_text` has tab stops and placeholders.
|
||||
pub snippet: bool,
|
||||
pub replace: Option<ide_core::Range>,
|
||||
pub sort_text: Option<String>,
|
||||
pub filter_text: Option<String>,
|
||||
pub documentation: Option<String>,
|
||||
/// Applied with the item elsewhere in the document (an import).
|
||||
pub additional_edits: Vec<ide_core::TextEdit>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -365,6 +384,8 @@ pub struct CodeAction {
|
||||
pub kind: Option<String>,
|
||||
pub preferred: bool,
|
||||
pub edits: Vec<(PathBuf, Vec<ide_core::TextEdit>)>,
|
||||
/// The plugin's reference: the edits come from `resolve_code_action`.
|
||||
pub data: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -440,20 +440,11 @@ impl vcs::Host for StoreData {
|
||||
}
|
||||
}
|
||||
|
||||
fn kind_from_wit(k: events::EventKind) -> EventKind {
|
||||
match k {
|
||||
events::EventKind::FileOpened => EventKind::FileOpened,
|
||||
events::EventKind::FileSaved => EventKind::FileSaved,
|
||||
events::EventKind::EditorFocused => EventKind::EditorFocused,
|
||||
events::EventKind::ActionPerformed => EventKind::ActionPerformed,
|
||||
events::EventKind::VcsChanged => EventKind::VcsChanged,
|
||||
events::EventKind::Scheduled => EventKind::Scheduled,
|
||||
}
|
||||
}
|
||||
|
||||
impl events::Host for StoreData {
|
||||
fn subscribe(&mut self, kind: events::EventKind) -> Fallible<()> {
|
||||
let kind = kind_from_wit(kind);
|
||||
fn subscribe(&mut self, kind: String) -> Fallible<()> {
|
||||
let Some(kind) = EventKind::parse(&kind) else {
|
||||
return Ok(Err(wit::Error::Invalid(format!("no event kind {kind:?} in this OpenIDEA"))));
|
||||
};
|
||||
if let Some(cap) = kind.capability()
|
||||
&& let Err(e) = self.require(cap)
|
||||
{
|
||||
@@ -463,8 +454,10 @@ impl events::Host for StoreData {
|
||||
Ok(Ok(()))
|
||||
}
|
||||
|
||||
fn unsubscribe(&mut self, kind: events::EventKind) -> wasmtime::Result<()> {
|
||||
self.host.subscribe(kind_from_wit(kind), false);
|
||||
fn unsubscribe(&mut self, kind: String) -> wasmtime::Result<()> {
|
||||
if let Some(kind) = EventKind::parse(&kind) {
|
||||
self.host.subscribe(kind, false);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -542,10 +535,10 @@ impl diagnostics::Host for StoreData {
|
||||
diagnostics::Severity::Hint => ide_core::Severity::Hint,
|
||||
},
|
||||
message: clip(d.message, 4096),
|
||||
source: Some(source.clone()),
|
||||
source: Some(d.source.map_or_else(|| source.clone(), |s| clip(s, 128))),
|
||||
code: d.code.map(|c| clip(c, 128)),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
unnecessary: d.tags.iter().any(|t| t == "unnecessary"),
|
||||
deprecated: d.tags.iter().any(|t| t == "deprecated"),
|
||||
server: Some(source.clone()),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
86dfe70a30ab1f7955a16e96c1b32c8be663456b871cc4d3bed7dc6052c062da
|
||||
c9acbc021f3840649823cb7680e13907d429c6fda8271fdb0ae6e5ea89ed15ee
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
0dacb82ac35c1f132dc66e85dbf0663b729f818279d3b32cd06403e502fbf880
|
||||
2fb6aa879562733bf5b7f11dabe8fc6a415c9ef695868fe7845417a4245d2dc8
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
0ad2e4c6977a576b7eb27fc1e535fd056dd9da64bdfe6cfda9ca9f57537d0384
|
||||
25b0f419a68a3b1651d3c2774d834b05e40ede52bc5ed8c0eba6d27a204efe82
|
||||
@@ -40,3 +40,11 @@ title = "insert"
|
||||
[[contributes.commands]]
|
||||
id = "cancel"
|
||||
title = "cancel"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "subscribe"
|
||||
title = "subscribe"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "diagnose"
|
||||
title = "diagnose"
|
||||
@@ -14,7 +14,9 @@ wit_bindgen::generate!({
|
||||
generate_all,
|
||||
});
|
||||
|
||||
use exports::openidea::plugin::providers::{self, CodeAction, CompletionItem, Document, InlineSuggestion, LineMarker};
|
||||
use exports::openidea::plugin::providers::{
|
||||
self, CodeAction, CompletionItem, Document, FileEdit, InlineSuggestion, LineMarker,
|
||||
};
|
||||
use exports::openidea::plugin::syntax_provider::{self, Fold, Symbol, Token};
|
||||
use exports::openidea::plugin::{commands, event_handler, lifecycle};
|
||||
use openidea::plugin::{invocation::Invocation, types};
|
||||
@@ -67,6 +69,23 @@ impl commands::Guest for Misbehave {
|
||||
}
|
||||
// The user gave up: not the plugin failing.
|
||||
"cancel" => Err(types::Error::Cancelled),
|
||||
// Event kinds are names: one this IDE doesn't know is refused.
|
||||
"subscribe" => openidea::plugin::events::subscribe(&arg.unwrap_or_default()).map(|()| None),
|
||||
// Tagged problems from another tool on the line 0 of `arg`.
|
||||
"diagnose" => {
|
||||
use openidea::plugin::diagnostics::{self, Diagnostic, Severity};
|
||||
let start = types::Position { line: 0, character: 0 };
|
||||
let d = Diagnostic {
|
||||
range: types::Range { start, end: start },
|
||||
severity: Severity::Warning,
|
||||
message: "unused".into(),
|
||||
code: None,
|
||||
source: Some("lint".into()),
|
||||
tags: vec!["unnecessary".into(), "glowing".into()],
|
||||
related: Vec::new(),
|
||||
};
|
||||
diagnostics::publish(&arg.unwrap_or_default(), &[d]).map(|()| None)
|
||||
}
|
||||
other => Err(types::Error::NotFound(format!("command {other}"))),
|
||||
}
|
||||
}
|
||||
@@ -113,14 +132,24 @@ impl syntax_provider::Guest for Misbehave {
|
||||
impl providers::Guest for Misbehave {
|
||||
fn completion(doc: Document, _at: types::Position, _trigger: Option<String>) -> Vec<CompletionItem> {
|
||||
behave(&doc.text);
|
||||
// `rich`: a snippet that also adds an import.
|
||||
let rich = doc.text == "rich";
|
||||
let start = types::Position { line: 0, character: 0 };
|
||||
vec![CompletionItem {
|
||||
label: doc.path.clone(),
|
||||
detail: None,
|
||||
kind: Some("keyword".into()),
|
||||
insert_text: doc.path,
|
||||
insert_text: if rich { "f(${1:x})$0".into() } else { doc.path },
|
||||
snippet: rich,
|
||||
replace: None,
|
||||
sort_text: None,
|
||||
filter_text: rich.then(|| "fun".into()),
|
||||
documentation: None,
|
||||
additional_edits: if rich {
|
||||
vec![types::TextEdit { range: types::Range { start, end: start }, text: "use f;\n".into() }]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -128,8 +157,27 @@ impl providers::Guest for Misbehave {
|
||||
None
|
||||
}
|
||||
|
||||
fn code_actions(_doc: Document, _selection: types::Range) -> Vec<CodeAction> {
|
||||
Vec::new()
|
||||
/// `lazy`: one action whose edits come from `resolve-code-action`.
|
||||
fn code_actions(doc: Document, _selection: types::Range) -> Vec<CodeAction> {
|
||||
if doc.text != "lazy" {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![CodeAction {
|
||||
title: "Fix later".into(),
|
||||
kind: Some("quickfix".into()),
|
||||
preferred: false,
|
||||
edits: Vec::new(),
|
||||
data: Some("fix".into()),
|
||||
}]
|
||||
}
|
||||
|
||||
fn resolve_code_action(doc: Document, action: CodeAction) -> Result<CodeAction, types::Error> {
|
||||
if action.data.as_deref() != Some("fix") {
|
||||
return Err(types::Error::Invalid("not one of mine".into()));
|
||||
}
|
||||
let start = types::Position { line: 0, character: 0 };
|
||||
let edit = types::TextEdit { range: types::Range { start, end: start }, text: "fixed ".into() };
|
||||
Ok(CodeAction { edits: vec![FileEdit { path: doc.path, edits: vec![edit] }], ..action })
|
||||
}
|
||||
|
||||
fn definition(_doc: Document, _at: types::Position) -> Vec<types::Location> {
|
||||
|
||||
@@ -6,6 +6,14 @@ block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "C"
|
||||
tree-sitter = "c"
|
||||
scratch-template = '''
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
$END$
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
[[language-servers]]
|
||||
name = "clangd"
|
||||
|
||||
@@ -6,6 +6,14 @@ block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "C++"
|
||||
tree-sitter = "cpp"
|
||||
scratch-template = '''
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
$END$
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
[[language-servers]]
|
||||
name = "clangd"
|
||||
|
||||
@@ -6,6 +6,13 @@ block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = false }
|
||||
ui-mode = "Go"
|
||||
tree-sitter = "go"
|
||||
scratch-template = '''
|
||||
package main
|
||||
|
||||
func main() {
|
||||
$END$
|
||||
}
|
||||
'''
|
||||
|
||||
[[language-servers]]
|
||||
name = "gopls"
|
||||
|
||||
@@ -6,6 +6,13 @@ block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "Java"
|
||||
tree-sitter = "java"
|
||||
scratch-template = '''
|
||||
class Scratch {
|
||||
public static void main(String[] args) {
|
||||
$END$
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
# Microsoft java-debug runs inside jdtls as a bundle (`initializationOptions.bundles`,
|
||||
# added when installed); sessions start with `vscode.java.startDebugSession` and the
|
||||
|
||||
@@ -6,6 +6,11 @@ block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "Kotlin"
|
||||
tree-sitter = "kotlin"
|
||||
scratch-template = '''
|
||||
fun main() {
|
||||
$END$
|
||||
}
|
||||
'''
|
||||
|
||||
[[language-servers]]
|
||||
name = "kotlin-lsp"
|
||||
|
||||
@@ -6,6 +6,11 @@ block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "Rust"
|
||||
tree-sitter = "rust"
|
||||
scratch-template = '''
|
||||
fn main() {
|
||||
$END$
|
||||
}
|
||||
'''
|
||||
|
||||
[[language-servers]]
|
||||
name = "rust-analyzer"
|
||||
|
||||
@@ -76,6 +76,9 @@
|
||||
"index_100k/find_files/ordcon": 10000,
|
||||
"index_100k/find_files/src/user": 10000,
|
||||
"index_100k/find_files/PaymentService": 10000,
|
||||
"index_100k/find_dirs/util": 5000,
|
||||
"index_100k/find_dirs/src/ui": 5000,
|
||||
"index_100k/find_dirs/a": 5000,
|
||||
"index_100k/find_symbols/OCo": 15000,
|
||||
"index_100k/find_symbols/q": 15000,
|
||||
"index_100k/find_symbols/invoiceRepo": 15000,
|
||||
|
||||
@@ -44,7 +44,8 @@ The plugin API is defined in [`wit/`](../wit/) (`openidea:[email protected]`, world
|
||||
The `openidea-plugin` tool scaffolds, builds, checks and links plugins:
|
||||
|
||||
```sh
|
||||
cargo install --path crates/ide-host --bin openidea-plugin # or: cargo run -p ide-host --bin openidea-plugin -- …
|
||||
cargo install --locked --git https://github.com/l0ng-ai/openidea ide-host --bin openidea-plugin
|
||||
# in a checkout of this repository: cargo install --path crates/ide-host --bin openidea-plugin
|
||||
|
||||
openidea-plugin new my-plugin # Rust command plugin (SDK)
|
||||
openidea-plugin new my-theme --template theme # also: icon-theme, language
|
||||
@@ -54,6 +55,17 @@ openidea-plugin build # → dist/plugin.wasm, t
|
||||
openidea-plugin link # load this folder in the IDE
|
||||
```
|
||||
|
||||
Each release also attaches the tool for Linux x64
|
||||
(`openidea-plugin-linux-x86_64.gz`). A plugin is a project of its own: keep it
|
||||
in its own repository, and list it in the community marketplace when it is
|
||||
ready (§8.1).
|
||||
|
||||
A Rust plugin made by `new` depends on the SDK of the tool's release, from
|
||||
this repository's tag (`openidea-plugin = { git = "…", tag = "vX.Y.Z" }`);
|
||||
change the tag to build against a later API. Inside a checkout of this
|
||||
repository, or with `--sdk <path to sdk/rust/openidea-plugin>`, it depends on
|
||||
that SDK by path instead.
|
||||
|
||||
`build` runs `cargo build --release --target wasm32-wasip2` (installing the
|
||||
target through rustup if needed), copies the component to the manifest's
|
||||
`wasm` path and runs `check`. `check` validates the package exactly as
|
||||
@@ -212,7 +224,7 @@ edition = "2024"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "…/sdk/rust/openidea-plugin" }
|
||||
openidea-plugin = { git = "https://github.com/l0ng-ai/openidea", tag = "vX.Y.Z" } # or { path = "…/sdk/rust/openidea-plugin" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
@@ -321,6 +333,11 @@ Events are batched: a running plugin gets them within a fraction of a second,
|
||||
an idle one collects them for 2 s before it is woken, so frequent events
|
||||
(Key Promoter's actions) don't keep it alive.
|
||||
|
||||
Kinds are names (`subscribe` takes a string), so later IDEs add kinds without
|
||||
a new API: an IDE refuses a kind it doesn't know with `invalid`, and a kind
|
||||
newer than the plugin's SDK arrives as `Event::Other { kind, data }` (JSON).
|
||||
The SDK's event enums are `#[non_exhaustive]`; match them with a `_` arm.
|
||||
|
||||
### Providers
|
||||
|
||||
Declare what the plugin provides in the editor; only plugins whose
|
||||
@@ -338,7 +355,14 @@ Then `register_plugin!(MyPlugin, providers)` and implement
|
||||
the document (path, language, version, text). Results join the language
|
||||
servers' (completion lists, ⌥⏎ quick fixes, ⌘B, gutter icons; a code action
|
||||
carries edits for any files, applied as one change). A completion item's
|
||||
`kind` (`CompletionKind` in the SDK, a string in the WIT) picks its icon.
|
||||
`kind` (`CompletionKind` in the SDK, a string in the WIT) picks its icon; it
|
||||
can be a `snippet` (`$1`, `${1:name}`, `$0`), match on `filter_text` instead
|
||||
of its label, and bring `additional_edits` elsewhere in the document (an
|
||||
import). A code action can leave `edits` empty and set `data`: its edits are
|
||||
then computed by `resolve_code_action` when the user picks it, under the
|
||||
command budget instead of the 50 ms. Problems (`publish_diagnostics`) can name
|
||||
the tool that found them (`source`) and be `unnecessary` (faded) or
|
||||
`deprecated` (struck through).
|
||||
Editor providers run under the edit-path budget: 50 ms, after which the
|
||||
result is dropped, and an interruption at 500 ms. Every plugin providing a
|
||||
kind is asked at the same time, so each has the whole budget.
|
||||
@@ -393,6 +417,9 @@ collapse of items, form fields, table cells, inserted and deleted rows, and
|
||||
`html` messages. A tree is a flat list whose items name their `parent`; an
|
||||
`expandable` item gets its children when it is expanded. A table gets only
|
||||
the rows it shows (`viewport`): report `total_rows` and return those.
|
||||
Bodies, field types and view events added by later APIs travel as `Other {
|
||||
kind, data }`: an IDE that doesn't know a body says it needs updating, and
|
||||
leaves out a field type it doesn't know.
|
||||
|
||||
Showing a view activates the plugin (`on-view:<id>`). `views` become tool
|
||||
windows; a `customEditors` file (`priority = "default"`) opens in the
|
||||
@@ -758,8 +785,19 @@ granted, and starts the approved program.
|
||||
- **Project plugins:** put (or symlink) the package in
|
||||
`<project>/.openidea/plugins/<name>/`. They load only in trusted projects and
|
||||
only after you approve their capabilities.
|
||||
- **Where:** installing, removing, enabling, granting and reloading plugins
|
||||
work on the welcome screen and in trusted projects. A project opened in
|
||||
restricted mode can browse the marketplace and show a package's install
|
||||
page, but not change which plugin code runs.
|
||||
- Commands appear in Search Everywhere › Actions under their category, and can
|
||||
be bound in Settings › Keymap like any other action.
|
||||
- **Troubleshooting:** `openidea-plugin check` says why a package would be
|
||||
refused. Settings › Plugins shows each plugin's state, why it failed if it
|
||||
did, and its call stats (§3, _Sandbox and limits_). `host::log` lines go to
|
||||
the IDE log (Help › _Show Log in Finder_ / _Explorer_ / _Files_) tagged with
|
||||
the plugin id; debug and trace lines are written when the IDE is started
|
||||
with `RUST_LOG=info,ide_plugin=trace`. `eprintln!` output is logged as
|
||||
well, and a panic's message is shown with the crash.
|
||||
|
||||
## 8. Distribution
|
||||
|
||||
@@ -890,7 +928,10 @@ only grows:
|
||||
Extend with new types and new functions (or interfaces). `types.error` is
|
||||
used everywhere and is no exception; new situations use `failed(string)`
|
||||
or `invalid(string)`. Sets that keep growing (completion, token, symbol and
|
||||
fold kinds, icons) are strings for this reason.
|
||||
fold kinds, icons, event kinds, action sources, diagnostic tags) are
|
||||
strings for this reason, and variants that grow (`event`, view `body`,
|
||||
`view-event`, `field-value`) have an `other(extension)` case, a kind and
|
||||
JSON data, that carries later cases to older plugins and IDEs.
|
||||
2. **Host interfaces (imports) may gain functions and interfaces**: older
|
||||
components don't import them.
|
||||
3. **Plugin interfaces (exports) never gain functions** once released: the
|
||||
@@ -902,6 +943,11 @@ only grows:
|
||||
minor with a message that says to update the IDE or rebuild with the SDK.
|
||||
5. **One version number**: the `wit/` package version, `ENGINE_VERSION` and
|
||||
`API_VERSION` agree, and the SDK's `wit/` copy is identical to `wit/`.
|
||||
6. **1.x calls are synchronous and pass documents whole.** Host calls block
|
||||
the plugin's instance, and providers get the document's text with each
|
||||
call. WASI 0.3 async components come with 2.0, behind an adapter in the
|
||||
host that keeps 1.x plugins running; incremental document sync, if
|
||||
needed, is a new interface.
|
||||
|
||||
Checked automatically:
|
||||
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
aa09a92c0ba9d85a01c56bbf4455e40ae44f005b443ce1002bbe8011408ff975
|
||||
28e4bf10a41bdda011111b0e150ebe96205c57f410bad98c19eea3f1286349d6
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
908c2fd177ad2bb9a8a8492505151c3b81579191156c5ec53f705127f50a8ee9
|
||||
7e015486cc916f5edbac542863373fd7204f5bcd534f6c408d5f9d2b72913862
|
||||
@@ -97,12 +97,8 @@ fn diagnostic(p: &Problem, text: &str) -> Diagnostic {
|
||||
let line_len = text.split('\n').nth(p.line as usize).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
let start = p.column.unwrap_or(0).min(line_len);
|
||||
let end = if p.column.is_some() && start < line_len { start + 1 } else { line_len };
|
||||
Diagnostic {
|
||||
range: Range::new(Position::new(p.line, start), Position::new(p.line, end.max(start))),
|
||||
severity: p.severity,
|
||||
message: p.message.clone(),
|
||||
code: Some(p.check.clone()),
|
||||
}
|
||||
let range = Range::new(Position::new(p.line, start), Position::new(p.line, end.max(start)));
|
||||
Diagnostic::new(range, p.severity, p.message.clone()).code(p.check.clone())
|
||||
}
|
||||
|
||||
/// The project containing `path`.
|
||||
@@ -188,6 +184,7 @@ impl Providers for Checkstyle {
|
||||
kind: Some("quickfix".into()),
|
||||
preferred: true,
|
||||
edits: vec![(doc.path.clone(), vec![edit])],
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
64270fa0f5b3084c78764f09b8ce161742fdbff9c28fb90590da39594e558db1
|
||||
a6cf59e74595e13908e2cbf1752c58665c6963de258413c9d7332d2a7dd9cbd0
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
22876f842f727a2b9aa292986df3393f5b5f30c5c34319f5665f7d2701c8accf
|
||||
b8dde206a74b222b93e61056d4cbe403617ae240d142e01e91420a2aacdb2da4
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
14c60782eca79a25cf2c38d58c05be0eb97c4afc607d4cc83302d1445d094aab
|
||||
a681c2abd4a65d6aeb62efd514e9b170f4fca52b0c14d2d380a3b04be0a3fbc6
|
||||
@@ -52,12 +52,9 @@ pub fn diagnostics(text: &str, reports: &[Report]) -> Vec<Diagnostic> {
|
||||
.map(|r| {
|
||||
let line = r.line.map_or(0, |l| l.saturating_sub(1)).min(lines.len().saturating_sub(1) as u32);
|
||||
let len = lines.get(line as usize).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
Diagnostic {
|
||||
range: Range::new(Position::new(line, 0), Position::new(line, len)),
|
||||
severity: if r.error { Severity::Error } else { Severity::Warning },
|
||||
message: r.message.clone(),
|
||||
code: Some("graphviz".into()),
|
||||
}
|
||||
let range = Range::new(Position::new(line, 0), Position::new(line, len));
|
||||
let severity = if r.error { Severity::Error } else { Severity::Warning };
|
||||
Diagnostic::new(range, severity, r.message.clone()).code("graphviz")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7f5aacde2b8a8bcee5365c8cbda91045195688899c6537dc2159037cca74a672
|
||||
3c83bc9559df54457e19e650cdd21bab9d609e22daaa1fc4f596910b70834a34
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
45a7ee993b5c234b0d25e5b05ef60e714fa3edf63d6bd0d6a29b13587c8d09ce
|
||||
63f1bbdf6eca5a4642cd3453ae384ff3f876de0373c12008b757a63852164b71
|
||||
@@ -129,12 +129,8 @@ pub fn header_edit(path: &str, text: &str, year: i64, owner: &str, license: &str
|
||||
fn missing(text: &str) -> Diagnostic {
|
||||
let line = insert_line(text);
|
||||
let len = text.lines().nth(line as usize).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
Diagnostic {
|
||||
range: Range::new(Position::new(line, 0), Position::new(line, len)),
|
||||
severity: Severity::Info,
|
||||
message: "No license header".into(),
|
||||
code: Some(CODE.into()),
|
||||
}
|
||||
Diagnostic::new(Range::new(Position::new(line, 0), Position::new(line, len)), Severity::Info, "No license header")
|
||||
.code(CODE)
|
||||
}
|
||||
|
||||
/// Reports `path` when it takes a header and has none, clears it otherwise.
|
||||
@@ -274,6 +270,7 @@ impl Providers for LicenseHeader {
|
||||
kind: Some("quickfix".into()),
|
||||
preferred: true,
|
||||
edits: vec![(doc.path.clone(), vec![edit])],
|
||||
data: None,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
d5cf81455ae8b2b0fd6d1402d8775913bd7999db62b9bdf87675890ce52b1e80
|
||||
0db5cb24c358651d0e728ab3efb52286290c1a38ec379435225c935d4165ad6a
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
227c8150c6ad7a5a20236764f149c876cbbc3b082763bf2e7fc05de99726b740
|
||||
257478b050ea360c55e904f2a89c6069293139ff0d97ba860de3f29dac927787
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
bbadcaa7a86a3e0a3f8be6d86aed2229d5cdfd128fda3435b4d64c7e19ad1df2
|
||||
21e7510d6a3712bf0f21d53a5c8d652e3c2787d89a1fc25998cde96efe124207
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
09cc92e8e731f8f59f3857a71f9a30cc3d9e04a1c32092920f573b0f26592855
|
||||
04844bfbfbcb1770f4f4742658944c592922b037b2387e9340de58ef0d9baacc
|
||||
@@ -152,24 +152,12 @@ mod imp {
|
||||
wit::vcs::fetch(p).map_err(error)
|
||||
}
|
||||
|
||||
fn kind(k: EventKind) -> wit::events::EventKind {
|
||||
use wit::events::EventKind as K;
|
||||
match k {
|
||||
EventKind::FileOpened => K::FileOpened,
|
||||
EventKind::FileSaved => K::FileSaved,
|
||||
EventKind::EditorFocused => K::EditorFocused,
|
||||
EventKind::ActionPerformed => K::ActionPerformed,
|
||||
EventKind::VcsChanged => K::VcsChanged,
|
||||
EventKind::Scheduled => K::Scheduled,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscribe(k: EventKind) -> Result<(), Error> {
|
||||
wit::events::subscribe(kind(k)).map_err(error)
|
||||
wit::events::subscribe(k.name()).map_err(error)
|
||||
}
|
||||
|
||||
pub fn unsubscribe(k: EventKind) {
|
||||
wit::events::unsubscribe(kind(k))
|
||||
wit::events::unsubscribe(k.name())
|
||||
}
|
||||
|
||||
pub fn begin_task(title: &str, cancellable: bool) -> TaskRes {
|
||||
@@ -189,7 +177,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn publish_diagnostics(path: &str, items: &[Diagnostic]) -> Result<(), Error> {
|
||||
use wit::diagnostics::{Diagnostic as D, Severity as S};
|
||||
use wit::diagnostics::{Diagnostic as D, RelatedInformation as R, Severity as S};
|
||||
let items: Vec<D> = items
|
||||
.iter()
|
||||
.map(|d| D {
|
||||
@@ -202,6 +190,23 @@ mod imp {
|
||||
},
|
||||
message: d.message.clone(),
|
||||
code: d.code.clone(),
|
||||
source: d.source.clone(),
|
||||
tags: [(d.unnecessary, "unnecessary"), (d.deprecated, "deprecated")]
|
||||
.into_iter()
|
||||
.filter(|(on, _)| *on)
|
||||
.map(|(_, tag)| tag.to_owned())
|
||||
.collect(),
|
||||
related: d
|
||||
.related
|
||||
.iter()
|
||||
.map(|r| R {
|
||||
location: wit::types::Location {
|
||||
path: r.location.path.clone(),
|
||||
range: range_out(r.location.range),
|
||||
},
|
||||
message: r.message.clone(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
wit::diagnostics::publish(path, &items).map_err(error)
|
||||
@@ -264,7 +269,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn event(e: wit::events::Event) -> Event {
|
||||
use wit::events::{ActionSource as S, Event as E};
|
||||
use wit::events::Event as E;
|
||||
match e {
|
||||
E::FileOpened(p) => Event::FileOpened(p),
|
||||
E::FileSaved(p) => Event::FileSaved(p),
|
||||
@@ -274,16 +279,10 @@ mod imp {
|
||||
E::ActionPerformed(a) => Event::ActionPerformed(ActionPerformed {
|
||||
action: a.action,
|
||||
title: a.title,
|
||||
source: match a.source {
|
||||
S::Keyboard => ActionSource::Keyboard,
|
||||
S::Menu => ActionSource::Menu,
|
||||
S::Toolbar => ActionSource::Toolbar,
|
||||
S::ContextMenu => ActionSource::ContextMenu,
|
||||
S::Search => ActionSource::Search,
|
||||
S::Other => ActionSource::Other,
|
||||
},
|
||||
source: ActionSource::parse(&a.source),
|
||||
shortcut: a.shortcut,
|
||||
}),
|
||||
E::Other(x) => Event::Other { kind: x.kind, data: x.data },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,6 +255,16 @@ macro_rules! __providers_exports {
|
||||
$crate::__rt::code_actions::<$plugin>(doc, selection)
|
||||
}
|
||||
|
||||
fn resolve_code_action(
|
||||
doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document,
|
||||
action: $crate::providers_bindings::exports::openidea::plugin::providers::CodeAction,
|
||||
) -> ::core::result::Result<
|
||||
$crate::providers_bindings::exports::openidea::plugin::providers::CodeAction,
|
||||
$crate::bindings::openidea::plugin::types::Error,
|
||||
> {
|
||||
$crate::__rt::resolve_code_action::<$plugin>(doc, action)
|
||||
}
|
||||
|
||||
fn definition(
|
||||
doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document,
|
||||
at: $crate::bindings::openidea::plugin::types::Position,
|
||||
@@ -420,9 +430,12 @@ pub mod __rt {
|
||||
detail: i.detail,
|
||||
kind: i.kind.map(|k| k.as_str().to_owned()),
|
||||
insert_text: i.insert_text,
|
||||
snippet: i.snippet,
|
||||
replace: i.replace.map(crate::host::__range_to),
|
||||
sort_text: i.sort_text,
|
||||
filter_text: i.filter_text,
|
||||
documentation: i.documentation,
|
||||
additional_edits: i.additional_edits.into_iter().map(edit_out).collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -443,25 +456,54 @@ pub mod __rt {
|
||||
sel: b::types::Range,
|
||||
) -> Vec<w::CodeAction> {
|
||||
let d = doc(d);
|
||||
with::<T, _>(|x| x.code_actions(&d, crate::host::__range_from(sel)))
|
||||
.into_iter()
|
||||
.map(|a| w::CodeAction {
|
||||
title: a.title,
|
||||
kind: a.kind,
|
||||
preferred: a.preferred,
|
||||
edits: a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|(path, edits)| w::FileEdit {
|
||||
path,
|
||||
edits: edits
|
||||
.into_iter()
|
||||
.map(|e| b::types::TextEdit { range: crate::host::__range_to(e.range), text: e.text })
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
with::<T, _>(|x| x.code_actions(&d, crate::host::__range_from(sel))).into_iter().map(action_out).collect()
|
||||
}
|
||||
|
||||
pub fn resolve_code_action<T: Plugin + p::Providers + Default>(
|
||||
d: w::Document,
|
||||
action: w::CodeAction,
|
||||
) -> Result<w::CodeAction, b::types::Error> {
|
||||
let d = doc(d);
|
||||
with::<T, _>(|x| x.resolve_code_action(&d, action_in(action))).map(action_out).map_err(error_out)
|
||||
}
|
||||
|
||||
fn edit_out(e: crate::TextEdit) -> b::types::TextEdit {
|
||||
b::types::TextEdit { range: crate::host::__range_to(e.range), text: e.text }
|
||||
}
|
||||
|
||||
fn action_out(a: p::CodeAction) -> w::CodeAction {
|
||||
w::CodeAction {
|
||||
title: a.title,
|
||||
kind: a.kind,
|
||||
preferred: a.preferred,
|
||||
edits: a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|(path, edits)| w::FileEdit { path, edits: edits.into_iter().map(edit_out).collect() })
|
||||
.collect(),
|
||||
data: a.data,
|
||||
}
|
||||
}
|
||||
|
||||
fn action_in(a: w::CodeAction) -> p::CodeAction {
|
||||
p::CodeAction {
|
||||
title: a.title,
|
||||
kind: a.kind,
|
||||
preferred: a.preferred,
|
||||
edits: a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let edits = f
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|e| crate::TextEdit { range: crate::host::__range_from(e.range), text: e.text })
|
||||
.collect();
|
||||
(f.path, edits)
|
||||
})
|
||||
.collect(),
|
||||
data: a.data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn definition<T: Plugin + p::Providers + Default>(
|
||||
@@ -531,6 +573,9 @@ pub mod __rt {
|
||||
v::FieldValue::Multiline(t) => vt::FieldValue::Multiline(t),
|
||||
v::FieldValue::Checkbox(c) => vt::FieldValue::Checkbox(c),
|
||||
v::FieldValue::Choice(o, s) => vt::FieldValue::Choice((o, s)),
|
||||
v::FieldValue::Other { kind, data } => {
|
||||
vt::FieldValue::Other(b::types::Extension { kind, data })
|
||||
}
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
@@ -543,6 +588,7 @@ pub mod __rt {
|
||||
editable: t.editable,
|
||||
}),
|
||||
v::Body::Html(h) => vt::Body::Html(h),
|
||||
v::Body::Other { kind, data } => vt::Body::Other(b::types::Extension { kind, data }),
|
||||
};
|
||||
vt::View {
|
||||
toolbar: view
|
||||
@@ -582,6 +628,7 @@ pub mod __rt {
|
||||
vt::ViewEvent::InsertRow(r) => v::ViewEvent::InsertRow(r),
|
||||
vt::ViewEvent::DeleteRows(r) => v::ViewEvent::DeleteRows(r),
|
||||
vt::ViewEvent::Message(m) => v::ViewEvent::Message(m),
|
||||
vt::ViewEvent::Other(x) => v::ViewEvent::Other { kind: x.kind, data: x.data },
|
||||
};
|
||||
with::<T, _>(|p| p.handle(&view, event, &ctx)).map_err(error_out)
|
||||
}
|
||||
|
||||
@@ -722,11 +722,8 @@ mod tests {
|
||||
let out = mock.invocation().project().unwrap().run_process("java", &["-version".into()], None).unwrap();
|
||||
assert_eq!(out.stdout, "-version");
|
||||
assert_eq!(mock.process_runs()[0].cwd.as_deref(), Some("/project"));
|
||||
host::publish_diagnostics(
|
||||
"/project/a.java",
|
||||
&[Diagnostic { range: Range::default(), severity: Severity::Warning, message: "m".into(), code: None }],
|
||||
)
|
||||
.unwrap();
|
||||
host::publish_diagnostics("/project/a.java", &[Diagnostic::new(Range::default(), Severity::Warning, "m")])
|
||||
.unwrap();
|
||||
assert_eq!(mock.diagnostics()["/project/a.java"].len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -92,12 +92,18 @@ pub struct CompletionItem {
|
||||
pub label: String,
|
||||
pub detail: Option<String>,
|
||||
pub kind: Option<CompletionKind>,
|
||||
/// With `snippet`, tab stops and placeholders (`$1`, `${1:name}`, `$0`).
|
||||
pub insert_text: String,
|
||||
pub snippet: bool,
|
||||
/// Replaced on accept; `None`: the word at the caret.
|
||||
pub replace: Option<Range>,
|
||||
pub sort_text: Option<String>,
|
||||
/// Matched against what was typed instead of `label`.
|
||||
pub filter_text: Option<String>,
|
||||
/// Markdown.
|
||||
pub documentation: Option<String>,
|
||||
/// Applied with the item elsewhere in the document (an import).
|
||||
pub additional_edits: Vec<TextEdit>,
|
||||
}
|
||||
|
||||
impl CompletionItem {
|
||||
@@ -107,9 +113,12 @@ impl CompletionItem {
|
||||
detail: None,
|
||||
kind: Some(kind),
|
||||
insert_text: label.into(),
|
||||
snippet: false,
|
||||
replace: None,
|
||||
sort_text: None,
|
||||
filter_text: None,
|
||||
documentation: None,
|
||||
additional_edits: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,6 +138,9 @@ pub struct CodeAction {
|
||||
pub preferred: bool,
|
||||
/// (absolute path, edits) per file.
|
||||
pub edits: Vec<(String, Vec<TextEdit>)>,
|
||||
/// The plugin's own reference: with it and no `edits`, the edits come
|
||||
/// from [`Providers::resolve_code_action`] once the user picks the action.
|
||||
pub data: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -157,6 +169,12 @@ pub trait Providers {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The edits of an action [`Providers::code_actions`] returned with
|
||||
/// `data`, when the user picks it (the command budget applies, not 50 ms).
|
||||
fn resolve_code_action(&mut self, _doc: &Document, action: CodeAction) -> Result<CodeAction, crate::Error> {
|
||||
Ok(action)
|
||||
}
|
||||
|
||||
fn definition(&mut self, _doc: &Document, _at: Position) -> Vec<Location> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
@@ -143,7 +143,9 @@ pub struct StatusItem {
|
||||
pub command: Option<String>,
|
||||
}
|
||||
|
||||
/// Kinds of workbench events; later SDKs add more.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum EventKind {
|
||||
FileOpened,
|
||||
FileSaved,
|
||||
@@ -154,17 +156,46 @@ pub enum EventKind {
|
||||
Scheduled,
|
||||
}
|
||||
|
||||
/// How the user started an action.
|
||||
impl EventKind {
|
||||
/// The name the IDE knows it by.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::FileOpened => "file-opened",
|
||||
Self::FileSaved => "file-saved",
|
||||
Self::EditorFocused => "editor-focused",
|
||||
Self::ActionPerformed => "action-performed",
|
||||
Self::VcsChanged => "vcs-changed",
|
||||
Self::Scheduled => "scheduled",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the user started an action; later IDEs may report more.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ActionSource {
|
||||
Keyboard,
|
||||
Menu,
|
||||
Toolbar,
|
||||
ContextMenu,
|
||||
Search,
|
||||
/// Anything else, including sources this SDK doesn't know.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ActionSource {
|
||||
pub fn parse(name: &str) -> Self {
|
||||
match name {
|
||||
"keyboard" => Self::Keyboard,
|
||||
"menu" => Self::Menu,
|
||||
"toolbar" => Self::Toolbar,
|
||||
"context-menu" => Self::ContextMenu,
|
||||
"search" => Self::Search,
|
||||
_ => Self::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ActionPerformed {
|
||||
/// Action id (`editor.duplicate-line`).
|
||||
@@ -177,6 +208,7 @@ pub struct ActionPerformed {
|
||||
|
||||
/// A workbench event (see [`crate::host::subscribe`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Event {
|
||||
FileOpened(String),
|
||||
FileSaved(String),
|
||||
@@ -186,6 +218,11 @@ pub enum Event {
|
||||
VcsChanged(String),
|
||||
/// The `on-schedule` period elapsed.
|
||||
Scheduled,
|
||||
/// A kind this SDK doesn't know: its name and JSON data.
|
||||
Other {
|
||||
kind: String,
|
||||
data: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// The repository containing a project.
|
||||
@@ -227,6 +264,41 @@ pub struct Diagnostic {
|
||||
pub message: String,
|
||||
/// Rule or check id.
|
||||
pub code: Option<String>,
|
||||
/// The tool that found it, when not the plugin itself.
|
||||
pub source: Option<String>,
|
||||
/// Code that does nothing (shown faded).
|
||||
pub unnecessary: bool,
|
||||
/// Use of something deprecated (struck through).
|
||||
pub deprecated: bool,
|
||||
/// Other places that explain it.
|
||||
pub related: Vec<RelatedInformation>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn new(range: Range, severity: Severity, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
range,
|
||||
severity,
|
||||
message: message.into(),
|
||||
code: None,
|
||||
source: None,
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
related: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code(mut self, code: impl Into<String>) -> Self {
|
||||
self.code = Some(code.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Another place that explains a diagnostic.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RelatedInformation {
|
||||
pub location: Location,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// An HTTP request (see [`crate::host::fetch`]).
|
||||
@@ -276,3 +348,17 @@ pub struct ProcessOutput {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_the_ide_uses() {
|
||||
assert_eq!(EventKind::ActionPerformed.name(), "action-performed");
|
||||
assert_eq!(ActionSource::parse("context-menu"), ActionSource::ContextMenu);
|
||||
assert_eq!(ActionSource::parse("pen"), ActionSource::Other, "a source of a newer IDE");
|
||||
let d = Diagnostic::new(Range::default(), Severity::Hint, "m").code("c");
|
||||
assert_eq!((d.code.as_deref(), d.unnecessary, d.related.len()), (Some("c"), false, 0));
|
||||
}
|
||||
}
|
||||
@@ -110,12 +110,19 @@ impl ListItem {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum FieldValue {
|
||||
Text(String),
|
||||
Multiline(String),
|
||||
Checkbox(bool),
|
||||
/// Options and the chosen one.
|
||||
Choice(Vec<String>, String),
|
||||
/// A field type of a newer plugin API: its kind and JSON data (IDEs that
|
||||
/// don't know it leave the field out).
|
||||
Other {
|
||||
kind: String,
|
||||
data: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -142,6 +149,7 @@ pub struct Table {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Body {
|
||||
Message(String),
|
||||
Tree(Vec<TreeItem>),
|
||||
@@ -151,6 +159,12 @@ pub enum Body {
|
||||
/// Shown in a sandboxed frame; its script talks to the plugin with
|
||||
/// `openidea.postMessage(text)` and `openidea.onMessage(fn)`.
|
||||
Html(String),
|
||||
/// A body of a newer plugin API: its kind and JSON data (IDEs that don't
|
||||
/// know it say they need updating).
|
||||
Other {
|
||||
kind: String,
|
||||
data: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -197,6 +211,7 @@ impl Viewport {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ViewEvent {
|
||||
Button(String),
|
||||
Activate(String),
|
||||
@@ -213,6 +228,11 @@ pub enum ViewEvent {
|
||||
InsertRow(u32),
|
||||
DeleteRows(Vec<u32>),
|
||||
Message(String),
|
||||
/// An event this SDK doesn't know: its kind and JSON data.
|
||||
Other {
|
||||
kind: String,
|
||||
data: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Content of the plugin's declared views and custom editors.
|
||||
|
||||
@@ -2,36 +2,15 @@ package openidea:[email protected];
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
use types.{error};
|
||||
|
||||
enum event-kind {
|
||||
file-opened,
|
||||
file-saved,
|
||||
/// The focused editor changed.
|
||||
editor-focused,
|
||||
/// An IDE action ran. Requires `events.input`.
|
||||
action-performed,
|
||||
/// A repository's state changed (commit, checkout, fetch, …).
|
||||
vcs-changed,
|
||||
/// The plugin's `on-schedule` period elapsed.
|
||||
scheduled,
|
||||
}
|
||||
|
||||
/// How the user started an action.
|
||||
enum action-source {
|
||||
keyboard,
|
||||
menu,
|
||||
toolbar,
|
||||
context-menu,
|
||||
search,
|
||||
other,
|
||||
}
|
||||
use types.{error, extension};
|
||||
|
||||
record action-performed {
|
||||
/// Action id (`editor.duplicate-line`).
|
||||
action: string,
|
||||
title: string,
|
||||
source: action-source,
|
||||
/// How the user started it: `keyboard`, `menu`, `toolbar`,
|
||||
/// `context-menu`, `search` or `other` (more may be added).
|
||||
source: string,
|
||||
/// Its keyboard shortcut, when it has one (`Ctrl+D`).
|
||||
shortcut: option<string>,
|
||||
}
|
||||
@@ -43,14 +22,21 @@ interface events {
|
||||
action-performed(action-performed),
|
||||
vcs-changed(string),
|
||||
scheduled,
|
||||
/// A kind added after 1.0 (subscribed to by its name).
|
||||
other(extension),
|
||||
}
|
||||
|
||||
/// Delivers `kind` events from now on, for the rest of the session (also
|
||||
/// across idle reclaim: an event activates the plugin again). Declare
|
||||
/// `activation = ["on-event:<kind>"]` to get them before first use.
|
||||
/// Kinds: `file-opened`, `file-saved`, `editor-focused` (the focused editor
|
||||
/// changed), `vcs-changed` (a repository's state changed: commit,
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran) and
|
||||
/// `scheduled` (the `on-schedule` period elapsed); later IDEs add more,
|
||||
/// and an IDE that doesn't know one fails with `invalid`.
|
||||
/// Requires `events` (`events.input` for `action-performed`).
|
||||
subscribe: func(kind: event-kind) -> result<_, error>;
|
||||
unsubscribe: func(kind: event-kind);
|
||||
subscribe: func(kind: string) -> result<_, error>;
|
||||
unsubscribe: func(kind: string);
|
||||
}
|
||||
|
||||
/// Long-running work with a progress indicator. While a task is open, the
|
||||
|
||||
@@ -2,7 +2,7 @@ package openidea:[email protected];
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
use types.{error, range};
|
||||
use types.{error, range, location};
|
||||
|
||||
enum severity {
|
||||
error,
|
||||
@@ -11,12 +11,23 @@ interface diagnostics {
|
||||
hint,
|
||||
}
|
||||
|
||||
/// Another place that explains a diagnostic (the earlier declaration, say).
|
||||
record related-information {
|
||||
location: location,
|
||||
message: string,
|
||||
}
|
||||
|
||||
record diagnostic {
|
||||
range: range,
|
||||
severity: severity,
|
||||
message: string,
|
||||
/// Rule or check id (`LineLength`).
|
||||
code: option<string>,
|
||||
/// The tool that found it, when not the plugin itself (`checkstyle`).
|
||||
source: option<string>,
|
||||
/// `unnecessary` (shown faded) and `deprecated` (struck through); unknown ones are ignored.
|
||||
tags: list<string>,
|
||||
related: list<related-information>,
|
||||
}
|
||||
|
||||
/// Replaces the plugin's diagnostics for the file at `path` (absolute, in
|
||||
|
||||
@@ -5,7 +5,7 @@ package openidea:[email protected];
|
||||
/// on the editing path: a result later than ~50 ms is dropped, a call still
|
||||
/// running at 500 ms is interrupted.
|
||||
interface providers {
|
||||
use types.{position, range, text-edit, location};
|
||||
use types.{error, position, range, text-edit, location};
|
||||
|
||||
/// The document a request is about.
|
||||
record document {
|
||||
@@ -24,11 +24,17 @@ interface providers {
|
||||
/// constant, struct, event, operator or type-parameter. Unknown kinds
|
||||
/// show no icon.
|
||||
kind: option<string>,
|
||||
/// With `snippet`, tab stops and placeholders (`$1`, `${1:name}`, `$0`).
|
||||
insert-text: string,
|
||||
snippet: bool,
|
||||
/// Replaced on accept; `none`: the word at the caret.
|
||||
replace: option<range>,
|
||||
sort-text: option<string>,
|
||||
/// Matched against what was typed instead of `label`.
|
||||
filter-text: option<string>,
|
||||
documentation: option<string>,
|
||||
/// Applied with the item elsewhere in the document (an import).
|
||||
additional-edits: list<text-edit>,
|
||||
}
|
||||
|
||||
record inline-suggestion {
|
||||
@@ -48,6 +54,9 @@ interface providers {
|
||||
kind: option<string>,
|
||||
preferred: bool,
|
||||
edits: list<file-edit>,
|
||||
/// The plugin's own reference: with it and no `edits`, the edits are
|
||||
/// computed by `resolve-code-action` once the user picks the action.
|
||||
data: option<string>,
|
||||
}
|
||||
|
||||
record line-marker {
|
||||
@@ -64,6 +73,9 @@ interface providers {
|
||||
inline-completion: func(doc: document, at: position) -> option<inline-suggestion>;
|
||||
/// Actions for `selection` (quick fixes for the plugin's own diagnostics).
|
||||
code-actions: func(doc: document, selection: range) -> list<code-action>;
|
||||
/// The edits of an action `code-actions` returned with `data`, when the
|
||||
/// user picks it (the command budget applies, not the editor's 50 ms).
|
||||
resolve-code-action: func(doc: document, action: code-action) -> result<code-action, error>;
|
||||
definition: func(doc: document, at: position) -> list<location>;
|
||||
line-markers: func(doc: document) -> list<line-marker>;
|
||||
}
|
||||
@@ -52,6 +52,15 @@ interface types {
|
||||
range: range,
|
||||
}
|
||||
|
||||
/// A case added after 1.0, carried by the `other` case of a variant that
|
||||
/// grows (events, view bodies, view events, form fields): its kind and its
|
||||
/// data as JSON. Whoever doesn't know the kind ignores it or shows a
|
||||
/// fallback; the SDKs decode the kinds they know.
|
||||
record extension {
|
||||
kind: string,
|
||||
data: string,
|
||||
}
|
||||
|
||||
/// Passed to `lifecycle.activate`.
|
||||
record context {
|
||||
plugin-id: string,
|
||||
|
||||
@@ -8,6 +8,8 @@ package openidea:[email protected];
|
||||
/// runs in the WebView, except a `html` body, which is shown in a sandboxed
|
||||
/// frame that can only exchange messages with the plugin.
|
||||
interface view-types {
|
||||
use types.{extension};
|
||||
|
||||
record button {
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -43,6 +45,8 @@ interface view-types {
|
||||
checkbox(bool),
|
||||
/// The options and the chosen one.
|
||||
choice(tuple<list<string>, string>),
|
||||
/// A field type added after 1.0 (an IDE that doesn't know it leaves it out).
|
||||
other(extension),
|
||||
}
|
||||
|
||||
record field {
|
||||
@@ -72,6 +76,8 @@ interface view-types {
|
||||
/// network, no IDE API. Its script talks to the plugin with
|
||||
/// `openidea.postMessage(text)` / `openidea.onMessage(fn)`.
|
||||
html(string),
|
||||
/// A body added after 1.0; an IDE that doesn't know it says it needs updating.
|
||||
other(extension),
|
||||
}
|
||||
|
||||
record view {
|
||||
@@ -109,6 +115,8 @@ interface view-types {
|
||||
delete-rows(list<u32>),
|
||||
/// From the `html` body's script.
|
||||
message(string),
|
||||
/// An event added after 1.0, from a body or field added after 1.0.
|
||||
other(extension),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -188,6 +188,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
nav::index_status,
|
||||
nav::spring_route_sources,
|
||||
nav::find_files,
|
||||
nav::find_dirs,
|
||||
nav::find_symbols,
|
||||
nav::mark_recent,
|
||||
nav::recent_files,
|
||||
|
||||
@@ -22,6 +22,13 @@ pub fn find_files(window: Window, state: State<'_, AppState>, query: String, lim
|
||||
ide_host::ops::nav::find_files(&state.host, window.label(), query, limit)
|
||||
}
|
||||
|
||||
/// Folders holding indexed files, for `@` references.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn find_dirs(window: Window, state: State<'_, AppState>, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
|
||||
ide_host::ops::nav::find_dirs(&state.host, window.label(), query, limit)
|
||||
}
|
||||
|
||||
/// Spring Web mapping sources for the request-path index of Search Everywhere.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -327,6 +327,8 @@ export const commands = {
|
||||
/** Spring Web mapping sources for the request-path index of Search Everywhere. */
|
||||
springRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("spring_route_sources")),
|
||||
findFiles: (query: string, limit: number) => typedError<FileMatch[], IdeError>(__TAURI_INVOKE("find_files", { query, limit })),
|
||||
/** Folders holding indexed files, for `@` references. */
|
||||
findDirs: (query: string, limit: number) => typedError<FileMatch[], IdeError>(__TAURI_INVOKE("find_dirs", { query, limit })),
|
||||
findSymbols: (query: string, filter: SymbolFilter, limit: number) => typedError<SymbolMatch[], IdeError>(__TAURI_INVOKE("find_symbols", { query, filter, limit })),
|
||||
markRecent: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("mark_recent", { path })),
|
||||
/** Recently opened files, most recent first (⌘E). */
|
||||
@@ -4532,6 +4534,8 @@ export type LanguageInfo_Deserialize = {
|
||||
filenames?: string[],
|
||||
/** First-line regex of the definition (shebangs, `<?php`). */
|
||||
firstLine?: string | null,
|
||||
/** Content of a new scratch file; `$END$` marks where the caret goes. */
|
||||
scratchTemplate?: string | null,
|
||||
};
|
||||
|
||||
/** The UI-facing view of a language. */
|
||||
@@ -4551,6 +4555,8 @@ export type LanguageInfo_Serialize = {
|
||||
filenames?: string[],
|
||||
/** First-line regex of the definition (shebangs, `<?php`). */
|
||||
firstLine?: string | null,
|
||||
/** Content of a new scratch file; `$END$` marks where the caret goes. */
|
||||
scratchTemplate?: string | null,
|
||||
};
|
||||
|
||||
export type LanguageServerSettings = LanguageServerSettings_Serialize | LanguageServerSettings_Deserialize;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { outsideProjectNotice } from "./outsideProject";
|
||||
|
||||
const text = (message: string) => outsideProjectNotice(message)?.text ?? null;
|
||||
@@ -36,7 +37,22 @@ it("recognizes each server's report that a file is outside its projects", () =>
|
||||
expect(outsideProjectNotice("No packages found for open file x.go.")?.reload).toBeFalsy();
|
||||
});
|
||||
|
||||
afterEach(() => useProject.setState({ project: null }));
|
||||
|
||||
const openProject = (root: string, projects?: string[]) =>
|
||||
useProject.setState({
|
||||
project: {
|
||||
root,
|
||||
name: "p",
|
||||
trusted: true,
|
||||
isGit: false,
|
||||
settings: {},
|
||||
...(projects && { workspace: { version: 1, name: "p", projects } }),
|
||||
},
|
||||
});
|
||||
|
||||
it("shows a banner while the server reports the file, with the build reloads available", async () => {
|
||||
openProject("/p");
|
||||
const { renderHook, act } = await import("@testing-library/react");
|
||||
const { setFileDiagnostics } = await import("./diagnostics");
|
||||
const { registerActions } = await import("@/platform/actions");
|
||||
@@ -64,3 +80,39 @@ it("shows a banner while the server reports the file, with the build reloads ava
|
||||
setFileDiagnostics(path, "jdtls", []);
|
||||
}
|
||||
});
|
||||
|
||||
it("offers a build reload only for files of the open project", async () => {
|
||||
const { renderHook, act } = await import("@testing-library/react");
|
||||
const { setFileDiagnostics } = await import("./diagnostics");
|
||||
const { registerActions } = await import("@/platform/actions");
|
||||
const { outsideProjectBanner } = await import("./outsideProject");
|
||||
const off = registerActions([{ id: "maven.reload", title: "Reload All Maven Projects", run: () => {} }]);
|
||||
openProject("/ws", ["/p"]);
|
||||
// A scratch lives in the app data dir; a module the import missed lives in the project.
|
||||
const cases: [string, string[]][] = [
|
||||
["/data/scratches/scratch.java", []],
|
||||
["/p/tools/Gen.java", ["Reload Maven Projects"]],
|
||||
["/ws/Gen.java", ["Reload Maven Projects"]],
|
||||
];
|
||||
try {
|
||||
for (const [path, labels] of cases) {
|
||||
const { result } = renderHook(() => outsideProjectBanner.useBanner(path));
|
||||
const warning = {
|
||||
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
|
||||
severity: "warning" as const,
|
||||
message: `${path.split("/").pop()} is a non-project file, only syntax errors are reported`,
|
||||
source: "Java",
|
||||
code: "32",
|
||||
};
|
||||
act(() => setFileDiagnostics(path, "jdtls", [warning]));
|
||||
expect(result.current?.text, path).toMatch(/only JDK classes resolve/);
|
||||
expect(
|
||||
result.current?.actions?.map((a) => a.label),
|
||||
path,
|
||||
).toEqual(labels);
|
||||
act(() => setFileDiagnostics(path, "jdtls", []));
|
||||
}
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
@@ -6,10 +6,15 @@
|
||||
*/
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { executeAction, getAction, isActionEnabled } from "@/platform/actions";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { EditorBannerContribution } from "@/workbench/contributions";
|
||||
import { diagnosticsFor, subscribeDiagnostics } from "./diagnostics";
|
||||
|
||||
/** `reload`: a build reload may bring the file into a project (a module the import missed). */
|
||||
/**
|
||||
* `reload`: a build reload may bring the file into a project (a module the import missed); offered
|
||||
* only for files inside the open project.
|
||||
*/
|
||||
const NOTICES: readonly { test: RegExp; text: string; reload?: boolean }[] = [
|
||||
// jdtls: "Foo.java is not on the classpath of project app, only syntax errors are reported"
|
||||
{
|
||||
@@ -17,10 +22,11 @@ const NOTICES: readonly { test: RegExp; text: string; reload?: boolean }[] = [
|
||||
text: "This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.",
|
||||
reload: true,
|
||||
},
|
||||
// jdtls: "Foo.java is a non-project file, only syntax errors are reported"
|
||||
// jdtls: "Foo.java is a non-project file, only syntax errors are reported". jdtls still completes
|
||||
// and navigates JDK classes in such a file (a scratch, a file opened from outside the project).
|
||||
{
|
||||
test: /is a non-project file, only syntax errors are reported/,
|
||||
text: "This file does not belong to an imported Java project: only syntax errors are reported, and navigation and completion don't work.",
|
||||
text: "This file does not belong to an imported Java project: only syntax errors are reported, and only JDK classes resolve.",
|
||||
reload: true,
|
||||
},
|
||||
// gopls, before its generic "No packages found" below.
|
||||
@@ -73,13 +79,17 @@ export const outsideProjectBanner: EditorBannerContribution = {
|
||||
(l) => subscribeDiagnostics(path, l),
|
||||
() => noticeFor(path),
|
||||
);
|
||||
const inProject = useProject(({ project }) =>
|
||||
[project?.root, ...(project?.workspace?.projects ?? [])].some((root) => !!root && isSameOrInside(path, root)),
|
||||
);
|
||||
if (!notice) return null;
|
||||
const actions = notice.reload
|
||||
? RELOADS.filter(({ id }) => {
|
||||
const action = getAction(id);
|
||||
return action && isActionEnabled(action);
|
||||
}).map(({ id, label }) => ({ label, run: () => void executeAction(id) }))
|
||||
: [];
|
||||
const actions =
|
||||
notice.reload && inProject
|
||||
? RELOADS.filter(({ id }) => {
|
||||
const action = getAction(id);
|
||||
return action && isActionEnabled(action);
|
||||
}).map(({ id, label }) => ({ label, run: () => void executeAction(id) }))
|
||||
: [];
|
||||
return { text: notice.text, level: "warning", actions };
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* The message box of the New Task page and of sessions: `@` file references (project file
|
||||
* search), `/` agent commands, ↑ / ↓ history, pasted or dropped images, Shift+Tab to cycle
|
||||
* The message box of the New Task page and of sessions: `@` file and folder references
|
||||
* (project index search), `/` agent commands, ↑ / ↓ history, pasted or dropped images, Shift+Tab to cycle
|
||||
* the agent's mode. Its draft lives in the store under `id`.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
applyCompletion,
|
||||
atEdgeLine,
|
||||
isPathQuery,
|
||||
mergeMatches,
|
||||
resolveTyped,
|
||||
completionAt,
|
||||
imageFromDataUrl,
|
||||
@@ -129,14 +130,15 @@ export function Composer(props: ComposerProps) {
|
||||
.catch(() => alive && setFiles([]));
|
||||
return;
|
||||
}
|
||||
call(commands.findFiles(query, MAX_ITEMS))
|
||||
.then((found) => {
|
||||
Promise.all([call(commands.findFiles(query, MAX_ITEMS)), call(commands.findDirs(query, MAX_ITEMS))])
|
||||
.then(([found, dirs]) => {
|
||||
if (!alive) return;
|
||||
setFiles(
|
||||
found.map((f) => ({
|
||||
mergeMatches(found, dirs, MAX_ITEMS).map((f) => ({
|
||||
kind: "file",
|
||||
rel: f.relPath,
|
||||
path: root === projectRoot ? f.path : `${root}/${f.relPath}`,
|
||||
rel: f.rel,
|
||||
dir: f.dir,
|
||||
path: root === projectRoot ? f.path : `${root}/${f.rel}`,
|
||||
})),
|
||||
);
|
||||
})
|
||||
@@ -171,19 +173,20 @@ export function Composer(props: ComposerProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const accept = (item: Item | undefined) => {
|
||||
/** Enter or a click references the item; Tab on a folder keeps completing inside it. */
|
||||
const accept = (item: Item | undefined, descend = false) => {
|
||||
if (!item || !completion) return;
|
||||
if (item.kind === "file" && item.dir) {
|
||||
// Descend: keep completing inside the folder.
|
||||
const insert = `${mentionOf(item.rel)}/`;
|
||||
setText(text.slice(0, completion.from) + insert + text.slice(completion.to), completion.from + insert.length);
|
||||
return;
|
||||
}
|
||||
if (item.kind === "file") {
|
||||
const mention = mentionOf(item.rel);
|
||||
const next = applyCompletion(text, completion, mention);
|
||||
const rel = item.dir ? `${item.rel}/` : item.rel;
|
||||
// A folder stays referenced while its `@folder/` is left as typed (`toPrompt`).
|
||||
const current = composerDraft(id);
|
||||
updateComposer(id, { files: [...current.files, { path: item.path, rel: item.rel } satisfies FileRef] });
|
||||
updateComposer(id, { files: [...current.files, { path: item.path, rel } satisfies FileRef] });
|
||||
if (item.dir && descend) {
|
||||
const insert = mentionOf(rel);
|
||||
setText(text.slice(0, completion.from) + insert + text.slice(completion.to), completion.from + insert.length);
|
||||
return;
|
||||
}
|
||||
const next = applyCompletion(text, completion, mentionOf(rel));
|
||||
setText(next.text, next.caret);
|
||||
} else {
|
||||
const next = applyCompletion(text, completion, `/${item.command.name}`);
|
||||
@@ -266,7 +269,7 @@ export function Composer(props: ComposerProps) {
|
||||
}
|
||||
if (e.key === "Enter" || e.key === "Tab") {
|
||||
e.preventDefault();
|
||||
accept(items[active]);
|
||||
accept(items[active], e.key === "Tab");
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
@@ -345,7 +348,10 @@ export function Composer(props: ComposerProps) {
|
||||
{item.kind === "file" ? (
|
||||
<>
|
||||
<Icon name={item.dir ? "folder" : fileIconName(basename(item.rel), item.rel)} size={16} />
|
||||
<span className={styles.itemName}>{basename(item.rel)}</span>
|
||||
<span className={styles.itemName}>
|
||||
{basename(item.rel)}
|
||||
{item.dir && "/"}
|
||||
</span>
|
||||
<span className={styles.itemDetail}>{item.rel}</span>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -99,7 +99,9 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
|
||||
id={HOME}
|
||||
autoFocus
|
||||
placeholder={
|
||||
docked ? "Describe a task…" : "Describe a task for the agent. @ references a file, / runs a command"
|
||||
docked
|
||||
? "Describe a task…"
|
||||
: "Describe a task for the agent. @ references a file or folder, / runs a command"
|
||||
}
|
||||
root={root}
|
||||
projectRoot={root}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
nextValue,
|
||||
recall,
|
||||
toPrompt,
|
||||
mergeMatches,
|
||||
retryParts,
|
||||
usageLabel,
|
||||
limitLabel,
|
||||
@@ -67,6 +68,27 @@ const option = (category: string, values: string[], current: string | null): Age
|
||||
via: "option",
|
||||
});
|
||||
|
||||
describe("mergeMatches", () => {
|
||||
it("ranks folders among files by score, files first on a tie", () => {
|
||||
const merged = mergeMatches(
|
||||
[
|
||||
{ path: "/p/src/agents.ts", relPath: "src/agents.ts", score: 50 },
|
||||
{ path: "/p/x.ts", relPath: "x.ts", score: 10 },
|
||||
],
|
||||
[
|
||||
{ path: "/p/src/agents", relPath: "src/agents/", score: 50 },
|
||||
{ path: "/p/docs", relPath: "docs/", score: 70 },
|
||||
],
|
||||
3,
|
||||
);
|
||||
expect(merged).toEqual([
|
||||
{ path: "/p/docs", rel: "docs", dir: true, score: 70 },
|
||||
{ path: "/p/src/agents.ts", rel: "src/agents.ts", dir: false, score: 50 },
|
||||
{ path: "/p/src/agents", rel: "src/agents", dir: true, score: 50 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent composer", () => {
|
||||
it("completes @files anywhere and /commands as the first word", () => {
|
||||
expect(completionAt("fix @src/le", 11)).toEqual({ kind: "file", query: "src/le", from: 4, to: 11 });
|
||||
@@ -111,6 +133,11 @@ describe("agent composer", () => {
|
||||
});
|
||||
expect(prompt).toEqual({ text: "look at @src/a.rs:3-5 and @b.rs", files: ["/w/src/a.rs", "/w/b.rs"], images: [] });
|
||||
expect(mentionOf("a.rs", { from: 3, to: 3 })).toBe("@a.rs:3");
|
||||
// A folder counts while `@src/` is left as typed, not once a file inside it was picked.
|
||||
const folder = { path: "/w/src", rel: "src/" };
|
||||
expect(toPrompt({ text: "explain @src/ please", files: [folder], images: [] }).files).toEqual(["/w/src"]);
|
||||
expect(toPrompt({ text: "explain @src/", files: [folder], images: [] }).files).toEqual(["/w/src"]);
|
||||
expect(toPrompt({ text: "explain @src/a.rs", files: [folder], images: [] }).files).toEqual([]);
|
||||
expect(canSend({ text: " ", files: [], images: [] })).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
const findFiles = vi.fn();
|
||||
const findDirs = vi.fn();
|
||||
const pathCompletions = vi.fn();
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: vi.fn(() => false),
|
||||
commands: {
|
||||
...real.commands,
|
||||
findFiles: (query: string, limit: number) => findFiles(query, limit),
|
||||
findDirs: (query: string, limit: number) => findDirs(query, limit),
|
||||
pathCompletions: (base: string, typed: string) => pathCompletions(base, typed),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { Composer } from "./Composer";
|
||||
import { composerDraft, updateComposer } from "./store";
|
||||
import { emptyDraft, toPrompt } from "./composerModel";
|
||||
|
||||
const ID = "folders-test";
|
||||
const ok = <T,>(data: T) => Promise.resolve({ status: "ok", data });
|
||||
|
||||
function renderComposer() {
|
||||
render(
|
||||
<Composer
|
||||
id={ID}
|
||||
placeholder="Ask"
|
||||
root="/p"
|
||||
projectRoot="/p"
|
||||
commands={[]}
|
||||
history={[]}
|
||||
config={[]}
|
||||
onSubmit={() => {}}
|
||||
/>,
|
||||
);
|
||||
return screen.getByPlaceholderText("Ask") as HTMLTextAreaElement;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
updateComposer(ID, emptyDraft());
|
||||
const match = (path: string, relPath: string, score: number) => ({ path, relPath, score, indices: [] });
|
||||
findFiles.mockReset().mockReturnValue(ok([match("/p/src/agents.ts", "src/agents.ts", 40)]));
|
||||
findDirs.mockReset().mockReturnValue(ok([match("/p/src/agents", "src/agents/", 90)]));
|
||||
pathCompletions.mockReset().mockReturnValue(ok([{ name: "lib", dir: true }]));
|
||||
});
|
||||
|
||||
describe("Composer @ folders", () => {
|
||||
it("lists index folders among files and references one on Enter", async () => {
|
||||
const box = renderComposer();
|
||||
await userEvent.type(box, "see @agen");
|
||||
const options = await screen.findAllByRole("option");
|
||||
expect(options.map((o) => o.textContent)).toEqual(["agents/src/agents", "agents.tssrc/agents.ts"]);
|
||||
await userEvent.keyboard("{Enter}");
|
||||
expect(box.value).toBe("see @src/agents/ ");
|
||||
expect(toPrompt(composerDraft(ID)).files).toEqual(["/p/src/agents"]);
|
||||
});
|
||||
|
||||
it("keeps completing inside a folder on Tab, which drops the folder once a file is picked", async () => {
|
||||
const box = renderComposer();
|
||||
await userEvent.type(box, "@agen");
|
||||
await screen.findAllByRole("option");
|
||||
await userEvent.keyboard("{Tab}");
|
||||
expect(box.value).toBe("@src/agents/");
|
||||
expect(toPrompt(composerDraft(ID)).files).toEqual(["/p/src/agents"]);
|
||||
await userEvent.type(box, "x.ts ");
|
||||
expect(toPrompt(composerDraft(ID)).files).toEqual([]);
|
||||
});
|
||||
|
||||
it("references a folder of a typed path", async () => {
|
||||
const box = renderComposer();
|
||||
await userEvent.type(box, "@./");
|
||||
await screen.findByRole("option");
|
||||
await userEvent.keyboard("{Enter}");
|
||||
expect(box.value).toBe("@./lib/ ");
|
||||
expect(toPrompt(composerDraft(ID)).files).toEqual(["/p/lib"]);
|
||||
});
|
||||
});
|
||||
@@ -94,6 +94,29 @@ export function resolveTyped(root: string, rel: string): string {
|
||||
return isDrive(out[0]) ? out.join("/") : `/${out.join("/")}`;
|
||||
}
|
||||
|
||||
interface IndexMatch {
|
||||
path: string;
|
||||
relPath: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index file and folder matches as one list, best first (files first on a tie); folders'
|
||||
* `rel` loses the trailing `/` the index gives them.
|
||||
*/
|
||||
export function mergeMatches(
|
||||
files: readonly IndexMatch[],
|
||||
dirs: readonly IndexMatch[],
|
||||
limit: number,
|
||||
): { path: string; rel: string; dir: boolean; score: number }[] {
|
||||
return [
|
||||
...files.map((f) => ({ path: f.path, rel: f.relPath, dir: false, score: f.score })),
|
||||
...dirs.map((d) => ({ path: d.path, rel: d.relPath.replace(/\/$/, ""), dir: true, score: d.score })),
|
||||
]
|
||||
.sort((a, b) => b.score - a.score || Number(a.dir) - Number(b.dir))
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
/** `@rel` with a line range suffix when given ("@src/a.rs:10-20"). */
|
||||
export function mentionOf(rel: string, lines?: { from: number; to: number }): string {
|
||||
if (!lines) return `@${rel}`;
|
||||
|
||||
@@ -369,17 +369,6 @@
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.marketBar {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.marketBar > :first-child {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.categorySelect {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
SearchField,
|
||||
Select,
|
||||
Spinner,
|
||||
@@ -48,6 +47,7 @@ import {
|
||||
} from "./store";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { importIntellijTheme, showInstalledIntellijThemes } from "./intellijImport";
|
||||
import { promptInput } from "@/workbench/inputDialogs";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -537,6 +537,21 @@ interface GearActions {
|
||||
install: (packageFile: boolean) => void;
|
||||
importIntellijFile: () => void;
|
||||
importInstalledIntellij: () => void;
|
||||
editRepository: () => void;
|
||||
}
|
||||
|
||||
/** Asks for the marketplace index URL; an empty one restores the default. */
|
||||
async function editMarketUrl() {
|
||||
const url = await promptInput({
|
||||
title: "Plugin Repository",
|
||||
label: "Marketplace index URL:",
|
||||
initial: usePlugins.getState().marketUrl ?? "",
|
||||
placeholder: "https://…/index.json or a folder path",
|
||||
okLabel: "Save",
|
||||
validate: () => null,
|
||||
hint: <T>Leave empty to use the default repository.</T>,
|
||||
});
|
||||
if (url !== null) await setMarketUrl(url);
|
||||
}
|
||||
|
||||
function gearMenu(plugins: readonly PluginInfo[], updates: number, actions: GearActions): MenuItem[] {
|
||||
@@ -550,6 +565,7 @@ function gearMenu(plugins: readonly PluginInfo[], updates: number, actions: Gear
|
||||
{ kind: "separator" },
|
||||
{ label: "Install Plugin from Disk…", icon: "package", run: () => actions.install(false) },
|
||||
{ label: "Install Plugin from Package File…", run: () => actions.install(true) },
|
||||
{ label: "Plugin Repository…", run: actions.editRepository },
|
||||
...(actions.canImport
|
||||
? [
|
||||
{ kind: "separator" as const },
|
||||
@@ -654,30 +670,6 @@ function CategoryFilter({
|
||||
);
|
||||
}
|
||||
|
||||
/** The marketplace index URL, editable in place. */
|
||||
function MarketUrlBar() {
|
||||
const current = usePlugins((s) => s.marketUrl);
|
||||
const [value, setValue] = useState(current ?? "");
|
||||
useEffect(() => setValue(current ?? ""), [current]);
|
||||
return (
|
||||
<form
|
||||
className={styles.marketBar}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void setMarketUrl(value);
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
value={value}
|
||||
placeholder="Marketplace index URL (https://…/index.json or a folder path)"
|
||||
aria-label="Marketplace index URL"
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
/>
|
||||
<IconButton icon="refresh" title="Refresh Marketplace" type="submit" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function MarketRow({ entry, selected, onSelect }: { entry: MarketPlugin; selected: boolean; onSelect: () => void }) {
|
||||
const update = isUpdate(entry);
|
||||
return (
|
||||
@@ -832,6 +824,7 @@ export function PluginsPage() {
|
||||
install: (packageFile) => void installFromDisk(undefined, packageFile).then(showInstalled),
|
||||
importIntellijFile: () => void importIntellijTheme().then(showInstalled),
|
||||
importInstalledIntellij: () => showInstalledIntellijThemes(showInstalled),
|
||||
editRepository: () => void editMarketUrl(),
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -876,7 +869,7 @@ export function PluginsPage() {
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tab === "installed" ? "Search installed plugins" : "Search local plugins"}
|
||||
placeholder={tab === "installed" ? "Search installed plugins" : "Search plugins"}
|
||||
aria-label="Filter plugins"
|
||||
/>
|
||||
{tab === "installed" ? (
|
||||
@@ -916,20 +909,11 @@ export function PluginsPage() {
|
||||
</ul>
|
||||
) : (
|
||||
<ul className={styles.list} aria-label={tx("Available plugins")}>
|
||||
<li className={styles.marketItem}>
|
||||
<MarketUrlBar />
|
||||
</li>
|
||||
{(market?.length ?? 0) > 0 && (
|
||||
<li className={styles.marketItem}>
|
||||
<CategoryFilter market={market ?? []} value={category} onChange={setCategory} />
|
||||
</li>
|
||||
)}
|
||||
{!marketUrl && (
|
||||
<li className={styles.notice} role="note">
|
||||
<Icon name="info" size={14} />
|
||||
<span>{tx`${NO_REPOSITORY}. Showing plugin packages available on this machine.`}</span>
|
||||
</li>
|
||||
)}
|
||||
{marketError && <li className={clsx(styles.listEmpty, styles.errorText)}>{marketError}</li>}
|
||||
{marketShown.length > 0 && <ListHeader title="Marketplace" count={marketShown.length} />}
|
||||
{marketShown.map((m) => (
|
||||
@@ -983,6 +967,8 @@ export function PluginsPage() {
|
||||
/>
|
||||
) : selectedEntry ? (
|
||||
<CatalogDetails key={selectedEntry.id} entry={selectedEntry} />
|
||||
) : marketUrl ? (
|
||||
<EmptyState className={styles.detailsEmpty} title="No plugin selected" />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={NO_REPOSITORY}>
|
||||
<T>Install a plugin folder with</T> <code>plugin.toml</code>{" "}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { executeAction, executeActionFrom, getAction, registerAction } from "@/p
|
||||
import { useProject } from "@/platform/project";
|
||||
import { pluginThemeRef, useContributedIconThemes } from "@/platform/themes";
|
||||
import { ContextMenuHost, hideContextMenu } from "@/ui";
|
||||
import { InputDialogsHost } from "@/workbench/inputDialogs";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import { applyThemeAttributes, previewTheme, useThemeOverride } from "@/workbench/theme";
|
||||
import { createMemoryPluginsBackend, sampleCatalog, setPluginsBackend, type PluginsBackend } from "../backend";
|
||||
@@ -561,7 +562,6 @@ describe("PluginsPage", () => {
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
expect(within(list).getByText(new RegExp(NO_REPOSITORY))).toBeInTheDocument();
|
||||
await waitFor(() => expect(within(list).getByText("Toy Language")).toBeInTheDocument());
|
||||
await user.click(within(list).getByText("Toy Language"));
|
||||
expect(screen.getByRole("heading", { level: 2 })).toHaveTextContent("Toy Language");
|
||||
@@ -570,6 +570,21 @@ describe("PluginsPage", () => {
|
||||
expect(within(list).getAllByText("Installed").length).toBeGreaterThan(0);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Installed Toy Language 0.1.0" });
|
||||
});
|
||||
|
||||
it("shows why the marketplace couldn't be read instead of claiming there is none", async () => {
|
||||
// Commands without a result type reject with the backend's error object, not an Error.
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([], sampleCatalog()),
|
||||
marketUrl: () => Promise.reject({ kind: "unavailable", message: "Index unreachable", data: null }),
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
expect(await within(list).findByText("Index unreachable")).toBeInTheDocument();
|
||||
expect(within(list).queryByText("[object Object]")).not.toBeInTheDocument();
|
||||
expect(within(list).queryByText(new RegExp(NO_REPOSITORY))).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("secrets", () => {
|
||||
@@ -648,6 +663,53 @@ describe("marketplace", () => {
|
||||
expect(asked[0]).toMatchObject({ pluginId: "hello", kind: "install" });
|
||||
});
|
||||
|
||||
it("doesn't claim there is no repository while one is configured", async () => {
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([], []),
|
||||
marketUrl: async () => "https://plugins.example/index.json",
|
||||
market: async () => [],
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
expect(await screen.findByText("No plugin selected")).toBeInTheDocument();
|
||||
expect(screen.queryByText(new RegExp(NO_REPOSITORY))).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox", { name: "Filter plugins" })).toHaveAttribute("placeholder", "Search plugins");
|
||||
});
|
||||
|
||||
it("edits the repository from the gear menu; an empty URL restores the default", async () => {
|
||||
const base = createMemoryPluginsBackend([], []);
|
||||
const set: (string | null)[] = [];
|
||||
setPluginsBackend({
|
||||
...base,
|
||||
marketUrl: async () => "https://plugins.example/index.json",
|
||||
market: async () => [],
|
||||
setMarketUrl: async (url) => void set.push(url),
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage />
|
||||
<ContextMenuHost />
|
||||
<InputDialogsHost />
|
||||
</>,
|
||||
);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
expect(screen.queryByRole("textbox", { name: /Marketplace index URL/ })).not.toBeInTheDocument();
|
||||
const edit = async (value: string) => {
|
||||
await user.click(screen.getByRole("button", { name: "Manage Plugins" }));
|
||||
await user.click(screen.getByRole("menuitem", { name: "Plugin Repository…" }));
|
||||
const field = await screen.findByRole("textbox", { name: /Marketplace index URL/ });
|
||||
await waitFor(() => expect(field).toHaveValue("https://plugins.example/index.json"));
|
||||
await user.clear(field);
|
||||
if (value) await user.type(field, value);
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
};
|
||||
await edit("https://mirror.example/index.json");
|
||||
await edit("");
|
||||
await waitFor(() => expect(set).toEqual(["https://mirror.example/index.json", null]));
|
||||
});
|
||||
|
||||
it("filters the marketplace by category", async () => {
|
||||
const entry = (id: string, name: string, categories: string[]) => ({
|
||||
id,
|
||||
|
||||
@@ -54,7 +54,13 @@ export const usePlugins = create<PluginsState>(() => ({
|
||||
marketError: null,
|
||||
}));
|
||||
|
||||
export const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||
/** A rejection's message: an `Error`, or an `IdeError` object from a command without a result type. */
|
||||
export const errorText = (e: unknown): string =>
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: typeof e === "object" && e !== null && "message" in e && typeof e.message === "string"
|
||||
? e.message
|
||||
: String(e);
|
||||
|
||||
/** Statuses whose contributions are in effect. */
|
||||
export const isLive = (status: PluginStatus) => status === "active" || status === "inactive" || status === "static";
|
||||
|
||||
@@ -4,14 +4,26 @@ import userEvent from "@testing-library/user-event";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useProjectViewRoots } from "@/workbench/contributions";
|
||||
import { chooserRows, pushRecent, scratchFileName, scratchLanguages, type ScratchLanguage } from "../model";
|
||||
import {
|
||||
chooserRows,
|
||||
pushRecent,
|
||||
scratchContent,
|
||||
scratchFileName,
|
||||
scratchLanguages,
|
||||
type ScratchLanguage,
|
||||
} from "../model";
|
||||
import { createScratch, setScratchBackend, tauriScratchBackend, type ScratchBackend } from "../scratches";
|
||||
import { useScratch } from "../store";
|
||||
import { ScratchChooserHost } from "../ScratchChooser";
|
||||
import { activate } from "..";
|
||||
|
||||
const LANGS: ScratchLanguage[] = scratchLanguages([
|
||||
{ id: "java", name: "Java", extensions: ["java"] },
|
||||
{
|
||||
id: "java",
|
||||
name: "Java",
|
||||
extensions: ["java"],
|
||||
scratchTemplate: "class Scratch {\n public static void main(String[] args) {\n $END$\n }\n}\n",
|
||||
},
|
||||
{ id: "python", name: "Python", extensions: ["py", "pyi"] },
|
||||
{ id: "javascript", name: "JavaScript", extensions: ["js", "mjs"] },
|
||||
{ id: "plaintext", name: "Plain Text", extensions: ["txt"] },
|
||||
@@ -27,6 +39,22 @@ describe("scratch naming", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("scratch content", () => {
|
||||
it("starts from the language's template with the caret at $END$", () => {
|
||||
const cases: [string | undefined, string, { line: number; col: number } | null][] = [
|
||||
[undefined, "", null],
|
||||
["", "", null],
|
||||
["fn main() {\n $END$\n}\n", "fn main() {\n \n}\n", { line: 1, col: 4 }],
|
||||
["package main\n\nfunc main() {\n\t$END$\n}\n", "package main\n\nfunc main() {\n\t\n}\n", { line: 3, col: 1 }],
|
||||
["$END$x", "x", { line: 0, col: 0 }],
|
||||
["// é\n$END$ $END$", "// é\n ", { line: 1, col: 0 }],
|
||||
["no caret\n", "no caret\n", null],
|
||||
];
|
||||
for (const [template, text, caret] of cases)
|
||||
expect(scratchContent(template), String(template)).toEqual({ text, caret });
|
||||
});
|
||||
});
|
||||
|
||||
describe("language chooser rows", () => {
|
||||
it("keeps languages with an extension, sorted by name, first extension wins", () => {
|
||||
expect(LANGS.map((l) => `${l.name}:${l.ext}`)).toEqual([
|
||||
@@ -62,20 +90,30 @@ describe("language chooser rows", () => {
|
||||
|
||||
describe("creating scratch files", () => {
|
||||
let files: Set<string>;
|
||||
let contents: Map<string, string>;
|
||||
let opened: string[];
|
||||
let carets: ({ line: number; col: number } | null)[];
|
||||
let backend: ScratchBackend;
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useScratch.setState({ languages: null, recent: [] });
|
||||
files = new Set(["/data/scratches/scratch.java"]);
|
||||
contents = new Map();
|
||||
opened = [];
|
||||
carets = [];
|
||||
backend = {
|
||||
dataDir: async () => "/data/",
|
||||
listNames: async (dir) => [...files].filter((f) => f.startsWith(dir + "/")).map((f) => f.slice(dir.length + 1)),
|
||||
createDir: async () => {},
|
||||
createFile: async (p) => void files.add(p),
|
||||
createFile: async (p, text) => {
|
||||
files.add(p);
|
||||
contents.set(p, text);
|
||||
},
|
||||
languages: async () => LANGS,
|
||||
open: async (p) => void opened.push(p),
|
||||
open: async (p, caret) => {
|
||||
opened.push(p);
|
||||
carets.push(caret);
|
||||
},
|
||||
};
|
||||
setScratchBackend(backend);
|
||||
});
|
||||
@@ -91,6 +129,16 @@ describe("creating scratch files", () => {
|
||||
expect(opened).toEqual(["/data/scratches/scratch_1.java"]);
|
||||
});
|
||||
|
||||
it("fills a new scratch from its language's template, caret in the body; others start empty", async () => {
|
||||
await createScratch(LANGS.find((l) => l.id === "java")!);
|
||||
await createScratch(LANGS.find((l) => l.id === "python")!);
|
||||
expect(contents.get("/data/scratches/scratch_1.java")).toBe(
|
||||
"class Scratch {\n public static void main(String[] args) {\n \n }\n}\n",
|
||||
);
|
||||
expect(contents.get("/data/scratches/scratch.py")).toBe("");
|
||||
expect(carets).toEqual([{ line: 2, col: 8 }, null]);
|
||||
});
|
||||
|
||||
it("registers the action and the Scratches root; the chooser creates the picked language", async () => {
|
||||
const dispose = activate();
|
||||
try {
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface ScratchLanguage {
|
||||
name: string;
|
||||
/** Extension (without the dot) new scratch files of this language get. */
|
||||
ext: string;
|
||||
/** Initial content; `$END$` marks where the caret goes. */
|
||||
template?: string;
|
||||
}
|
||||
|
||||
/** IDEA's names: `scratch.<ext>`, then `scratch_1.<ext>`, `scratch_2.<ext>`… */
|
||||
@@ -21,16 +23,34 @@ export function scratchFileName(existing: Iterable<string>, ext: string): string
|
||||
|
||||
/** Languages a scratch file can be created for (those with an extension), by name. */
|
||||
export function scratchLanguages(
|
||||
langs: ReadonlyArray<{ id: string; name: string; extensions: readonly string[] }>,
|
||||
langs: ReadonlyArray<{ id: string; name: string; extensions: readonly string[]; scratchTemplate?: string | null }>,
|
||||
): ScratchLanguage[] {
|
||||
const out: ScratchLanguage[] = [];
|
||||
for (const l of langs) {
|
||||
const ext = l.extensions.find((e) => e.trim())?.replace(/^\./, "");
|
||||
if (ext) out.push({ id: l.id, name: l.name, ext });
|
||||
if (ext) out.push({ id: l.id, name: l.name, ext, ...(l.scratchTemplate && { template: l.scratchTemplate }) });
|
||||
}
|
||||
return out.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
|
||||
}
|
||||
|
||||
const CARET = "$END$";
|
||||
|
||||
/** A new scratch file's text and caret (0-based line, UTF-16 column) from its language's template. */
|
||||
export function scratchContent(template: string | undefined): {
|
||||
text: string;
|
||||
caret: { line: number; col: number } | null;
|
||||
} {
|
||||
if (!template) return { text: "", caret: null };
|
||||
const at = template.indexOf(CARET);
|
||||
if (at < 0) return { text: template, caret: null };
|
||||
const before = template.slice(0, at);
|
||||
const lines = before.split("\n");
|
||||
return {
|
||||
text: before + template.slice(at + CARET.length).replaceAll(CARET, ""),
|
||||
caret: { line: lines.length - 1, col: lines[lines.length - 1]!.length },
|
||||
};
|
||||
}
|
||||
|
||||
export interface LanguageRow {
|
||||
lang: ScratchLanguage;
|
||||
matches: number[] | null;
|
||||
|
||||
@@ -6,16 +6,16 @@
|
||||
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
|
||||
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
|
||||
|
||||
export interface ScratchBackend {
|
||||
/** Absolute app data dir. */
|
||||
dataDir(): Promise<string>;
|
||||
listNames(dir: string): Promise<string[]>;
|
||||
createDir(dir: string): Promise<void>;
|
||||
createFile(path: string): Promise<void>;
|
||||
createFile(path: string, text: string): Promise<void>;
|
||||
languages(): Promise<ScratchLanguage[]>;
|
||||
open(path: string): Promise<void>;
|
||||
open(path: string, caret: { line: number; col: number } | null): Promise<void>;
|
||||
}
|
||||
|
||||
export const tauriScratchBackend: ScratchBackend = {
|
||||
@@ -26,9 +26,12 @@ export const tauriScratchBackend: ScratchBackend = {
|
||||
},
|
||||
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
|
||||
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
|
||||
createFile: async (path) => void (await call(commands.fsCreateFile(path))),
|
||||
createFile: async (path, text) =>
|
||||
void (await call(
|
||||
text ? commands.fsCreateFileBytes(path, [...new TextEncoder().encode(text)]) : commands.fsCreateFile(path),
|
||||
)),
|
||||
languages: async () => scratchLanguages(await commands.languages()),
|
||||
open: (path) => editorService().openFile(path, { focus: true }),
|
||||
open: (path, caret) => editorService().openFile(path, { focus: true, ...(caret && { selection: caret }) }),
|
||||
};
|
||||
|
||||
let backend: ScratchBackend = tauriScratchBackend;
|
||||
@@ -64,16 +67,17 @@ export function scratchesDir(): Promise<string> {
|
||||
|
||||
export const scratchesAvailable = () => isTauri() || backend !== tauriScratchBackend;
|
||||
|
||||
/** Creates `scratch[_n].<ext>` for `lang` and opens it; returns its path. */
|
||||
/** Creates `scratch[_n].<ext>` for `lang` from its template and opens it; returns its path. */
|
||||
export async function createScratch(lang: ScratchLanguage): Promise<string | null> {
|
||||
try {
|
||||
const dir = await scratchesDir();
|
||||
const name = scratchFileName(await backend.listNames(dir), lang.ext);
|
||||
const path = `${dir}/${name}`;
|
||||
await backend.createFile(path);
|
||||
const { text, caret } = scratchContent(lang.template);
|
||||
await backend.createFile(path, text);
|
||||
// The file watcher covers the project only: tell the project view.
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [path], modified: [], removed: [] });
|
||||
await backend.open(path);
|
||||
await backend.open(path, caret);
|
||||
return path;
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
|
||||
@@ -16,6 +16,7 @@ import { auxiliaryWindow } from "./platform/auxWindow";
|
||||
import { installRepeatedDoubleClick } from "./platform/doubleClick";
|
||||
import { installErrorLogging } from "./platform/errorLog";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { installPointerFocus } from "./platform/pointerFocus";
|
||||
import { isTauri } from "./platform/ipc";
|
||||
import { hideSplash } from "./platform/splash";
|
||||
import { prefetchLazyComponents } from "./ui";
|
||||
@@ -28,6 +29,7 @@ if (import.meta.env.DEV && isTauri()) {
|
||||
}
|
||||
|
||||
installRepeatedDoubleClick();
|
||||
installPointerFocus();
|
||||
installErrorLogging();
|
||||
|
||||
// Auxiliary windows (Settings `settings-<parent>`, comparisons `comparison-<parent>-<n>`, Sync with
|
||||
|
||||
@@ -1859,7 +1859,6 @@
|
||||
"Search frames": "Rechercher des cadres",
|
||||
"Search in comments and strings": "Rechercher dans les commentaires et les chaînes",
|
||||
"Search installed plugins": "Rechercher parmi les plugins installés",
|
||||
"Search local plugins": "Rechercher parmi les plugins locaux",
|
||||
"Search packages": "Rechercher des paquets",
|
||||
"Search projects": "Rechercher des projets",
|
||||
"Search pull requests": "Rechercher des pull requests",
|
||||
@@ -3385,7 +3384,7 @@
|
||||
"Not installed": "Non installé",
|
||||
"{command} was not found on PATH": "{command} est introuvable dans le PATH",
|
||||
"Agent tasks": "Tâches d'agent",
|
||||
"Describe a task for the agent. @ references a file, / runs a command": "Décrivez une tâche pour l'agent. @ référence un fichier, / lance une commande",
|
||||
"Describe a task for the agent. @ references a file or folder, / runs a command": "Décrivez une tâche pour l'agent. @ référence un fichier ou un dossier, / lance une commande",
|
||||
"away from your changes": "à l'écart de vos modifications",
|
||||
"edits your files directly": "modifie directement vos fichiers",
|
||||
"from": "depuis",
|
||||
@@ -4406,7 +4405,6 @@
|
||||
"Memory & Diagnostics": "Mémoire et diagnostics",
|
||||
"Over budget ({budget})": "Budget dépassé ({budget})",
|
||||
"dev": "dev",
|
||||
"{label}. Showing plugin packages available on this machine.": "{label}. Affichage des packages de plugins disponibles sur cette machine.",
|
||||
"Zoomed into {name}": "Zoom sur {name}",
|
||||
"Rename directory '{current}' and its usages to:": "Renommer le répertoire '{current}' et ses utilisations en :",
|
||||
"Rename file '{current}' and its usages to:": "Renommer le fichier '{current}' et ses utilisations en :",
|
||||
@@ -5494,7 +5492,7 @@
|
||||
"oxfmt formatting failed": "Échec du formatage avec oxfmt",
|
||||
"oxfmt formatting timed out": "Le formatage avec oxfmt a expiré",
|
||||
"This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.": "Ce fichier est en dehors des dossiers sources de son module Java : seules les erreurs de syntaxe sont signalées, et la navigation et la complétion ne fonctionnent pas.",
|
||||
"This file does not belong to an imported Java project: only syntax errors are reported, and navigation and completion don't work.": "Ce fichier n'appartient à aucun projet Java importé : seules les erreurs de syntaxe sont signalées, et la navigation et la complétion ne fonctionnent pas.",
|
||||
"This file does not belong to an imported Java project: only syntax errors are reported, and only JDK classes resolve.": "Ce fichier n'appartient à aucun projet Java importé : seules les erreurs de syntaxe sont signalées, et seules les classes du JDK sont résolues.",
|
||||
"This Go file belongs to no package of the workspace: code insight is limited.": "Ce fichier Go n'appartient à aucun paquet de l'espace de travail : l'analyse du code est limitée.",
|
||||
"This Rust file is not included in any crate: rust-analyzer can't offer code insight for it.": "Ce fichier Rust n'est inclus dans aucune crate : rust-analyzer ne peut pas proposer d'analyse du code pour celui-ci.",
|
||||
"Reload Maven Projects": "Recharger les projets Maven",
|
||||
@@ -5548,8 +5546,6 @@
|
||||
"Unsigned": "Non signé",
|
||||
"Roll Back to {previousVersion}": "Revenir à {previousVersion}",
|
||||
"Install Plugin from Package File…": "Installer un plugin depuis un fichier de paquet…",
|
||||
"Marketplace index URL": "URL de l'index de la marketplace",
|
||||
"Refresh Marketplace": "Actualiser la marketplace",
|
||||
"The plugin system is a preview: its API and the plugins may still change.": "Le système de plugins est en préversion : son API et les plugins peuvent encore changer.",
|
||||
"Linked for development": "Lié pour le développement",
|
||||
"Marketplace": "Marketplace",
|
||||
@@ -5782,7 +5778,6 @@
|
||||
"Weekly limit": "Limite hebdomadaire",
|
||||
"Weekly Opus limit": "Limite hebdomadaire Opus",
|
||||
"Weekly Sonnet limit": "Limite hebdomadaire Sonnet",
|
||||
"Marketplace index URL (https://…/index.json or a folder path)": "URL de l'index de la marketplace (https://…/index.json ou un chemin de dossier)",
|
||||
"Editor Providers": "Fournisseurs d'éditeurs",
|
||||
"Syntax errors": "Erreurs de syntaxe",
|
||||
"Pull Members Up…": "Remonter les membres…",
|
||||
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача