Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 84abdc1885 fix(plugins): move the repository URL to the gear menu and drop the no-repository hint
The Available tab always showed a "There is no online plugin repository"
notice under the search field when no index was set. Release builds use
the official index by default, so the notice only appeared in development
builds, where the empty URL field above it already said the same thing.
The URL field itself sat at the top of the list although most people never
change it.

- The notice is gone, and the search placeholder reads "Search plugins"
  because the list holds marketplace plugins as well as local ones.
- With a repository configured, the empty details panel says "No plugin
  selected" instead of claiming there is no online repository.
- The marketplace index URL is edited from the gear menu's "Plugin
  Repository…" dialog; leaving it empty restores the default.
2026-11-04 21:37:16 +08:00
l0ng-ai 3100aa2c00 feat(scratch): start new scratch files from a language template
A new Java scratch was an empty file that couldn't run until a class and
main method were typed in. Languages can now define `scratch-template` in
`languages/<id>.toml`; a new scratch gets that content with the caret at
`$END$`.

- Java, Kotlin, Go, Rust, C and C++ get a runnable `main`.
- Other languages still start empty.
2026-11-04 21:09:12 +08:00
l0ng-ai 52360c72d2 fix(editor): describe a Java file outside every project accurately
jdtls still completes and navigates JDK classes in a non-project file such
as a scratch; it only skips semantic checks and project classes. The banner
said navigation and completion don't work, and in a Maven or Gradle project
it offered a build reload that can't bring a file outside the project in.

- The banner now says only syntax errors are reported and only JDK classes
  resolve.
- The Maven / Gradle reload is offered only for files inside the open
  project (or one of its workspace projects).
2026-11-04 21:09:12 +08:00
l0ng-ai 7fd330912a fix(process): wait for a killed tree's descendants to exit on Windows (#1272)
`taskkill /T /F` only starts terminating the tree, and the caller then
waits for its direct child. A grandchild could still be exiting, with its
files open, when `kill_tree` returned or `Peer::exited` resolved. The
descendants are now opened before the kill and waited for (up to 5 s)
after it. A process counts as a descendant only if it started after its
parent, so a reused parent id doesn't pull in unrelated processes.

Closes #1270
2026-11-04 21:07:08 +08:00
l0ng-ai eaca68f263 test: retry first edit-path calls and wait for effects in flaky tests (#1271)
A provider call that starts a plugin instance (or reads files) can run past
the edit-path soft deadline on a slow runner and returns nothing; the tests
now ask again, as the editor does. The AI completion test cancels the slow
request only once the server has it, and measures from the cancel. The
SourcePreview test waits for the effect that marks the selection scope.

Closes #1269
2026-11-04 21:07:03 +08:00
l0ng-ai 4b5ef7069c fix(plugins): build new plugins outside the repository
- `openidea-plugin new` makes a Rust plugin depend on the SDK at the tool's
  release tag (git) unless the plugin is inside the source tree the tool was
  built from or `--sdk` is given; the path written before only resolved on
  the machine that built the tool.
- The command template compiles again: `run_command` returns
  `openidea_plugin::Error`. A test now runs `cargo test` on the generated
  plugin against the SDK.
- plugins/README.md: installing the tool with `cargo install --git`, the SDK
  dependency, where plugins can be installed (welcome screen and trusted
  projects), and where to look when a plugin misbehaves.
2026-11-04 20:55:31 +08:00
l0ng-ai 2cd16a723d fix(lsp): let language servers register the files they watch (#1223)
* fix(lsp): resolve newly installed Python packages without a restart

Packages installed into an excluded .venv (uv add, uv pip install) never
reached the Python language servers: the watcher reports changes in excluded
folders only as excluded_dirs, and didChangeWatchedFiles forwarded nothing but
the server's own source files. basedpyright kept its failed import resolution
until restarted.

Language servers get a watched-files list of globs. Files matching it, and
excluded folders matching it, are forwarded too; the Python servers watch
their configuration and site-packages.

* fix(lsp): let servers register the files they watch

Clients now support dynamic registration of workspace/didChangeWatchedFiles,
with relative patterns. Changes on disk go to each server as its registered
watchers match them, including folders in excluded trees (a package installed
into .venv, go.mod rewritten by go get). Folders outside the project that
relative patterns name (a virtualenv elsewhere, a path dependency) get their
own watchers. Servers that register nothing keep hearing of their languages'
files.

Registrations sent right after initialized are no longer dropped while the
server is still being marked ready.

Replaces the per-server watched-files list.
2026-11-04 20:44:24 +08:00
l0ng-ai 71c0515af6 fix(ui): no focus ring on controls that were only clicked (#1213)
The webview focuses a clicked button and the focus stays there: across
project window-tab switches, and popups hand it back to their trigger. The
next keystroke switches the engine to keyboard modality, so that button got a
focus ring (window tabs, the title-bar project switcher). A pressed control is
now marked and keeps no ring until Tab or an arrow key moves focus onto it.
Focus itself is unchanged, since actions resolve their context from it.

Closes #1211
2026-11-04 20:44:19 +08:00
l0ng-ai b473876d59 feat(agents): reference folders from @ completion (#1210)
Folders now appear in the composer's `@` completion next to files, from a new
`find_dirs` index query over the folders that hold indexed files (kept
incrementally in the index, ~0.5 ms on 100k files). Enter or a click
references the folder as `@dir/` and sends it as a resource link; Tab keeps
completing inside it.

Closes #1202
2026-11-04 20:44:14 +08:00
l0ng-ai d7886bab45 test(plugins): repeat the cancel until the call is running in the cancel test (#1263)
Closes #1248
2026-11-04 20:34:33 +08:00
l0ng-ai dd370654cb feat(plugins): leave room in plugin API 1.0 for what will grow (#1245)
Closes #1237
2026-11-04 20:11:46 +08:00
55 змінених файлів з 1315 додано та 180 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -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"] }
+101 -15
Переглянути файл
@@ -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
+1
Переглянути файл
@@ -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 {
+68 -8
Переглянути файл
@@ -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();
+5 -4
Переглянути файл
@@ -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()),
}
}
}
+5
Переглянути файл
@@ -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")?)
});
+38 -1
Переглянути файл
@@ -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],
+1
Переглянути файл
@@ -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"
+29 -16
Переглянути файл
@@ -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);
@@ -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))]
@@ -2434,7 +2442,12 @@ fn completion_quick_fixes_problems_and_event_kinds_of_api_1() {
};
let at = ide_core::Pos::new(0, 0);
let items = f.host.provide_completion(&doc("rich"), at, None);
// 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()),
+3
Переглянути файл
@@ -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()))
+47
Переглянути файл
@@ -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();
+9
Переглянути файл
@@ -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)
}
+71 -1
Переглянути файл
@@ -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")
}
+17
Переглянути файл
@@ -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", "")]);
+8
Переглянути файл
@@ -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(),
}
}
}
+4
Переглянути файл
@@ -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");
+1 -1
Переглянути файл
@@ -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 },
+150
Переглянути файл
@@ -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));
}
}
+19 -5
Переглянути файл
@@ -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(&params)),
"workspace/workspaceFolders" => Ok(mgr.workspace_folders(&self.server)),
"client/registerCapability" => {
self.registration(&params, true);
self.registration(&mgr, &params, true);
Ok(Value::Null)
}
"client/unregisterCapability" => {
self.registration(&params, false);
self.registration(&mgr, &params, false);
Ok(Value::Null)
}
"workspace/applyEdit" => self.apply_edit(&mgr, params),
+70 -11
Переглянути файл
@@ -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)?;
+22
Переглянути файл
@@ -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)
+72 -1
Переглянути файл
@@ -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())]);
+1
Переглянути файл
@@ -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,
+8
Переглянути файл
@@ -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"
+8
Переглянути файл
@@ -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"
+7
Переглянути файл
@@ -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"
+7
Переглянути файл
@@ -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
+5
Переглянути файл
@@ -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"
+5
Переглянути файл
@@ -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"
+3
Переглянути файл
@@ -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,
+25 -2
Переглянути файл
@@ -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"
@@ -773,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
+1
Переглянути файл
@@ -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,
+7
Переглянути файл
@@ -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]
+6
Переглянути файл
@@ -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;
+53 -1
Переглянути файл
@@ -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();
}
});
+19 -9
Переглянути файл
@@ -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 };
},
};
+25 -19
Переглянути файл
@@ -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>
</>
) : (
+3 -1
Переглянути файл
@@ -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}
+27
Переглянути файл
@@ -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);
});
+84
Переглянути файл
@@ -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"]);
});
});
+23
Переглянути файл
@@ -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}`;
-11
Переглянути файл
@@ -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%;
}
+21 -35
Переглянути файл
@@ -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 && !marketError && (
<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>{" "}
+48 -1
Переглянути файл
@@ -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");
@@ -663,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,
+52 -4
Переглянути файл
@@ -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 {
+22 -2
Переглянути файл
@@ -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;
+12 -8
Переглянути файл
@@ -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({
+2
Переглянути файл
@@ -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
+2 -7
Переглянути файл
@@ -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…",
+2 -7
Переглянути файл
@@ -1937,7 +1937,6 @@
"Search frames": "프레임 검색",
"Search in comments and strings": "주석 및 문자열에서 검색",
"Search installed plugins": "설치된 플러그인 검색",
"Search local plugins": "로컬 플러그인 검색",
"Search packages": "패키지 검색",
"Search projects": "프로젝트 검색",
"Search pull requests": "풀 리퀘스트 검색",
@@ -3492,7 +3491,7 @@
"Not installed": "설치되지 않음",
"{command} was not found on PATH": "PATH에서 {command}을(를) 찾을 수 없습니다",
"Agent tasks": "에이전트 작업",
"Describe a task for the agent. @ references a file, / runs a command": "에이전트에게 맡길 작업을 설명하세요. @는 파일 참조, /는 명령 실행",
"Describe a task for the agent. @ references a file or folder, / runs a command": "에이전트에게 맡길 작업을 설명하세요. @는 파일·폴더 참조, /는 명령 실행",
"away from your changes": "변경 사항과 분리됨",
"edits your files directly": "파일을 직접 편집함",
"from": "기준",
@@ -4517,7 +4516,6 @@
"Memory & Diagnostics": "메모리 및 진단",
"Over budget ({budget})": "예산 초과({budget})",
"dev": "개발",
"{label}. Showing plugin packages available on this machine.": "{label}. 이 머신에서 사용 가능한 플러그인 패키지를 표시합니다.",
"Zoomed into {name}": "{name} 확대됨",
"Rename directory '{current}' and its usages to:": "디렉터리 '{current}' 및 해당 사용 위치의 새 이름:",
"Rename file '{current}' and its usages to:": "파일 '{current}' 및 해당 사용 위치의 새 이름:",
@@ -5627,7 +5625,7 @@
"Java project import failed": "Java 프로젝트 가져오기 실패",
"The Java project cannot be imported because these files use a name Windows reserves for devices: {paths}. Delete or rename them, then restart the Java language server.": "다음 파일이 Windows에서 장치용으로 예약된 이름을 사용하므로 Java 프로젝트를 가져올 수 없습니다: {paths}. 파일을 삭제하거나 이름을 변경한 후 Java 언어 서버를 다시 시작하세요.",
"This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.": "이 파일은 해당 Java 모듈의 소스 폴더 밖에 있습니다. 구문 오류만 보고되며 탐색과 코드 완성이 작동하지 않습니다.",
"This file does not belong to an imported Java project: only syntax errors are reported, and navigation and completion don't work.": "이 파일은 가져온 Java 프로젝트에 속하지 않습니다. 구문 오류만 보고되며 탐색과 코드 완성이 작동하지 않습니다.",
"This file does not belong to an imported Java project: only syntax errors are reported, and only JDK classes resolve.": "이 파일은 가져온 Java 프로젝트에 속하지 않습니다. 구문 오류만 보고되며 JDK 클래스만 확인됩니다.",
"This Go file belongs to no package of the workspace: code insight is limited.": "이 Go 파일은 작업 공간의 어떤 패키지에도 속하지 않습니다. 코드 인사이트가 제한됩니다.",
"This Rust file is not included in any crate: rust-analyzer can't offer code insight for it.": "이 Rust 파일은 어떤 crate에도 포함되어 있지 않습니다. rust-analyzer가 코드 인사이트를 제공할 수 없습니다.",
"Reload Maven Projects": "Maven 프로젝트 다시 로드",
@@ -5708,14 +5706,11 @@
"Unsigned": "서명되지 않음",
"Roll Back to {previousVersion}": "{previousVersion}(으)로 롤백",
"Install Plugin from Package File…": "패키지 파일에서 플러그인 설치…",
"Marketplace index URL": "마켓플레이스 인덱스 URL",
"Refresh Marketplace": "마켓플레이스 새로 고침",
"Marketplace": "마켓플레이스",
"Could not download plugin": "플러그인을 다운로드할 수 없습니다",
"Rolled back {name} to {version}": "{name}을(를) {version}(으)로 롤백했습니다",
"Could not roll back": "롤백할 수 없습니다",
"Could not open the package": "패키지를 열 수 없습니다",
"Marketplace index URL (https://…/index.json or a folder path)": "마켓플레이스 인덱스 URL(https://…/index.json 또는 폴더 경로)",
"Settings of the plugin; projects can override them.": "플러그인 설정입니다. 프로젝트에서 재정의할 수 있습니다.",
"Menus": "메뉴",
"Shortcuts": "단축키",
+7 -7
Переглянути файл
@@ -1940,8 +1940,8 @@
"Search frames": "搜索帧",
"Search in comments and strings": "在注释和字符串中搜索",
"Search installed plugins": "搜索已安装的插件",
"Search local plugins": "搜索本地插件",
"Search packages": "搜索软件包",
"Search plugins": "搜索插件",
"Search projects": "搜索项目",
"Search pull requests": "搜索拉取请求",
"Search query": "搜索查询",
@@ -3498,7 +3498,7 @@
"Not installed": "未安装",
"{command} was not found on PATH": "在 PATH 中找不到 {command}",
"Agent tasks": "Agent 任务",
"Describe a task for the agent. @ references a file, / runs a command": "描述要交给 agent 的任务。@ 引用文件,/ 运行命令",
"Describe a task for the agent. @ references a file or folder, / runs a command": "描述要交给 agent 的任务。@ 引用文件或文件夹,/ 运行命令",
"away from your changes": "不影响你的改动",
"edits your files directly": "直接修改你的文件",
"from": "基于",
@@ -4535,7 +4535,6 @@
"Memory & Diagnostics": "内存与诊断",
"Over budget ({budget})": "超出预算({budget})",
"dev": "开发",
"{label}. Showing plugin packages available on this machine.": "{label}。显示此计算机上可用的插件包。",
"Zoomed into {name}": "已缩放到 {name}",
"Rename directory '{current}' and its usages to:": "将目录“{current}”及其用法重命名为:",
"Rename file '{current}' and its usages to:": "将文件“{current}”及其用法重命名为:",
@@ -5655,7 +5654,7 @@
"Java project import failed": "Java 项目导入失败",
"The Java project cannot be imported because these files use a name Windows reserves for devices: {paths}. Delete or rename them, then restart the Java language server.": "无法导入 Java 项目,因为这些文件使用了 Windows 保留的设备名:{paths}。请删除或重命名这些文件,然后重启 Java 语言服务器。",
"This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.": "此文件不在所属 Java 模块的源码目录中:只报告语法错误,跳转和补全不可用。",
"This file does not belong to an imported Java project: only syntax errors are reported, and navigation and completion don't work.": "此文件不属于已导入的 Java 项目:只报告语法错误,跳转和补全不可用。",
"This file does not belong to an imported Java project: only syntax errors are reported, and only JDK classes resolve.": "此文件不属于已导入的 Java 项目:只报告语法错误,只能解析 JDK 中的类。",
"This Go file belongs to no package of the workspace: code insight is limited.": "此 Go 文件不属于工作区中的任何包:代码洞察功能受限。",
"This Rust file is not included in any crate: rust-analyzer can't offer code insight for it.": "此 Rust 文件未包含在任何 crate 中:rust-analyzer 无法为它提供代码洞察。",
"Reload Maven Projects": "重新加载 Maven 项目",
@@ -5791,14 +5790,15 @@
"1 theme": "1 个主题",
"{count} themes": "{count} 个主题",
"No theme plugins found in JetBrains IDEs on this computer. Choose a theme plugin downloaded from the JetBrains Marketplace (.jar or .zip) or a .theme.json file instead.": "在此计算机上的 JetBrains IDE 中未找到主题插件。请改为选择从 JetBrains Marketplace 下载的主题插件(.jar 或 .zip)或 .theme.json 文件。",
"Marketplace index URL": "插件市场索引 URL",
"Refresh Marketplace": "刷新插件市场",
"Marketplace": "插件市场",
"Plugin Repository…": "插件仓库…",
"Plugin Repository": "插件仓库",
"Marketplace index URL:": "插件市场索引 URL:",
"Leave empty to use the default repository.": "留空则使用默认仓库。",
"Could not download plugin": "无法下载插件",
"Rolled back {name} to {version}": "已将 {name} 回滚到 {version}",
"Could not roll back": "无法回滚",
"Could not open the package": "无法打开插件包",
"Marketplace index URL (https://…/index.json or a folder path)": "插件市场索引 URL(https://…/index.json 或文件夹路径)",
"Settings of the plugin; projects can override them.": "插件的设置;项目可以覆盖。",
"Menus": "菜单",
"Shortcuts": "快捷键",
+45
Переглянути файл
@@ -0,0 +1,45 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { installPointerFocus } from "./pointerFocus";
let uninstall: () => void;
beforeEach(() => {
document.body.innerHTML = `
<button id="tab" role="tab"><span id="label">go-app</span></button>
<button id="other">Other</button>
<div id="row" role="treeitem" tabindex="0">row</div>`;
uninstall = installPointerFocus();
});
afterEach(() => uninstall());
const el = (id: string) => document.getElementById(id)!;
const press = (id: string) => el(id).dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
const key = (k: string) => document.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true }));
const marked = (id: string) => el(id).hasAttribute("data-pointer-focus");
describe("installPointerFocus", () => {
it("marks the control under a press, not other focusable elements", () => {
press("label");
press("row");
expect([marked("tab"), marked("row")]).toEqual([true, false]);
});
it("keeps the mark when focus comes back without keyboard navigation (a popup closed with Esc)", () => {
press("tab");
el("tab").focus();
el("other").focus();
key("Escape");
el("tab").focus();
expect(marked("tab")).toBe(true);
});
it("clears the mark when Tab or an arrow key moves focus onto the control", () => {
press("tab");
press("other");
key("Tab");
el("tab").focus();
expect(marked("tab")).toBe(false);
key("ArrowRight");
el("other").focus();
expect(marked("other")).toBe(false);
});
});
+34
Переглянути файл
@@ -0,0 +1,34 @@
/**
* No focus ring on a control the user only clicked. The webview focuses a clicked button and
* the focus outlives the click (across window-tab switches, and popups hand it back to their
* trigger); the next keystroke then switches the engine to keyboard modality and rings a button
* that was never reached by keyboard. Focus itself stays put (actions resolve their context from
* it): a pressed control is marked, `global.css` drops the ring of marked controls, and moving
* focus onto one with Tab or the arrow keys clears its mark.
*/
const CONTROL = "button, [role='button'], [role='tab'], a[href], summary";
const MARK = "data-pointer-focus";
const NAVIGATION = new Set(["Tab", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"]);
export function installPointerFocus(win: Window = window): () => void {
const doc = win.document;
let navigating = false;
const onPointerDown = (e: PointerEvent) => {
navigating = false;
if (e.target instanceof Element) e.target.closest(CONTROL)?.setAttribute(MARK, "");
};
const onKeyDown = (e: KeyboardEvent) => {
navigating = NAVIGATION.has(e.key);
};
const onFocusIn = (e: FocusEvent) => {
if (navigating && e.target instanceof Element) e.target.removeAttribute(MARK);
};
doc.addEventListener("pointerdown", onPointerDown, true);
doc.addEventListener("keydown", onKeyDown, true);
doc.addEventListener("focusin", onFocusIn, true);
return () => {
doc.removeEventListener("pointerdown", onPointerDown, true);
doc.removeEventListener("keydown", onKeyDown, true);
doc.removeEventListener("focusin", onFocusIn, true);
};
}
+6
Переглянути файл
@@ -152,6 +152,12 @@ a:hover {
outline-offset: -2px;
}
/* A control the user only clicked keeps no ring once a keystroke turns on keyboard modality
(`platform/pointerFocus.ts`); `!important` covers the components' own focus rings. */
[data-pointer-focus]:focus-visible {
outline: none !important;
}
::selection {
background: var(--bg-editor-selection);
}
+3 -2
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import { SourcePreview } from "./SourcePreview";
/** A stable loader reference (a new function reloads, like the real module-level ones). */
@@ -24,6 +24,7 @@ describe("SourcePreview", () => {
const { container } = render(<SourcePreview path="/p/a.ts" line={0} load={loadOf("// TODO")} />);
await screen.findByText("// TODO");
// The scroll pane is a selection scope: drags stay inside, text stays copyable.
expect(container.querySelector("[data-selection-scope]")).toBeTruthy();
// Set by an effect, which can run after the text is on screen.
await waitFor(() => expect(container.querySelector("[data-selection-scope]")).toBeTruthy());
});
});