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

..
Автор SHA1 Повідомлення Дата
l0ng-ai a46ae78035 fix(java): run the language server on a full JDK 2026-11-02 15:07:21 +08:00
arookieofcтаa-rookie-of-C-language 95188d9f40 fix(vcs): fall back to plain blame when git rejects --contents with a revision (#787)
Git before 2.41 refuses `blame --contents - <revision>` ("cannot use --contents with final commit object name"), so blame failed outright on e.g. Ubuntu 22.04's git 2.34. On that error, blame the revision plainly and mark the edited lines as uncommitted from the diff against it, the same path restricted mode already uses. Fixes #755.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-02 14:33:14 +08:00
arookieofcтаa-rookie-of-C-language 6184330876 test(tools): compare the oxfmt script path by components on every platform (#786)
package_bin joins the manifest's bin entry (bin/oxfmt) onto a platform path, so on Windows the separators differ from the expected path and the oxfmt formatter test failed. Compare path components instead.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-02 14:33:11 +08:00
l0ng-ai 8e8a998abe feat(vcs): inline blame for the current line (#778)
Show the current line's author, relative date and commit summary as a dimmed hint after the line end, with the full message, date and hash on hover and the commit opened on click. Uncommitted lines read "You, now · Uncommitted changes". Reuses the blame command with a per-version cache and a debounced caret; skipped outside repositories, for untracked/ignored and very large files. Off by default: Settings › Version Control › Git › Show inline blame for the current line. Fixes #742.
2026-11-02 12:11:12 +08:00
misswellтаmisswell 743612d4ec fix(java): let jdtls read jars JDK 25 rejects (#771)
jdtls runs on JDK 25, whose ZipFile validates the ZIP64 extra field and rejects jars written by older tools (aspectjweaver 1.8.10: "Invalid CEN header (invalid zip64 extra data field size)"). ECJ then reports the dependency as unreadable, the module gets a build path error and never compiles, and running its main class fails with a missing class. Pass -Djdk.util.zip.disableZip64ExtraFieldValidation=true to jdtls unless the user set the property; set_jvm_property now owns the set-once, user-value-wins rule shared with the proxy properties.

Co-authored-by: misswell <[email protected]>
2026-11-02 12:05:25 +08:00
d0whc3r 44c603f7db feat: add oxfmt/oxlint support for JS and TS projects (#717)
Below an oxfmt configuration (.oxfmtrc.json/.jsonc, oxfmt.config.ts/.mts) Reformat Code runs oxfmt instead of Prettier, with the same external-formatter settings; oxfmt formats whole files, so a selection formats the file with a notice. oxlint --lsp serves JS/TS/React/Vue/Svelte files below an oxlint config. Both are managed npm tools; a missing oxfmt gets the same Install prompt and error handling as Prettier, and formatter messages are translated for either tool.

Co-authored-by: d0whc3r <[email protected]>
2026-11-02 11:22:49 +08:00
l0ng-ai e2f8e8d5bc fix(cpp): explain missing clang-tidy checks with Apple's clangd (#770)
Apple's clangd (/usr/bin/clangd, Xcode and CommandLineTools toolchains) is built without clang-tidy, so on a Mac without a managed clangd the checks from .clang-tidy never appear. When a clangd server for C, C++, Objective-C or Objective-C++ resolves to Apple's binary and the project has a .clang-tidy, show one warning per session with Install (managed LLVM clangd, which already takes precedence once installed) and Language Servers… actions. Fixes #692.
2026-11-02 11:14:27 +08:00
l0ng-ai ff97d7724c fix(ui): give AsciiDoc files their own icon (#763)
AsciiDoc became a recognized language in #731 but .adoc/.asciidoc still used the generic text glyph, failing the icon catalog test that requires every detected language to have a specific icon. Add a dedicated AsciiDoc icon (light/dark) and map both extensions to it.
2026-11-02 10:47:30 +08:00
kkmihaiтаkkMihai 239753df9f fix(editor): speed up rapid file opening (#734)
Rapid double-clicks queued their opens one after another and an earlier open finishing late took the active tab and focus back. Each open now carries a sequence/activation generation: only the newest request activates and focuses, older ones still add their tab. Pending file probes are shared, document and syntax loading overlap, and repeated folder double-clicks are handled. A pending navigation selection survives a later plain open of any file; a newer selection still wins. Refs #724.

Co-authored-by: kkMihai <[email protected]>
2026-11-02 10:38:02 +08:00
arookieofcтаa-rookie-of-C-language c8cc69a56e feat(language): add D language support (#728)
Register D (.d/.di) with comments, indentation, the built-in D highlighting mode, a file icon, and serve-d as its language server (dub.json/dub.sdl roots). Closes #727.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-02 10:04:03 +08:00
arookieofcтаa-rookie-of-C-language c5ff0de1ee fix(terminal): open the file a link names, not a same-named one (#711)
resolvePath only understood POSIX paths, so on Windows the direct lookup never matched and every click fell back to a project-wide search by bare file name, which opened any same-named file. Resolve Windows drive paths and backslashes, and make the fallback query include the link's directory and check the hit's project-relative path ends with it; a bare-name match is used only for links without a directory. Fixes #705.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-02 10:03:59 +08:00
Bl0ck fb55847afa feat(editor): recognize AsciiDoc files with basic highlighting (#731)
Register .adoc/.asciidoc as AsciiDoc in the language catalog (backend registry and in-memory backend) with // line comments, and add a lightweight CodeMirror stream mode for headings, attributes, delimited blocks, emphasis, inline code, URLs and comments. Refs #708.

Co-authored-by: Bl0ck154 <[email protected]>
2026-11-02 10:01:04 +08:00
misswellтаmisswell 2653021389 fix(java): pass the IDE proxy to language-server JVMs (#745)
A JVM reads none of HTTP_PROXY/HTTPS_PROXY, so jdtls went direct and a repository that accepts the connection but never answers stalled the Maven import. ProxySettings::jvm_args turns the proxy configuration into JVM system properties (useSystemProxies for Auto, http/https/nonProxyHosts for a manual HTTP proxy, socks* for SOCKS), passed to jdtls as --jvm-arg; a property the user set themselves (matched by exact name) wins. Maven sync keeps Maven's normal snapshot update policy.

Co-authored-by: misswell <[email protected]>
2026-11-02 10:00:32 +08:00
arookieofcтаa-rookie-of-C-language e7f00ee7ce fix(tools): pick the platform archive for kotlin-lsp (#726)
kotlin-lsp releases renamed their archives to kotlin-server-*, so no rule matched and the loose kotlin-*.zip fallback picked the Windows zip on every OS. Match the current names per platform: .sit (a zip archive) on macOS, .tar.gz on Linux, .win.zip on Windows; extract .sit as zip; drop the loose fallback.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-02 09:59:54 +08:00
Jasmeet Singhтаjasi381 4015a5b71f fix(maven): read Maven 4 <subprojects> as modules (#700)
Maven 4 (model 4.1.0) declares child projects in <subprojects>/<subproject> instead of <modules>/<module>. The POM reader only read <modules>, so the children of a Maven 4 aggregator were missing. Projects and profiles now read both.

Co-authored-by: jasi381 <[email protected]>
2026-11-01 21:46:36 +08:00
Dimas Victorтаdvictor357 88619505c3 feat(terminal): paste clipboard images into remote SSH terminals (#699)
In a remote-project window, pasting a clipboard image into the terminal uploads it to the SSH host that owns the terminal (new term_store_image command over the existing remote RPC) and inserts the POSIX-quoted path after a successful upload, without a newline. Images go to a private per-user terminal-images directory (0700/0600, UUID names, no-follow descriptor-relative writes) and expire after 24 hours on the next upload. Failures notify and insert nothing; text paste and local terminals are unchanged. Images over 20 MiB are rejected in both the frontend and the host.

Co-authored-by: dvictor357 <[email protected]>
2026-11-01 21:42:15 +08:00
Jasmeet Singhтаjasi381 0d0de01831 fix(java): re-sync jdtls after a Gradle sync so new dependencies resolve (#694)
After a Gradle sync, build_sync did not send java/projectConfigurationsUpdate to jdtls (only the Maven path did), so jdtls kept its cached classpath and dependencies newly added to build.gradle stayed unresolved. The update is now sent for both Maven and Gradle, listing each project's build file.

Co-authored-by: jasi381 <[email protected]>
2026-11-01 21:03:17 +08:00
arookieofcтаa-rookie-of-C-language 9ce3c4cd7e test(inspections): expect the Cargo group (#695)
The dependency-update inspection added a Cargo built-in group; the inspections tree test still expected the previous group list.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-01 20:46:03 +08:00
arookieofcтаl0ng-ai 74062497bd fix(core): read the Windows user PATH past REG_EXPAND_SZ quirks (#690)
* fix(core): read the Windows user PATH past REG_EXPAND_SZ quirks

`RegGetValueW` reports the unexpanded size of a `REG_EXPAND_SZ` value, so
a user `Path` that grows when its `%VAR%` references are expanded was
silently dropped. And when the terminating NUL leaked into the read
buffer with a stray UTF-16 unit behind it, `trim_end_matches('\0')`
left that unit in the string and `env::set_var("PATH", ...)` panicked
("strings passed to WinAPI cannot contain NULs", #683).

Re-read at the size the failed call reports, and cut the decoded string
at the first NUL instead of trimming trailing ones. Covered by a test
against a throwaway key under HKCU\Software.

* test: cover registry terminator corruption and refresh inspection groups

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-11-01 20:31:32 +08:00
l0ng-ai 8d7ce81249 fix(macos): open project windows as tabs per the system tab preference (#693)
Project windows only joined a tab group when merged explicitly or restored at startup; the macOS "Prefer tabs when opening documents" setting was never read, so opening another project or a workspace always created a separate window.

New project windows now follow that preference: with Always they join the active project window's tab group (forming one if needed) and are selected; with In Full Screen they do so only while the active window is full screen; with Manually they stay separate. This covers every path that creates a project window — Open, recent projects, workspaces, drag and drop, and opening from the command line or Finder — while LightEdit windows and restored groups keep their behaviour. New Workspace now opens through the same Open project in policy as Open Workspace, and a race when toggling full screen during the join is fixed.

Fixes #678
2026-11-01 20:14:08 +08:00
l0ng-ai b3abc8edd1 fix(remote): browse remote directories without an open project (#691)
Browse in the Remote Development dialog failed with "no project is open in this window" on the welcome screen, and in untrusted project windows: remote_bootstrap_list was not classified in the restricted-mode allowlist, so IPC authorization required a trusted project before the command reached SSH. The listing itself already used the selected SSH configuration and never depended on a project.

remote_bootstrap_list and deploy_test_connection are now allowed alongside the other application-level remote commands; both only connect or list remote paths and run no project code. Every other command used by the dialog and the welcome screen's remote entries was checked and is already classified.

Fixes #672
2026-11-01 20:09:08 +08:00
93 змінених файлів з 3690 додано та 311 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -4241,6 +4241,7 @@ dependencies = [
"ide-vfs",
"ide-workspace",
"parking_lot",
"rustix",
"serde",
"serde_json",
"specta",
+30 -2
Переглянути файл
@@ -285,6 +285,14 @@ fn texts(e: &Element, path: &str, item: &str) -> Vec<String> {
e.list(path, item).iter().map(|m| m.text.trim().to_owned()).filter(|m| !m.is_empty()).collect()
}
/// Child modules of a project or profile: `<modules>` (model 4.0.0) plus `<subprojects>`,
/// which Maven 4 (model 4.1.0) uses instead.
fn module_names(e: &Element) -> Vec<String> {
let mut names = texts(e, "modules", "module");
names.extend(texts(e, "subprojects", "subproject"));
names
}
fn read_build(e: &Element, plugins: &mut Vec<RawPlugin>, managed: &mut Vec<RawPlugin>) {
plugins.extend(e.list("build/plugins", "plugin").into_iter().filter_map(read_plugin));
managed.extend(e.list("build/pluginManagement/plugins", "plugin").into_iter().filter_map(read_plugin));
@@ -308,7 +316,7 @@ fn read_raw(project: &Element) -> RawPom {
name: project.text_of("name"),
parent,
properties: read_properties(project.child("properties")),
modules: texts(project, "modules", "module"),
modules: module_names(project),
deps: project.list("dependencies", "dependency").into_iter().filter_map(read_dep).collect(),
managed: project
.list("dependencyManagement/dependencies", "dependency")
@@ -329,7 +337,7 @@ fn read_raw(project: &Element) -> RawPom {
let mut profile = RawProfile {
id: p.text_of("id").unwrap_or_else(|| "default".into()),
active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"),
modules: texts(p, "modules", "module"),
modules: module_names(p),
properties: read_properties(p.child("properties")),
deps: p.list("dependencies", "dependency").into_iter().filter_map(read_dep).collect(),
..RawProfile::default()
@@ -1276,6 +1284,26 @@ mod tests {
</profiles>
</project>"#;
#[test]
fn maven_4_subprojects_are_modules() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"pom.xml",
r#"<project xmlns="http://maven.apache.org/POM/4.1.0"><modelVersion>4.1.0</modelVersion>
<groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version><packaging>pom</packaging>
<subprojects><subproject>core</subproject></subprojects>
<profiles><profile><id>extra</id><subprojects><subproject>extra</subproject></subprojects></profile></profiles>
</project>"#,
);
write(root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(root, "extra/pom.xml", "<project><artifactId>extra</artifactId></project>");
let model = load_with_repo(root, None);
assert_eq!(model.projects[0].modules, ["core/pom.xml"]);
assert!(model.projects.iter().any(|p| p.pom == "core/pom.xml" && p.aggregated));
}
#[test]
fn multi_module_parent_properties_and_managed_versions() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -19,4 +19,4 @@ tokio-util.workspace = true
tempfile.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_System_Registry", "Win32_Foundation"] }
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_Security", "Win32_System_Registry", "Win32_Foundation"] }
+6
Переглянути файл
@@ -82,6 +82,12 @@ pub enum IdeEvent {
status: ServerStatus,
message: Option<String>,
},
/// A running server lacks a capability; the UI offers the managed tool as a replacement.
LanguageServerWarning {
name: String,
message: String,
install_tool: String,
},
/// A stopped language server left the project's list (disabled in settings, or a
/// fallback that a preferred server took over from again).
LanguageServerRemoved {
+25
Переглянути файл
@@ -0,0 +1,25 @@
//! Capabilities needed by the JVM hosting Java language-server bundles.
use std::path::Path;
/// jdtls' javac bundle, java-debug / hot code replace, and Lombok / Gradle tooling.
const BUNDLE_MODULES: &[&str] = &["jdk.compiler", "jdk.jdi", "jdk.unsupported"];
/// Require a full JDK, including the modules used by jdtls and its bundles.
/// Temurin JREs can list the build JDK's modules in `release` even when the runtime
/// image omits them, so module metadata alone does not establish suitability.
pub fn supports_java_bundles(home: &Path) -> bool {
let Ok(release) = std::fs::read_to_string(home.join("release")) else { return false };
let property =
|key: &str| release.lines().find_map(|line| line.trim().strip_prefix(key)).map(|v| v.trim().trim_matches('"'));
let javac = if cfg!(windows) { "javac.exe" } else { "javac" };
if property("IMAGE_TYPE=").is_some_and(|image| image.eq_ignore_ascii_case("jre"))
|| !home.join("bin").join(javac).is_file()
{
return false;
}
match property("MODULES=") {
Some(modules) => BUNDLE_MODULES.iter().all(|required| modules.split_whitespace().any(|m| m == *required)),
None => BUNDLE_MODULES.iter().all(|m| home.join("jmods").join(format!("{m}.jmod")).is_file()),
}
}
+1
Переглянути файл
@@ -11,6 +11,7 @@ pub mod ids;
pub mod ignored;
pub mod inspection_settings;
pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
pub mod output_encoding;
pub mod process;
+133 -38
Переглянути файл
@@ -245,10 +245,7 @@ pub fn find_executable(name: &str, search: &OsStr) -> Option<std::path::PathBuf>
#[cfg(windows)]
pub fn user_path() -> Option<OsString> {
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_READ, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, RegCloseKey, RegGetValueW,
RegOpenKeyExW,
};
use windows_sys::Win32::System::Registry::{HKEY, HKEY_CURRENT_USER, KEY_READ, RegCloseKey, RegOpenKeyExW};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
@@ -259,45 +256,53 @@ pub fn user_path() -> Option<OsString> {
if RegOpenKeyExW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), 0, KEY_READ, &mut key) != ERROR_SUCCESS {
return None;
}
let read = || {
// Only `Path`; `REG_EXPAND_SZ` is accepted so `%USERPROFILE%\…` entries expand.
let mut kind = 0u32;
let mut len = 0u32;
let name = wide("Path");
let status = RegGetValueW(
key,
std::ptr::null(),
name.as_ptr(),
RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ,
&mut kind,
std::ptr::null_mut(),
&mut len,
);
if status != ERROR_SUCCESS || len == 0 {
return None;
}
let mut buf = vec![0u16; (len as usize).div_ceil(2)];
let status = RegGetValueW(
key,
std::ptr::null(),
name.as_ptr(),
RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ,
&mut kind,
buf.as_mut_ptr() as *mut _,
&mut len,
);
if status != ERROR_SUCCESS {
return None;
}
let text = String::from_utf16_lossy(&buf);
Some(text.trim_end_matches('\0').to_owned())
};
let value = read();
let value = read_registry_string(key, &wide("Path"));
RegCloseKey(key);
value.filter(|v| !v.trim().is_empty()).map(OsString::from)
}
}
/// The string of value `name` under open `key`: `REG_SZ` as-is, `REG_EXPAND_SZ` expanded
/// against the current environment. `None` when the value is missing or unreadable.
///
/// A `REG_EXPAND_SZ` value's first size query reports the unexpanded size, so a value
/// that grows when expanded is re-read at the size the failed call reports. And the
/// terminating NUL can leak into the read buffer with a stray UTF-16 unit behind it —
/// seen with a `REG_EXPAND_SZ` user `Path`, where it made `env::set_var("PATH", …)`
/// panic with "strings passed to WinAPI cannot contain NULs" — so the text is cut at
/// the first NUL, not just stripped of trailing ones.
#[cfg(windows)]
fn read_registry_string(key: windows_sys::Win32::System::Registry::HKEY, name: &[u16]) -> Option<String> {
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, ERROR_SUCCESS};
use windows_sys::Win32::System::Registry::{RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, RegGetValueW};
const FLAGS: u32 = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ;
let mut kind = 0u32;
let mut len = 0u32;
// SAFETY: `name` is NUL-terminated and the size query writes only `kind` and `len`.
let status =
unsafe { RegGetValueW(key, std::ptr::null(), name.as_ptr(), FLAGS, &mut kind, std::ptr::null_mut(), &mut len) };
if status != ERROR_SUCCESS || len == 0 {
return None;
}
let buf = loop {
let mut buf = vec![0u16; len as usize / 2 + 1];
// SAFETY: as above; the buffer holds at least the `len` bytes the call may write.
let status = unsafe {
RegGetValueW(key, std::ptr::null(), name.as_ptr(), FLAGS, &mut kind, buf.as_mut_ptr() as *mut _, &mut len)
};
if status == ERROR_SUCCESS {
break buf;
}
if status != ERROR_MORE_DATA || len == 0 {
return None;
}
};
let text = String::from_utf16_lossy(&buf);
let end = text.find('\0').unwrap_or(text.len());
Some(text[..end].to_owned())
}
/// The user's own `PATH` entries; `None` outside Windows (see the Windows impl).
#[cfg(not(windows))]
pub fn user_path() -> Option<OsString> {
@@ -334,6 +339,96 @@ mod tests {
}
}
#[cfg(windows)]
#[test]
fn registry_strings_expand_and_stay_terminator_free() {
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_EXPAND_SZ, REG_SZ, RegCloseKey, RegCreateKeyExW,
RegDeleteTreeW, RegSetValueExW,
};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
struct TestState {
key: HKEY,
name: String,
variable: String,
previous: Option<OsString>,
}
impl Drop for TestState {
fn drop(&mut self) {
// SAFETY: the key belongs to this test; Windows environment mutation is safe.
unsafe {
RegCloseKey(self.key);
RegDeleteTreeW(HKEY_CURRENT_USER, wide(&self.name).as_ptr());
match &self.previous {
Some(value) => std::env::set_var(&self.variable, value),
None => std::env::remove_var(&self.variable),
}
}
}
}
let name = format!("Software\\ai.l0ng.openidea.registry-read-test-{}", std::process::id());
let variable = format!("OPENIDEA_TEST_REGVAR_{}", std::process::id());
let long = "x".repeat(600);
let mut key: HKEY = std::ptr::null_mut();
let opened = unsafe {
RegCreateKeyExW(
HKEY_CURRENT_USER,
wide(&name).as_ptr(),
0,
std::ptr::null(),
0,
KEY_READ | KEY_WRITE,
std::ptr::null(),
&mut key,
std::ptr::null_mut(),
)
};
assert_eq!(opened, ERROR_SUCCESS, "the test key must be creatable under HKCU\\Software");
let _cleanup = TestState { key, name, previous: std::env::var_os(&variable), variable: variable.clone() };
// SAFETY: Windows permits environment mutation. No other test uses this process-specific name.
unsafe { std::env::set_var(&variable, &long) };
let set = |value: &str, kind: u32, data: &[u16]| {
// SAFETY: `key` is open for writing and `data` holds `data.len() * 2` bytes.
assert_eq!(
unsafe {
RegSetValueExW(
key,
wide(value).as_ptr(),
0,
kind,
data.as_ptr() as *const _,
(data.len() * 2) as u32,
)
},
ERROR_SUCCESS
);
};
let read = |value: &str| read_registry_string(key, &wide(value));
set("Plain", REG_SZ, &wide("plain"));
set("Expand", REG_EXPAND_SZ, &wide(&format!("%{variable}%\\bin")));
set("ExpandLong", REG_EXPAND_SZ, &wide(&format!("%{variable}%")));
// Reproduce the reported interior terminator followed by a stale UTF-16 unit.
set("TrailingGarbage", REG_SZ, &wide("C:\\Zed\\bin\0n"));
set("ExpandTrailingGarbage", REG_EXPAND_SZ, &wide(&format!("%{variable}%\\bin\0n")));
set("Empty", REG_SZ, &wide(""));
let plain = read("Plain");
let expand = read("Expand");
let expand_long = read("ExpandLong");
assert_eq!(plain.as_deref(), Some("plain"));
assert_eq!(expand.as_deref(), Some(format!("{long}\\bin")).as_deref());
// Longer than its unexpanded form: needs the re-read at the expanded size.
assert_eq!(expand_long.as_deref(), Some(long.as_str()));
assert_eq!(read("TrailingGarbage").as_deref(), Some("C:\\Zed\\bin"));
assert_eq!(read("ExpandTrailingGarbage").as_deref(), Some(format!("{long}\\bin")).as_deref());
assert_eq!(read("Empty").as_deref(), Some(""));
assert_eq!(read("Missing"), None);
}
#[test]
fn append_path_entries_keeps_the_order_and_adds_what_is_missing() {
let join = |dirs: &[&str]| std::env::join_paths(dirs).unwrap();
+80
Переглянути файл
@@ -207,6 +207,58 @@ impl ProxySettings {
env.push((OsString::from("no_proxy"), Some(OsString::from(no_proxy))));
env
}
/// System properties that make a JVM follow this configuration. A JVM reads none of
/// [`Self::child_env`]: a Java tool (jetty, Maven's resolver, a language server's own
/// HTTP client) goes direct without these, and a repository its proxy answers in
/// milliseconds can then hang it instead.
pub fn jvm_args(&self) -> Vec<String> {
match self.mode {
// macOS and Windows JVMs read the system proxy with this one.
ProxyMode::Auto => vec!["-Djava.net.useSystemProxies=true".into()],
ProxyMode::None => Vec::new(),
ProxyMode::Manual if self.manual() => self.manual_jvm_args(),
ProxyMode::Manual => Vec::new(),
}
}
fn manual_jvm_args(&self) -> Vec<String> {
let (host, port) = (self.host.trim(), self.port);
match self.kind {
ProxyKind::Http => {
// HTTPS hosts read `https.proxyHost`, plain ones `http.proxyHost`.
let mut args = vec![
format!("-Dhttp.proxyHost={host}"),
format!("-Dhttp.proxyPort={port}"),
format!("-Dhttps.proxyHost={host}"),
format!("-Dhttps.proxyPort={port}"),
];
let hosts = self.non_proxy_hosts();
if !hosts.is_empty() {
args.push(format!("-Dhttp.nonProxyHosts={}", hosts.join("|")));
}
args
}
// SOCKS proxies every TCP connection, so there is one property pair.
ProxyKind::Socks => vec![
format!("-DsocksProxyHost={host}"),
format!("-DsocksProxyPort={port}"),
"-Djava.net.useSystemProxies=false".into(),
],
}
}
/// [`Self::no_proxy`] in the JVM's `http.nonProxyHosts` format: `|` between host
/// globs. CIDR ranges and IPv6 literals have no equivalent there and are dropped.
fn non_proxy_hosts(&self) -> Vec<String> {
let mut hosts: Vec<String> = LOOPBACK.iter().filter(|h| !h.contains(':')).map(|h| (*h).to_owned()).collect();
for entry in self.no_proxy_entries() {
if !entry.contains(['/', ':', '[', ']']) && !hosts.contains(&entry) {
hosts.push(entry);
}
}
hosts
}
}
/// Case-insensitive host glob (`pattern` is lowercase): `*` matches any run of characters.
@@ -292,6 +344,34 @@ mod tests {
assert!(p.child_env().is_empty());
}
#[test]
fn jvm_args_carry_the_proxy_as_system_properties() {
// A JVM reads none of `child_env`: a Java language server needs these to not go
// direct while curl, git and Node follow the environment.
assert_eq!(ProxySettings::default().jvm_args(), ["-Djava.net.useSystemProxies=true"]);
assert!(ProxySettings { mode: ProxyMode::None, ..manual("proxy", 3128) }.jvm_args().is_empty());
assert_eq!(
manual("proxy.corp", 3128).jvm_args(),
[
"-Dhttp.proxyHost=proxy.corp",
"-Dhttp.proxyPort=3128",
"-Dhttps.proxyHost=proxy.corp",
"-Dhttps.proxyPort=3128",
"-Dhttp.nonProxyHosts=localhost|127.0.0.1",
]
);
let socks = ProxySettings { kind: ProxyKind::Socks, ..manual("10.0.0.1", 1080) };
assert_eq!(socks.jvm_args()[..2], ["-DsocksProxyHost=10.0.0.1", "-DsocksProxyPort=1080"]);
// `http.nonProxyHosts` takes host globs: CIDR ranges and IPv6 literals drop out.
let p = ProxySettings {
no_proxy: "*.corp.com, 172.0.0.0/8, [::1], ::1, localhost".into(),
..manual("proxy.corp", 3128)
};
assert_eq!(p.jvm_args().last().unwrap(), "-Dhttp.nonProxyHosts=localhost|127.0.0.1|*.corp.com");
// A manual proxy without a host connects directly, and so does its JVM.
assert!(manual(" ", 80).jvm_args().is_empty());
}
#[test]
fn manual_http_and_socks_urls() {
let p = manual("proxy.corp", 3128);
+3
Переглянути файл
@@ -41,6 +41,8 @@ impl Default for VcsSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitSettings {
/// Show blame after the current editor line.
pub inline_blame: bool,
/// Path to the git executable; empty = auto-detect.
pub executable: String,
/// Default of Update Project: `merge` | `rebase`.
@@ -71,6 +73,7 @@ pub struct GitSettings {
impl Default for GitSettings {
fn default() -> Self {
Self {
inline_blame: false,
executable: String::new(),
update_method: "merge".into(),
auto_update_on_push_rejected: false,
+3
Переглянути файл
@@ -54,5 +54,8 @@ tempfile.workspace = true
ide-ssh = { workspace = true, features = ["testing"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
[target.'cfg(unix)'.dependencies]
rustix = { version = "1.1", features = ["fs", "process"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
+39 -11
Переглянути файл
@@ -7,6 +7,16 @@ use ide_core::{DocId, IdeError, IdeEvent, IdeResult, Range, TextEdit};
use ide_language::FormatterConfig;
use ide_lsp::types::FormatOptions;
use ide_tools::{Tools, formatter};
use std::path::Path;
const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.config.ts", "oxfmt.config.mts"];
/// oxfmt below an oxfmt configuration file, else Prettier. The Prettier
/// settings (languages, preference, on save) apply to both.
fn external_tool(file: &Path) -> &'static str {
let oxfmt = OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
if oxfmt { "oxfmt" } else { "prettier" }
}
fn external_selected(config: Option<&FormatterConfig>, language: &str, settings: &PrettierSettings, lsp: bool) -> bool {
config.is_some_and(|c| c.tool == "prettier")
@@ -44,16 +54,19 @@ pub async fn format(
return Err(IdeError::invalid("The file is read-only"));
}
let config = config.unwrap().clone();
let custom = ide_sdk::apply::setting_path(&project.root, &prettier.path);
let tool = external_tool(&snap.path);
let name = formatter::display_name(tool);
let custom = ide_sdk::apply::setting_path(&project.root, &prettier.path).filter(|_| tool == "prettier");
let tools = Tools::new(&host.local_data_dir);
let whole_selection = range.is_some() && !config.range;
let whole_selection = range.is_some() && !formatter::supports_range(tool, &config);
let edits: IdeResult<Vec<TextEdit>> = tokio::task::spawn_blocking(move || {
let text = ide_text::Document::new(&snap.text);
let offsets = range.map(|r| (text.pos_to_offset(r.start), text.pos_to_offset(r.end)));
let mut command = tools.formatter_command(&config.tool, &snap.path, custom.as_deref())?;
command.current_dir(snap.path.parent().ok_or_else(|| IdeError::invalid("Prettier: file has no directory"))?);
command.args(formatter::arguments(&config, &snap.path, options.tab_size, options.insert_spaces, offsets));
let formatted = formatter::run(command, &snap.text, &Default::default())?;
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
let dir = snap.path.parent().ok_or_else(|| IdeError::invalid(format!("{name}: file has no directory")))?;
command.current_dir(dir);
command.args(formatter::arguments(tool, &config, &snap.path, options.tab_size, options.insert_spaces, offsets));
let formatted = formatter::run(tool, command, &snap.text, &Default::default())?;
Ok(text
.diff(&formatted)
.changes
@@ -69,13 +82,13 @@ pub async fn format(
if edits.is_ok() && whole_selection {
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Info,
title: "Prettier".into(),
body: Some(
"Prettier does not support selection formatting for this language; formatted the whole file".into(),
),
title: name.into(),
body: Some(format!(
"{name} does not support selection formatting for this language; formatted the whole file"
)),
});
}
edits.map_err(|e| e.with_tool("prettier"))
edits.map_err(|e| e.with_tool(tool))
}
#[cfg(test)]
@@ -104,4 +117,19 @@ mod tests {
assert!(!external_selected(ts.formatter.as_ref(), "typescript", &settings, false));
assert!(!external_selected(None, "rust", &settings, false));
}
#[test]
fn oxfmt_config_selects_oxfmt_over_prettier() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("web/src")).unwrap();
let (web, api) = (root.join("web/src/app.ts"), root.join("api/main.ts"));
assert_eq!(external_tool(&web), "prettier");
for config in OXFMT_CONFIGS {
std::fs::write(root.join("web").join(config), "{}").unwrap();
assert_eq!(external_tool(&web), "oxfmt", "{config}");
assert_eq!(external_tool(&api), "prettier", "{config}");
std::fs::remove_file(root.join("web").join(config)).unwrap();
}
}
}
+21 -14
Переглянути файл
@@ -133,22 +133,29 @@ pub async fn build_sync(
host.end_request(request);
let model = result??;
if tool == BuildTool::Maven
&& let Some(maven) = &model.maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436).
if let Some(bridge) = &project.kotlin_bridge {
bridge.configure_maven(offline, bridge_profiles);
}
let lsp = project.lsp.clone();
let uris = maven.projects.iter().map(|p| ide_lsp::path_to_uri_string(&project.root.join(&p.pom))).collect();
tokio::spawn(async move {
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
});
bridge.configure_maven(offline, bridge_profiles);
}
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436). The same
// holds for Gradle: it reuses its cached classpath on restart, so a
// dependency added to `build.gradle` stays unresolved until told to sync.
let build_files: Vec<String> = match tool {
BuildTool::Maven => model.maven.iter().flat_map(|m| m.projects.iter().map(|p| p.pom.clone())).collect(),
BuildTool::Gradle => {
model.gradle.iter().flat_map(|g| g.projects.iter().filter_map(|p| p.build_file.clone())).collect()
}
};
let lsp = project.lsp.clone();
let uris = build_files.iter().map(|f| ide_lsp::path_to_uri_string(&project.root.join(f))).collect();
tokio::spawn(async move {
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
});
Ok(model)
}
+46
Переглянути файл
@@ -3,6 +3,21 @@ use crate::Host;
use ide_core::{IdeResult, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
mod images;
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
pub async fn store_image(host: &Host, id: TerminalId, data: Vec<u8>, mime: String) -> IdeResult<String> {
if data.len() > MAX_IMAGE_BYTES {
return Err(ide_core::IdeError::invalid("image is too large to paste (limit 20 MB)"));
}
if !host.terminals.contains(id) {
return Err(ide_core::IdeError::invalid("terminal session not found"));
}
let data_dir = host.data_dir.clone();
host.blocking(move || images::store(&data_dir, &data, &mime)).await
}
pub fn spawn(
host: &Host,
window: &str,
@@ -47,3 +62,34 @@ pub fn kill(host: &Host, id: TerminalId) -> IdeResult<()> {
pub fn is_busy(host: &Host, id: TerminalId) -> IdeResult<bool> {
host.terminals.is_busy(id)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
use ide_core::{NullSink, error::ErrorKind};
use std::sync::Arc;
#[tokio::test]
async fn image_size_limit_is_checked_before_storage() {
let root = tempfile::tempdir().unwrap();
let host = Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: root.path().join("data"),
local_data_dir: root.path().join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let id = TerminalId::next();
let error = store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert_eq!(error.message, "image is too large to paste (limit 20 MB)");
let error = store_image(&host, id, vec![0; MAX_IMAGE_BYTES], "image/png".into()).await.unwrap_err();
assert_eq!(error.message, "terminal session not found");
assert!(!host.data_dir.join("terminal-images").exists());
}
}
+220
Переглянути файл
@@ -0,0 +1,220 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
#[cfg(unix)]
mod unix {
use super::*;
use rustix::fs::{self, AtFlags, Dir, Mode, OFlags};
use std::fs::File;
use std::io::{self, Write};
use std::os::unix::fs::MetadataExt;
use std::time::{Duration, SystemTime};
const LIFETIME: Duration = Duration::from_secs(24 * 60 * 60);
const DIRECTORY: &str = "terminal-images";
fn extension(mime: &str) -> IdeResult<&str> {
match mime {
"image/png" => Ok("png"),
"image/jpeg" => Ok("jpg"),
"image/gif" => Ok("gif"),
"image/webp" => Ok("webp"),
"image/bmp" => Ok("bmp"),
"image/svg+xml" => Ok("svg"),
"image/tiff" => Ok("tiff"),
"image/x-icon" => Ok("ico"),
_ => Err(IdeError::invalid("unsupported image type")),
}
}
fn open_directory(data_dir: &Path) -> io::Result<File> {
if !data_dir.is_absolute() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "data directory must be absolute"));
}
// The configured data directory and its ancestors are the host's trust boundary.
let parent =
fs::open(data_dir, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?;
match fs::mkdirat(&parent, DIRECTORY, Mode::from_bits_truncate(0o700)) {
Ok(()) | Err(rustix::io::Errno::EXIST) => (),
Err(e) => return Err(e.into()),
}
let dir: File = fs::openat(
&parent,
DIRECTORY,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?
.into();
let meta = dir.metadata()?;
if meta.uid() != rustix::process::geteuid().as_raw() || meta.mode() & 0o7777 != 0o700 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"terminal image directory is not private or owned by the current user",
));
}
Ok(dir)
}
fn owned_name(name: &str) -> bool {
let name = name.strip_prefix(".partial-").unwrap_or(name);
let Some((id, ext)) = name.strip_prefix("image-").and_then(|s| s.split_once('.')) else { return false };
id.len() == 32
&& id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
&& matches!(ext, "png" | "jpg" | "gif" | "webp" | "bmp" | "svg" | "tiff" | "ico")
}
fn cleanup(dir: &File, now: SystemTime) -> io::Result<()> {
for entry in Dir::read_from(dir)? {
let entry = entry?;
let name = entry.file_name();
if !name.to_str().is_ok_and(owned_name) {
continue;
}
// Never follow symlinks; opening nonblocking avoids hanging on an unexpected FIFO.
let fd = match fs::openat(
dir,
name,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(_) => continue,
};
let file = File::from(fd);
let meta = file.metadata()?;
if meta.is_file()
&& meta.uid() == rustix::process::geteuid().as_raw()
&& meta
.modified()
.ok()
.and_then(|time| now.duration_since(time).ok())
.is_some_and(|age| age >= LIFETIME)
{
match fs::unlinkat(dir, name, AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => (),
Err(error) => return Err(error.into()),
}
}
}
Ok(())
}
fn store_with(
data_dir: &Path,
data: &[u8],
mime: &str,
now: SystemTime,
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
) -> IdeResult<String> {
let ext = extension(mime)?;
let dir = open_directory(data_dir)?;
cleanup(&dir, now)?;
let name = format!("image-{}.{}", uuid::Uuid::new_v4().simple(), ext);
let temporary = format!(".partial-{name}");
let fd = fs::openat(
&dir,
temporary.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::from_bits_truncate(0o600),
)
.map_err(io::Error::from)?;
let mut file = File::from(fd);
if let Err(error) = write(&mut file, data) {
let _ = fs::unlinkat(&dir, temporary.as_str(), AtFlags::empty());
return Err(error.into());
}
if let Err(error) = fs::linkat(&dir, temporary.as_str(), &dir, name.as_str(), AtFlags::empty()) {
let _ = fs::unlinkat(&dir, temporary.as_str(), AtFlags::empty());
return Err(io::Error::from(error).into());
}
let _ = fs::unlinkat(&dir, temporary.as_str(), AtFlags::empty());
Ok(data_dir.join(DIRECTORY).join(name).to_string_lossy().into_owned())
}
pub(in crate::ops::term) fn store(data_dir: &Path, data: &[u8], mime: &str) -> IdeResult<String> {
store_with(data_dir, data, mime, SystemTime::now(), |file, bytes| file.write_all(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
fn stores_bytes_with_private_modes_and_unpredictable_names() {
let root = tempfile::tempdir().unwrap();
let first = store(root.path(), b"image bytes", "image/png").unwrap();
let second = store(root.path(), b"other", "image/jpeg").unwrap();
assert_ne!(first, second);
assert_eq!(fs::read(&first).unwrap(), b"image bytes");
assert_eq!(fs::metadata(&first).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(fs::metadata(root.path().join(DIRECTORY)).unwrap().permissions().mode() & 0o777, 0o700);
assert!(owned_name(Path::new(&first).file_name().unwrap().to_str().unwrap()));
}
#[test]
fn expiry_only_removes_owned_regular_files_at_boundary() {
let root = tempfile::tempdir().unwrap();
let dir = open_directory(root.path()).unwrap();
let path = root.path().join(DIRECTORY);
let now = SystemTime::now();
let names = [
"image-00000000000000000000000000000001.png",
"image-00000000000000000000000000000002.png",
"image-00000000000000000000000000000003.png",
"unrelated.png",
];
for (name, time) in names.iter().zip([
now - LIFETIME,
now - LIFETIME + Duration::from_secs(1),
now + Duration::from_secs(1),
now - LIFETIME,
]) {
let file = File::create(path.join(name)).unwrap();
file.set_times(fs::FileTimes::new().set_modified(time)).unwrap();
}
let link = path.join("image-00000000000000000000000000000004.png");
symlink(path.join(names[0]), &link).unwrap();
cleanup(&dir, now).unwrap();
assert!(!path.join(names[0]).exists());
for name in &names[1..] {
assert!(path.join(name).exists());
}
assert!(fs::symlink_metadata(link).unwrap().file_type().is_symlink());
}
#[test]
fn rejects_symlink_and_insecure_directory() {
let root = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let target = root.path().join(DIRECTORY);
symlink(outside.path(), &target).unwrap();
assert!(store(root.path(), b"x", "image/png").is_err());
fs::remove_file(&target).unwrap();
fs::create_dir(&target).unwrap();
fs::set_permissions(&target, fs::Permissions::from_mode(0o755)).unwrap();
assert!(store(root.path(), b"x", "image/png").is_err());
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
}
#[test]
fn failed_write_removes_partial_file() {
let root = tempfile::tempdir().unwrap();
let result = store_with(root.path(), b"partial", "image/png", SystemTime::now(), |file, bytes| {
file.write_all(bytes)?;
Err(io::Error::other("simulated failure"))
});
assert!(result.is_err());
assert_eq!(fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), 0);
}
}
}
#[cfg(unix)]
pub(super) use unix::store;
#[cfg(not(unix))]
pub(super) fn store(_data_dir: &Path, _data: &[u8], _mime: &str) -> IdeResult<String> {
Err(IdeError::internal("private terminal image storage is unsupported on this platform"))
}
+3
Переглянути файл
@@ -231,6 +231,9 @@ impl Dispatcher {
let on_output = c.channel("onOutput")?;
ops::term::spawn(&c.host, &c.window, c.arg("options")?, on_output)
})
.add("term_store_image", |c| async move {
ops::term::store_image(&c.host, c.arg("id")?, c.arg("data")?, c.arg("mime")?).await
})
.add("term_write", |c| async move { ops::term::write(&c.host, c.arg("id")?, &c.arg::<String>("data")?) })
.add("term_resize", |c| async move { ops::term::resize(&c.host, c.arg("id")?, c.arg("cols")?, c.arg("rows")?) })
.add("term_kill", |c| async move { ops::term::kill(&c.host, c.arg("id")?) })
+47
Переглянути файл
@@ -0,0 +1,47 @@
#![cfg(unix)]
use ide_core::{NullSink, TerminalId};
use ide_host::{Host, HostConfig, ops};
use ide_terminal::TerminalOptions;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn storage_requires_a_registered_terminal() {
let root = tempfile::tempdir().unwrap();
let data_dir = root.path().join("data");
std::fs::create_dir(&data_dir).unwrap();
let host = Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: data_dir.clone(),
local_data_dir: data_dir.clone(),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert!(ops::term::store_image(&host, TerminalId::next(), vec![1], "image/png".into()).await.is_err());
assert!(!data_dir.join("terminal-images").exists());
let terminal = host
.terminals
.spawn(
TerminalOptions {
cwd: root.path().into(),
shell: Some("/bin/sh".into()),
args: vec![],
env: Default::default(),
cols: 80,
rows: 24,
shell_integration: false,
},
Arc::new(NullSink),
Box::new(|_| {}),
)
.unwrap();
let path = ops::term::store_image(&host, terminal.id, vec![1, 2, 3], "image/png".into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 1);
}
+28 -1
Переглянути файл
@@ -8,6 +8,7 @@ use std::sync::Arc;
/// Built-in definitions, embedded at compile time. Add new languages here.
const BUILTIN: &[(&str, &str)] = &[
("asciidoc", include_str!("../../../languages/asciidoc.toml")),
("bat", include_str!("../../../languages/bat.toml")),
("c", include_str!("../../../languages/c.toml")),
("clojure", include_str!("../../../languages/clojure.toml")),
@@ -15,6 +16,7 @@ const BUILTIN: &[(&str, &str)] = &[
("cpp", include_str!("../../../languages/cpp.toml")),
("csharp", include_str!("../../../languages/csharp.toml")),
("css", include_str!("../../../languages/css.toml")),
("d", include_str!("../../../languages/d.toml")),
("dart", include_str!("../../../languages/dart.toml")),
("diff", include_str!("../../../languages/diff.toml")),
("dockerfile", include_str!("../../../languages/dockerfile.toml")),
@@ -373,6 +375,7 @@ mod tests {
/// `name`s exported by `@codemirror/language-data` or built into `src/editor/core/cm/languages.ts`
/// (the UI resolves `ui-mode` against these).
const UI_MODES: &[&str] = &[
"AsciiDoc",
"Batch",
"C",
"C++",
@@ -532,6 +535,12 @@ mod tests {
let reg = reg();
assert_eq!(detect(&reg, "src/main.rs"), "rust");
assert_eq!(detect(&reg, "a/b.TS"), "typescript");
for path in ["guide.adoc", "guide.asciidoc", "GUIDE.ADOC"] {
assert_eq!(detect(&reg, path), "asciidoc");
}
let asciidoc = reg.get(&LanguageId::new("asciidoc")).unwrap();
assert_eq!(asciidoc.ui_mode.as_deref(), Some("AsciiDoc"));
assert_eq!(asciidoc.line_comment.as_deref(), Some("//"));
assert_eq!(reg.detect(Path::new("script"), Some("#!/usr/bin/env python3")).as_str(), "python");
assert_eq!(detect(&reg, "README"), "plaintext");
assert_eq!(detect(&reg, "unknown.zzz"), "plaintext");
@@ -567,7 +576,7 @@ mod tests {
};
// After the TypeScript fallback (an available server before it would hide
// it); before the HTML server (hover, rename and symbols take the first).
assert_eq!(names("typescript"), ["vtsls", "typescript-language-server", "angular-language-server"]);
assert_eq!(names("typescript"), ["vtsls", "typescript-language-server", "angular-language-server", "oxlint"]);
assert_eq!(names("html"), ["angular-language-server", "vscode-html-language-server"]);
for lang in ["typescript", "html"] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
@@ -577,6 +586,24 @@ mod tests {
}
}
#[test]
fn oxlint_serves_js_files_only_below_its_config() {
let reg = reg();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("apps/web/src")).unwrap();
std::fs::write(root.join("apps/web/.oxlintrc.json"), "{}").unwrap();
for lang in ["javascript", "javascriptreact", "typescript", "typescriptreact", "vue", "svelte"] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
let oxlint = cfg.language_servers.iter().find(|s| s.name == "oxlint").unwrap();
assert_eq!((oxlint.command.as_str(), oxlint.args.as_slice()), ("oxlint", ["--lsp".to_string()].as_slice()));
assert!(oxlint.require_root_marker && !oxlint.fallback, "{lang}");
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &oxlint.root_markers);
assert_eq!(served("apps/web/src/main.ts"), Some(root.join("apps/web")), "{lang}");
assert_eq!(served("apps/api/main.ts"), None, "{lang}");
}
}
#[test]
fn html_of_angular_projects_is_an_angular_template() {
let reg = reg();
+126
Переглянути файл
@@ -0,0 +1,126 @@
//! Apple clangd accepts `.clang-tidy` projects but ships without clang-tidy checks.
use crate::{LspManager, Server};
use ide_core::IdeEvent;
use std::path::Path;
pub(crate) const MESSAGE: &str = "Apple's clangd does not run clang-tidy, so checks from .clang-tidy are not shown. Install clangd (LLVM) to get them.";
fn is_apple_clangd(path: &Path) -> bool {
if path == Path::new("/usr/bin/clangd") {
return true;
}
if !path.ends_with("usr/bin/clangd") {
return false;
}
path.starts_with("/Library/Developer/CommandLineTools")
|| path.ancestors().any(|ancestor| {
ancestor.file_name().is_some_and(|name| name == "Toolchains")
&& ancestor.parent().is_some_and(|developer| {
developer.ends_with("Contents/Developer")
&& developer.parent().and_then(Path::parent).and_then(Path::file_name).is_some_and(|name| {
let name = name.to_string_lossy();
name.starts_with("Xcode") && name.ends_with(".app")
})
})
})
}
fn has_config(server_root: &Path, project_root: &Path, file: &Path) -> bool {
server_root.join(".clang-tidy").is_file()
|| file
.parent()
.into_iter()
.flat_map(Path::ancestors)
.take_while(|dir| dir.starts_with(project_root))
.any(|dir| dir.join(".clang-tidy").is_file())
}
impl LspManager {
pub(crate) async fn check_clang_tidy(&self, server: &Server) {
if server.name != "clangd"
|| !cfg!(target_os = "macos")
|| self.shown_messages.lock().contains(&("clangd".into(), MESSAGE.into()))
{
return;
}
let binary = server.resolved_binary.read().clone();
let Some(binary) = binary else { return };
let files: Vec<_> = self
.docs
.lock()
.values()
.filter(|doc| {
matches!(doc.language.as_str(), "c" | "cpp" | "objective-c" | "objective-cpp")
&& doc.servers.iter().any(|attached| attached.server.id == server.id)
})
.map(|doc| doc.path.clone())
.collect();
let root = server.root.clone();
let Some(me) = self.me.upgrade() else { return };
let _ = tokio::task::spawn_blocking(move || {
if !is_apple_clangd(&binary) && !std::fs::canonicalize(&binary).is_ok_and(|path| is_apple_clangd(&path)) {
return;
}
if !me.shutting_down.load(std::sync::atomic::Ordering::Acquire)
&& files.iter().any(|file| has_config(&root, &me.project_root_for(file), file))
&& me.first_message("clangd", MESSAGE)
{
me.sink.emit(IdeEvent::LanguageServerWarning {
name: "clangd".into(),
message: MESSAGE.into(),
install_tool: "clangd".into(),
});
}
})
.await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn apple_paths() {
for path in [
"/usr/bin/clangd",
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clangd",
"/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clangd",
"/Library/Developer/CommandLineTools/usr/bin/clangd",
] {
assert!(is_apple_clangd(Path::new(path)), "{path}");
}
for path in [
"/Users/me/Library/Application Support/openidea/tools/clangd/bin/clangd",
"/opt/homebrew/opt/llvm/bin/clangd",
"/usr/local/bin/clangd",
"/usr/bin/clangd-custom",
"/Library/Developer/CommandLineTools-custom/usr/bin/clangd",
"/Applications/Other.app/Contents/Developer/Toolchains/LLVM.xctoolchain/usr/bin/clangd",
] {
assert!(!is_apple_clangd(Path::new(path)), "{path}");
}
}
#[test]
fn config_in_server_root_or_file_ancestors_stays_inside_project() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("project");
let server = project.join("build");
let source = project.join("src/nested");
let file = source.join("main.cpp");
std::fs::create_dir_all(&source).unwrap();
std::fs::create_dir_all(&server).unwrap();
std::fs::write(dir.path().join(".clang-tidy"), "").unwrap();
assert!(!has_config(&server, &project, &file));
for root in [&server, &source, &project.join("src"), &project] {
let config = root.join(".clang-tidy");
std::fs::write(&config, "Checks: '-*,modernize-use-nullptr'").unwrap();
assert!(has_config(&server, &project, &file), "{}", root.display());
std::fs::remove_file(config).unwrap();
}
std::fs::create_dir(source.join(".clang-tidy")).unwrap();
assert!(!has_config(&server, &project, &file));
}
}
+26 -1
Переглянути файл
@@ -43,6 +43,18 @@ pub trait Launcher: Send + Sync + 'static {
self.launch(config, root, handler, on_stderr)
}
/// Starts a server and reports its executable when the launcher runs a local process.
fn launch_resolved(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<(Peer, Option<PathBuf>), LaunchError> {
self.launch_cancellable(config, root, handler, on_stderr, cancel).map(|peer| (peer, None))
}
/// Whether `config` could start without a `Missing` error.
fn available(&self, _config: &LanguageServerConfig, _root: &Path) -> bool {
true
@@ -72,6 +84,17 @@ impl Launcher for ProcessLauncher {
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
self.launch_resolved(config, root, handler, on_stderr, cancel).map(|(peer, _)| peer)
}
fn launch_resolved(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<(Peer, Option<PathBuf>), LaunchError> {
let search = server_search_path(config);
let binary = ide_core::tool_path::find_command(&config.command, &search, root)
.and_then(|b| resolve_rustup_proxy(&config.command, b));
@@ -87,10 +110,12 @@ impl Launcher for ProcessLauncher {
handler,
on_stderr,
cancel,
);
)
.map(|peer| (peer, None));
}
let binary = binary.ok_or(LaunchError::Missing)?;
Peer::spawn(&binary.to_string_lossy(), &config.args, root, &env, handler, on_stderr)
.map(|peer| (peer, Some(binary.clone())))
.map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))
}
+13 -2
Переглянути файл
@@ -8,6 +8,7 @@
mod angular;
mod caps;
mod clang_tidy;
mod convert;
mod external_project;
mod file_ops;
@@ -472,13 +473,16 @@ impl LspManager {
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
me.launcher.launch_cancellable(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)), &cancel)
me.launcher.launch_resolved(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)), &cancel)
})
.await
.unwrap_or_else(|e| Err(LaunchError::Failed(e.to_string())));
let peer = match launched {
Ok(peer) => peer,
Ok((peer, binary)) => {
*server.resolved_binary.write() = binary;
peer
}
Err(LaunchError::Missing) => {
let cfg = server.effective_config();
let message =
@@ -587,6 +591,7 @@ impl LspManager {
}
}
}
self.check_clang_tidy(&server).await;
server.refresh_busy_status(&self.sink);
server.announce_ready(generation);
self.spawn_supervisor(server, generation, peer);
@@ -810,6 +815,12 @@ impl LspManager {
}
for s in &servers {
self.ensure_started(s);
if s.running().is_some()
&& let Some(me) = self.me.upgrade()
{
let server = s.clone();
self.runtime.spawn(async move { me.check_clang_tidy(&server).await });
}
}
}
+2
Переглянути файл
@@ -79,6 +79,7 @@ pub struct Server {
pub config: LanguageServerConfig,
/// `config` with the settings hook applied, as the current instance was launched.
effective: Mutex<Option<LanguageServerConfig>>,
pub resolved_binary: RwLock<Option<PathBuf>>,
languages: Mutex<Vec<LanguageId>>,
state: Mutex<State>,
/// Fired when the instance being started is abandoned (stop / restart while starting).
@@ -114,6 +115,7 @@ impl Server {
root,
config,
effective: Mutex::new(None),
resolved_binary: RwLock::new(None),
languages: Mutex::new(vec![language]),
state: Mutex::new(State { generation: 0, conn: Conn::Idle }),
start_cancel: Mutex::new(CancellationToken::new()),
+78
Переглянути файл
@@ -21,6 +21,7 @@ use std::time::Duration;
struct MockState {
caps: Mutex<Value>,
missing: std::sync::atomic::AtomicBool,
binary: Mutex<Option<PathBuf>>,
launches: AtomicUsize,
notifications: Mutex<Vec<(String, Value)>>,
requests: Mutex<Vec<(String, Value)>>,
@@ -148,6 +149,18 @@ impl MockLauncher {
}
impl Launcher for MockLauncher {
fn launch_resolved(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &ide_core::CancellationToken,
) -> Result<(Peer, Option<PathBuf>), LaunchError> {
self.launch_cancellable(config, root, handler, on_stderr, cancel)
.map(|peer| (peer, self.state(&config.name).binary.lock().clone()))
}
fn launch(
&self,
config: &LanguageServerConfig,
@@ -2836,3 +2849,68 @@ async fn formatting_provider_selection_tracks_dynamic_registration() {
.unwrap();
assert!(!h.mgr.can_format(doc).await.unwrap());
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn apple_clangd_warns_for_tidy_config_once_across_languages_and_restarts() {
for language in ["c", "cpp", "objective-c", "objective-cpp"] {
let h = harness_for(language, "src", &[("clangd", incremental_caps())], &[]);
*h.launcher.state("clangd").binary.lock() = Some(PathBuf::from("/usr/bin/clangd"));
std::fs::write(h.root.join(".clang-tidy"), "Checks: '-*,modernize-use-nullptr'").unwrap();
h.open("main.src", "int *p = 0;");
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::LanguageServerWarning { .. }))).await;
let id = h.mgr.servers()[0].id;
h.mgr.restart(id).await.unwrap();
h.wait_status("clangd", ServerStatus::Ready).await;
h.open("other.src", "int *p = 0;");
h.mgr.shutdown_all().await;
let events = h.events.lock();
let warnings: Vec<_> = events
.iter()
.filter_map(|e| match e {
IdeEvent::LanguageServerWarning { name, message, install_tool } => Some((name, message, install_tool)),
_ => None,
})
.collect();
assert_eq!(warnings.len(), 1, "{language}");
assert_eq!(warnings[0].0, "clangd");
assert!(warnings[0].1.contains(".clang-tidy"));
assert_eq!(warnings[0].2, "clangd");
}
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn clang_tidy_warning_requires_apple_binary_and_a_config() {
for (binary, config) in [
("/usr/bin/clangd", false),
("/opt/homebrew/opt/llvm/bin/clangd", true),
("/Users/me/Library/Application Support/openidea/tools/clangd/bin/clangd", true),
] {
let h = harness_for("cpp", "cpp", &[("clangd", incremental_caps())], &[]);
*h.launcher.state("clangd").binary.lock() = Some(PathBuf::from(binary));
if config {
std::fs::write(h.root.join(".clang-tidy"), "Checks: '-*,modernize-use-nullptr'").unwrap();
}
h.open("main.cpp", "int *p = 0;");
h.wait_status("clangd", ServerStatus::Ready).await;
h.mgr.shutdown_all().await;
assert!(!h.events.lock().iter().any(|e| matches!(e, IdeEvent::LanguageServerWarning { .. })), "{binary}");
}
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn clang_tidy_config_for_a_later_opened_file_warns_on_a_running_server() {
let h = harness_for("cpp", "cpp", &[("clangd", incremental_caps())], &[]);
*h.launcher.state("clangd").binary.lock() = Some(PathBuf::from("/usr/bin/clangd"));
h.open("main.cpp", "int *p = 0;");
h.wait_status("clangd", ServerStatus::Ready).await;
assert!(!h.events.lock().iter().any(|e| matches!(e, IdeEvent::LanguageServerWarning { .. })));
std::fs::create_dir(h.root.join("nested")).unwrap();
std::fs::write(h.root.join("nested/.clang-tidy"), "Checks: '-*,modernize-use-nullptr'").unwrap();
h.open("nested/other.cpp", "int *p = 0;");
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::LanguageServerWarning { .. }))).await;
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
+3
Переглянути файл
@@ -88,6 +88,9 @@ pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
pub fn jdtls_jdk(root: &Path, s: &Settings) -> Result<Option<crate::java::Jdk>, String> {
match jdk_setting(root, &s.languages.java.jdtls_jdk) {
None => Ok(None),
Some(Ok(jdk)) if !ide_core::java_runtime::supports_java_bundles(&jdk.home) => {
Err(crate::java::server_jdk_incomplete_message(&jdk, jdk.major.max(crate::java::JDTLS_MIN_JAVA)))
}
Some(Ok(jdk)) => Ok(Some(jdk)),
Some(Err(p)) => Err(format!(
"The language server JDK {} is not a JDK home (Settings › Languages & Frameworks › Java).",
+207 -31
Переглянути файл
@@ -16,6 +16,13 @@ pub struct Jdk {
pub home: PathBuf,
}
pub(crate) fn server_jdk_incomplete_message(jdk: &Jdk, min_java: u32) -> String {
format!(
"The language server JDK ({}) must be a full JDK with jdk.compiler, jdk.jdi and jdk.unsupported for Java language support and debugging. jdtls needs JDK {min_java} or newer. Download JDK {min_java}, choose a full JDK in {SERVER_JDK_SETTING}, or set it to Auto.",
jdk.home.display()
)
}
/// `JAVA_VERSION="21.0.3"` (or `"1.8.0_372"`) from a JDK's `release` file.
pub fn parse_release(release: &str) -> Option<u32> {
let line = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
@@ -199,7 +206,7 @@ pub const JDTLS_MIN_JAVA: u32 = 21;
/// The JDK to run jdtls with: the first found that is new enough (`JAVA_HOME` wins).
pub fn jdtls_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> {
jdks.iter().find(|j| j.major >= min_java)
jdks.iter().find(|j| j.major >= min_java && ide_core::java_runtime::supports_java_bundles(&j.home))
}
/// The Java version the jdtls that `cfg` launches needs: the highest any of its
@@ -313,8 +320,36 @@ fn text_key(text: &str) -> String {
format!("{h:016x}")
}
/// Adds `arg` as its own `--jvm-arg`, unless the user already set the property it
/// carries: a value of theirs wins, and a second call adds nothing.
fn set_jvm_property(args: &mut Vec<String>, arg: &str) {
let key = arg.split('=').next().unwrap_or(arg);
let taken = args.iter().enumerate().any(|(i, a)| {
let value =
a.strip_prefix("--jvm-arg=").or_else(|| (i > 0 && args[i - 1] == "--jvm-arg").then_some(a.as_str()));
value.is_some_and(|a| a.split('=').next() == Some(key))
});
if !taken {
args.push(format!("--jvm-arg={arg}"));
}
}
fn add_jdtls_proxy_args(args: &mut Vec<String>, proxy: &ide_core::proxy_settings::ProxySettings) {
for arg in proxy.jvm_args() {
set_jvm_property(args, &arg);
}
}
const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot";
/// JDK 25's `ZipFile` validates the ZIP64 extra field, and jars written by older tools
/// carry a size that check rejects: ECJ reports the dependency as "cannot be read or is
/// not a valid ZIP file", the project using it gets a build path error, and every project
/// depending on that one stops compiling — aspectjweaver 1.8.10 stalls a whole Maven
/// build that way, while the same jar loads fine on IDEA's JBR 21. This is how 25 is told
/// to behave the same.
const ZIP64_LENIENCY: &str = "-Djdk.util.zip.disableZip64ExtraFieldValidation=true";
/// jdtls: its Eclipse workspace (`-data`) lives under the IDE's data
/// directory, one per server root, and no Eclipse metadata is written into
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
@@ -367,6 +402,14 @@ pub fn configure_jdtls(
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
}
crate::jdtls::add_default_vm_args(&mut cfg.args);
// jdtls resolves Maven dependencies through its own HTTP client, and a JVM reads none
// of the `HTTP_PROXY` / `HTTPS_PROXY` it inherits: pass the same proxy as system
// properties. One the user set in their own JVM arguments wins.
add_jdtls_proxy_args(&mut cfg.args, &ide_core::proxy_settings::proxy());
// ECJ reads the project's jars with the server JVM's own zip reader, so a jar JDK 25
// refuses to open takes the whole Maven build with it. IDEA never notices: its JBR 21
// accepts the same file.
set_jvm_property(&mut cfg.args, ZIP64_LENIENCY);
let managed = language_server_runtimes_dir(data_dir);
let managed = dunce::canonicalize(&managed).unwrap_or(managed);
let project_jdks: Vec<_> = project_jdk
@@ -385,6 +428,9 @@ pub fn configure_jdtls(
if !cfg.env.contains_key("JAVA_HOME") {
let runtime = match server_jdk {
Some(jdk) if jdk.major < min_java => Err(server_jdk_too_old_message(jdk, min_java)),
Some(jdk) if !ide_core::java_runtime::supports_java_bundles(&jdk.home) => {
Err(server_jdk_incomplete_message(jdk, min_java))
}
Some(jdk) => Ok(jdk),
None => jdtls_runtime(jdks, min_java).ok_or_else(|| missing_runtime_message(jdks, min_java)),
};
@@ -394,6 +440,10 @@ pub fn configure_jdtls(
}
Err(e) => cfg.launch_error = Some(e),
}
} else if let Some(jdk) = cfg.env.get("JAVA_HOME").and_then(|home| jdk_at(Path::new(home)))
&& !ide_core::java_runtime::supports_java_bundles(&jdk.home)
{
cfg.launch_error = Some(server_jdk_incomplete_message(&jdk, min_java));
}
let mut runtimes = runtimes(&project_jdks);
if let Some(project) = project_jdk.or_else(|| pick_jdk(&project_jdks, project_java_version(server_root))) {
@@ -537,6 +587,19 @@ fn parse_java_version(v: &str) -> Option<u32> {
mod tests {
use super::*;
fn test_jdk(root: &Path, major: u32, name: &str) -> Jdk {
let home = root.join(name.trim_start_matches('/'));
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(
home.join("release"),
format!("JAVA_VERSION=\"{major}\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n"),
)
.unwrap();
std::fs::write(java_executable(&home), "").unwrap();
std::fs::write(home.join("bin").join(crate::exe("javac")), "").unwrap();
Jdk { major, home }
}
#[test]
fn unmanaged_source_models_have_separate_jdtls_workspaces() {
let data = tempfile::tempdir().unwrap();
@@ -563,8 +626,13 @@ mod tests {
let project_root = data.path().join("tools/jdks");
let project_home = project_root.join("temurin-21");
std::fs::create_dir_all(project_home.join("bin")).unwrap();
std::fs::write(project_home.join("release"), "JAVA_VERSION=\"21.0.1\"\n").unwrap();
std::fs::write(
project_home.join("release"),
"JAVA_VERSION=\"21.0.1\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
std::fs::write(java_executable(&project_home), "").unwrap();
std::fs::write(project_home.join("bin").join(crate::exe("javac")), "").unwrap();
let project = jdk_at(&project_home).unwrap();
let discover = || jdk_homes(&project_root).filter_map(|home| jdk_at(&home)).collect::<Vec<_>>();
let installed = discover();
@@ -572,8 +640,13 @@ mod tests {
assert!(jdtls_runtime(&runtime_candidates(&installed, data.path()), 25).is_none());
let home = language_server_runtimes_dir(data.path()).join("temurin-25");
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
std::fs::write(
home.join("release"),
"JAVA_VERSION=\"25.0.1\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
std::fs::write(java_executable(&home), "").unwrap();
std::fs::write(home.join("bin").join(crate::exe("javac")), "").unwrap();
let candidates = runtime_candidates(&installed, data.path());
assert_eq!(jdtls_runtime(&candidates, 25).unwrap().major, 25);
assert_eq!(jdtls_runtime(&candidates, 21), Some(&project));
@@ -592,11 +665,47 @@ mod tests {
);
}
#[test]
fn jdtls_rejects_jre_for_auto_explicit_and_managed_runtimes() {
let tmp = tempfile::tempdir().unwrap();
let jre = test_jdk(tmp.path(), 25, "jre");
std::fs::write(jre.home.join("release"), "JAVA_VERSION=\"25\"\nMODULES=\"java.base java.compiler\"\n").unwrap();
let jdk = test_jdk(tmp.path(), 25, "jdk");
let installed = [jre.clone(), jdk.clone()];
assert_eq!(jdtls_runtime(&installed, 25), Some(&jdk));
assert!(jdtls_runtime(std::slice::from_ref(&jre), 25).is_none());
let managed = language_server_runtimes_dir(tmp.path()).join("temurin-25");
std::fs::create_dir_all(managed.parent().unwrap()).unwrap();
std::fs::rename(&jre.home, &managed).unwrap();
assert!(jdtls_runtime(&runtime_candidates(&[], tmp.path()), 25).is_none());
let jre = jdk_at(&managed).unwrap();
for env_override in [false, true] {
let mut cfg: LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
if env_override {
cfg.env.insert("JAVA_HOME".into(), jre.home.to_string_lossy().into_owned());
}
configure_jdtls(&mut cfg, tmp.path(), tmp.path(), &installed[1..], None, Some(&jre), 25, &[], None);
let err = cfg.launch_error.unwrap();
assert!(
err.contains("full JDK with jdk.compiler, jdk.jdi and jdk.unsupported")
&& err.contains("Download JDK 25")
&& err.contains(SERVER_JDK_SETTING),
"{err}"
);
}
std::fs::write(
managed.join("release"),
"JAVA_VERSION=\"25\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
assert!(jdtls_runtime(&runtime_candidates(&[], tmp.path()), 25).is_some());
}
#[test]
fn implicit_compiler_default_matches_project_pick_with_duplicate_versions() {
let installed =
[Jdk { major: 21, home: PathBuf::from("/jdk21a") }, Jdk { major: 21, home: PathBuf::from("/jdk21b") }];
let server = Jdk { major: 25, home: PathBuf::from("/custom-server-runtime") };
let fixtures = tempfile::tempdir().unwrap();
let installed = [test_jdk(fixtures.path(), 21, "/jdk21a"), test_jdk(fixtures.path(), 21, "/jdk21b")];
let server = test_jdk(fixtures.path(), 25, "/custom-server-runtime");
let mut cfg: LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &installed, None, Some(&server), 25, &[], None);
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
@@ -606,7 +715,7 @@ mod tests {
"name": "JavaSE-21", "path": pick_jdk(&installed, None).unwrap().home, "default": true
}])
);
assert_eq!(cfg.env["JAVA_HOME"], "/custom-server-runtime");
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("custom-server-runtime").to_string_lossy());
}
#[test]
@@ -619,15 +728,16 @@ mod tests {
#[test]
fn jdtls_workspace_and_runtimes() {
let fixtures = tempfile::tempdir().unwrap();
if cfg!(windows) {
return; // Unix paths and shells
}
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
let jdks = [
Jdk { major: 25, home: PathBuf::from("/jdk25") },
Jdk { major: 21, home: PathBuf::from("/jdk21a") },
Jdk { major: 21, home: PathBuf::from("/jdk21b") },
Jdk { major: 8, home: PathBuf::from("/jdk8") },
test_jdk(fixtures.path(), 25, "/jdk25"),
test_jdk(fixtures.path(), 21, "/jdk21a"),
test_jdk(fixtures.path(), 21, "/jdk21b"),
test_jdk(fixtures.path(), 8, "/jdk8"),
];
let bundles = [PathBuf::from("/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar")];
configure_jdtls(
@@ -647,13 +757,22 @@ mod tests {
assert_eq!(cfg.args[n], "-data");
assert!(cfg.args[n + 1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[n + 1]);
assert_eq!(cfg.args[n + 2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
assert!(
cfg.args.iter().any(|a| a == "--jvm-arg=-Djdk.util.zip.disableZip64ExtraFieldValidation=true"),
"jars JDK 25 rejects must still load: {:?}",
cfg.args
);
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": "/jdk8" }));
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21a" }));
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": "/jdk25", "default": true }));
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": fixtures.path().join("jdk8") }));
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": fixtures.path().join("jdk21a") }));
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": fixtures.path().join("jdk25"), "default": true }));
assert_eq!(opts["bundles"], json!(["/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar"]));
assert_eq!(cfg.env["JAVA_HOME"], "/jdk25", "first JDK new enough to run jdtls");
assert_eq!(
cfg.env["JAVA_HOME"],
fixtures.path().join("jdk25").to_string_lossy(),
"first JDK new enough to run jdtls"
);
assert_eq!(cfg.launch_error, None);
// Deterministic (reconfigure compares configs) and idempotent.
@@ -672,7 +791,7 @@ mod tests {
assert_eq!(cfg, before);
// The project JDK is the default runtime, and runs the server when new enough.
let project = Jdk { major: 21, home: PathBuf::from("/jdk21b") };
let project = test_jdk(fixtures.path(), 21, "/jdk21b");
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
configure_jdtls(
&mut cfg,
@@ -687,8 +806,8 @@ mod tests {
);
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21b", "default": true }));
assert_eq!(cfg.env["JAVA_HOME"], "/jdk21b");
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": fixtures.path().join("jdk21b"), "default": true }));
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("jdk21b").to_string_lossy());
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
configure_jdtls(
@@ -705,6 +824,54 @@ mod tests {
assert!(other.args.is_empty() && other.initialization_options.is_none());
}
#[test]
fn jdtls_proxy_properties_respect_exact_user_overrides() {
use ide_core::proxy_settings::{ProxyMode, ProxySettings};
let proxy =
ProxySettings { mode: ProxyMode::Manual, host: "ide.proxy".into(), port: 3128, ..Default::default() };
for (user_arg, overridden) in [
("--jvm-arg=-Dhttp.proxyHost=user.proxy", true),
("--jvm-arg=-Dhttp.proxyHost", true),
("--jvm-arg=-Dhttp.proxyHostSuffix=unrelated", false),
("--jvm-arg=-Dother=-Dhttp.proxyHost", false),
("/workspace/-Dhttp.proxyHost", false),
] {
let mut forms = vec![vec![user_arg.to_owned()]];
if let Some(value) = user_arg.strip_prefix("--jvm-arg=") {
forms.push(vec!["--jvm-arg".into(), value.into()]);
}
for mut args in forms {
let user_args = args.clone();
add_jdtls_proxy_args(&mut args, &proxy);
assert_eq!(args[..user_args.len()], user_args);
assert_eq!(args.contains(&"--jvm-arg=-Dhttp.proxyHost=ide.proxy".into()), !overridden, "{user_arg}");
assert!(args.contains(&"--jvm-arg=-Dhttps.proxyHost=ide.proxy".into()));
let before = args.clone();
add_jdtls_proxy_args(&mut args, &proxy);
assert_eq!(args, before, "idempotent: {user_arg}");
}
}
}
#[test]
fn a_jar_jdk_25_rejects_loads_and_the_users_value_wins() {
// aspectjweaver 1.8.10 carries a ZIP64 extra field size 25 refuses to read; on the
// JVM that runs jdtls that is a build path error in every project using it.
let mut args = Vec::new();
set_jvm_property(&mut args, ZIP64_LENIENCY);
assert_eq!(args, ["--jvm-arg=-Djdk.util.zip.disableZip64ExtraFieldValidation=true"]);
set_jvm_property(&mut args, ZIP64_LENIENCY);
assert_eq!(args.len(), 1, "added once");
for user in [
"--jvm-arg=-Djdk.util.zip.disableZip64ExtraFieldValidation=false".to_owned(),
"--jvm-arg=-Djdk.util.zip.disableZip64ExtraFieldValidation".to_owned(),
] {
let mut own = vec![user.clone()];
set_jvm_property(&mut own, ZIP64_LENIENCY);
assert_eq!(own, [user], "the user decides");
}
}
#[test]
fn jdtls_lombok_agent() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
@@ -747,8 +914,9 @@ mod tests {
#[test]
fn jdtls_needs_a_new_enough_jdk_to_run() {
let fixtures = tempfile::tempdir().unwrap();
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
let old = [test_jdk(fixtures.path(), 17, "/jdk17"), test_jdk(fixtures.path(), 8, "/jdk8")];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
assert!(!cfg.env.contains_key("JAVA_HOME"));
@@ -767,7 +935,7 @@ mod tests {
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
let mixed = [old[0].clone(), test_jdk(fixtures.path(), 21, "/jdk21")];
assert_eq!(jdtls_runtime(&mixed, 21).unwrap().major, 21);
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
@@ -780,11 +948,12 @@ mod tests {
#[test]
fn issue_49_jdtls_needs_25_with_8_17_21_installed() {
let fixtures = tempfile::tempdir().unwrap();
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let installed = [
Jdk { major: 21, home: PathBuf::from("/jdk21") },
Jdk { major: 17, home: PathBuf::from("/jdk17") },
Jdk { major: 8, home: PathBuf::from("/jdk8") },
test_jdk(fixtures.path(), 21, "/jdk21"),
test_jdk(fixtures.path(), 17, "/jdk17"),
test_jdk(fixtures.path(), 8, "/jdk8"),
];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &installed, None, None, 25, &[], None);
@@ -793,12 +962,11 @@ mod tests {
assert!(err.contains("Download JDK 25"), "{err}");
// Once a JDK 25 has been downloaded, Auto runs jdtls on it.
let downloaded =
[installed.as_slice(), &[Jdk { major: 25, home: PathBuf::from("/tools/jdks/temurin-25") }]].concat();
let downloaded = [installed.as_slice(), &[test_jdk(fixtures.path(), 25, "/tools/jdks/temurin-25")]].concat();
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &downloaded, None, None, 25, &[], None);
assert_eq!(cfg.launch_error, None);
assert_eq!(cfg.env["JAVA_HOME"], Path::new("/tools/jdks/temurin-25").to_string_lossy());
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("tools/jdks/temurin-25").to_string_lossy());
}
#[test]
@@ -835,8 +1003,9 @@ mod tests {
#[test]
fn jdtls_runs_on_the_chosen_server_jdk() {
let fixtures = tempfile::tempdir().unwrap();
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let jdk = |major: u32, home: &str| Jdk { major, home: PathBuf::from(home) };
let jdk = |major: u32, home: &str| test_jdk(fixtures.path(), major, home);
let installed = [jdk(25, "/jdk25"), jdk(21, "/jdk21"), jdk(17, "/jdk17")];
let project = jdk(17, "/jdk17");
let run = |server: Option<&Jdk>, min_java: u32| {
@@ -857,18 +1026,25 @@ mod tests {
// Project on JDK 17, server on the chosen 21: each keeps its own JDK.
let cfg = run(Some(&jdk(21, "/jdk21")), JDTLS_MIN_JAVA);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/jdk21", None));
assert_eq!(
(cfg.env["JAVA_HOME"].clone(), cfg.launch_error),
(fixtures.path().join("jdk21").to_string_lossy().into_owned(), None)
);
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[0], json!({ "name": "JavaSE-17", "path": "/jdk17", "default": true }), "still compiles on 17");
assert_eq!(
rt[0],
json!({ "name": "JavaSE-17", "path": fixtures.path().join("jdk17"), "default": true }),
"still compiles on 17"
);
// Not set: the first installed JDK new enough, as before.
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], "/jdk25");
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], fixtures.path().join("jdk25").to_string_lossy());
// A chosen JDK outside the scanned locations.
let own = jdk(25, "/opt/own-jdk");
let cfg = run(Some(&own), 25);
assert_eq!(cfg.env["JAVA_HOME"], "/opt/own-jdk");
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("opt/own-jdk").to_string_lossy());
// Too old for this jdtls: the user's choice is not overridden, it is explained.
let cfg = run(Some(&jdk(21, "/jdk21")), 25);
+19 -1
Переглянути файл
@@ -249,6 +249,10 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) {
}),
};
let Some((java, jdk)) = jdk.filter(|(java, _)| java.is_file()) else { return };
if !ide_core::java_runtime::supports_java_bundles(&jdk.home) {
cfg.launch_error = Some(crate::java::server_jdk_incomplete_message(&jdk, crate::java::jdtls_min_java(cfg)));
return;
}
cfg.args = java_args(&install, jdk.major, &cfg.args);
cfg.command = java.to_string_lossy().into_owned();
}
@@ -465,7 +469,12 @@ mod tests {
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let jdk = dir.path().join("jdk-25");
std::fs::create_dir_all(jdk.join("bin")).unwrap();
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
std::fs::write(
jdk.join("release"),
"JAVA_VERSION=\"25.0.1\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
std::fs::write(jdk.join("bin/javac"), "").unwrap();
std::fs::write(jdk.join("bin/java"), "").unwrap();
let cfg = |command: &str| -> LanguageServerConfig {
@@ -486,6 +495,15 @@ mod tests {
assert!(direct.args[jar + 1].ends_with("org.eclipse.equinox.launcher_1.7.0.jar"));
assert_eq!(direct.args[jar + 2..], strings(&["-data", "/ws"]));
let jre = dir.path().join("jre-25");
std::fs::create_dir_all(jre.join("bin")).unwrap();
std::fs::write(jre.join("bin/java"), "").unwrap();
std::fs::write(jre.join("release"), "JAVA_VERSION=\"25\"\nIMAGE_TYPE=\"JRE\"\n").unwrap();
let mut overridden = cfg("jdtls");
overridden.args.push(format!("--java-executable={}", jre.join("bin/java").display()));
launch_directly(&mut overridden);
assert!(overridden.launch_error.unwrap().contains("jdk.jdi"));
// Someone's own wrapper, or no usable JDK: the command is kept.
std::fs::write(home.join("bin/my-jdtls"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(home.join("bin/my-jdtls"), std::os::unix::fs::PermissionsExt::from_mode(0o755))
+12 -1
Переглянути файл
@@ -166,7 +166,12 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
fn fake_jdk(dir: &Path) {
std::fs::create_dir_all(dir.join("bin")).unwrap();
std::fs::write(dir.join("bin").join(exe("java")), "").unwrap();
std::fs::write(dir.join("release"), "JAVA_VERSION=\"17.0.9\"\n").unwrap();
std::fs::write(
dir.join("release"),
"JAVA_VERSION=\"17.0.9\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
std::fs::write(dir.join("bin").join(crate::exe("javac")), "").unwrap();
}
#[test]
@@ -307,6 +312,12 @@ fn jdtls_jdk_setting() {
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
s.languages.java.jdtls_jdk = "jdk17/bin".into();
assert_eq!(jdtls_jdk(tmp.path(), &s).unwrap().map(|j| j.major), Some(17));
std::fs::write(
tmp.path().join("jdk17/release"),
"JAVA_VERSION=\"25\"\nIMAGE_TYPE=\"JRE\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
assert!(jdtls_jdk(tmp.path(), &s).unwrap_err().contains("full JDK"));
// A chosen path that is not a JDK is an error, not a silent fallback.
s.languages.java.jdtls_jdk = "missing".into();
assert!(jdtls_jdk(tmp.path(), &s).unwrap_err().contains("is not a JDK home"));
+4
Переглянути файл
@@ -178,6 +178,10 @@ impl TerminalManager {
let Some(pid) = session.info.pid else { return Ok(false) };
Ok(foreground_busy(&session, pid))
}
/// Whether a terminal session is still registered.
pub fn contains(&self, id: TerminalId) -> bool {
self.sessions.lock().contains_key(&id)
}
pub fn list(&self) -> Vec<TerminalInfo> {
let mut out: Vec<TerminalInfo> = self.sessions.lock().values().map(|s| s.info.clone()).collect();
+3 -1
Переглянути файл
@@ -21,7 +21,8 @@ pub enum ArchiveKind {
impl ArchiveKind {
pub fn from_name(name: &str) -> Self {
let n = name.to_ascii_lowercase();
if n.ends_with(".zip") || n.ends_with(".vsix") {
// JetBrains' macOS .sit distributions are zip archives.
if n.ends_with(".zip") || n.ends_with(".vsix") || n.ends_with(".sit") {
Self::Zip
} else if n.ends_with(".tar.gz") || n.ends_with(".tgz") {
Self::TarGz
@@ -393,6 +394,7 @@ mod tests {
fn kinds() {
assert_eq!(ArchiveKind::from_name("a.vsix"), ArchiveKind::Zip);
assert_eq!(ArchiveKind::from_name("a.ZIP"), ArchiveKind::Zip);
assert_eq!(ArchiveKind::from_name("kotlin-server-263.7084.0-aarch64.sit"), ArchiveKind::Zip);
assert_eq!(ArchiveKind::from_name("a.tar.gz"), ArchiveKind::TarGz);
assert_eq!(ArchiveKind::from_name("a.tgz"), ArchiveKind::TarGz);
assert_eq!(ArchiveKind::from_name("zls.tar.xz"), ArchiveKind::TarXz);
+96 -38
Переглянути файл
@@ -13,20 +13,30 @@ pub fn find_up(file: &Path, relative: &Path) -> Option<PathBuf> {
file.parent()?.ancestors().map(|dir| dir.join(relative)).find(|p| p.is_file())
}
fn package_bin(package: &Path) -> IdeResult<PathBuf> {
pub fn display_name(tool: &str) -> &str {
crate::registry::find(tool).map_or(tool, |t| t.display)
}
fn package_bin(package: &Path, tool: &str) -> IdeResult<PathBuf> {
let name = display_name(tool);
let json: serde_json::Value = serde_json::from_slice(&std::fs::read(package.join("package.json"))?)
.map_err(|e| IdeError::invalid(format!("Prettier: {e}")))?;
.map_err(|e| IdeError::invalid(format!("{name}: {e}")))?;
let bin = json["bin"]
.as_str()
.or_else(|| json["bin"]["prettier"].as_str())
.ok_or_else(|| IdeError::invalid("Prettier: package has no CLI entry point"))?;
.or_else(|| json["bin"][tool].as_str())
.ok_or_else(|| IdeError::invalid(format!("{name}: package has no CLI entry point")))?;
let path = package.join(bin);
if !path.is_file() {
return Err(IdeError::unavailable(format!("Prettier: CLI does not exist: {}", path.display())));
return Err(IdeError::unavailable(format!("{name}: CLI does not exist: {}", path.display())));
}
Ok(path)
}
/// Prettier formats a range for some languages (`config.range`); oxfmt formats whole files only.
pub fn supports_range(tool: &str, config: &FormatterConfig) -> bool {
tool == "prettier" && config.range
}
impl Tools {
/// Explicit executable/script, then the nearest project package, then managed tools and PATH.
pub fn formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
@@ -34,22 +44,26 @@ impl Tools {
}
fn resolve_formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
if tool != "prettier" {
if crate::registry::find(tool).is_none_or(|t| t.kind != crate::ToolKind::Formatter) {
return Err(IdeError::unavailable(format!("Unknown external formatter: {tool}")));
}
let package = Path::new("node_modules").join(tool);
let manifest = package.join("package.json");
let (path, node) = if let Some(custom) = custom.filter(|p| p.is_dir()) {
(package_bin(custom)?, true)
(package_bin(custom, tool)?, true)
} else if let Some(custom) = custom {
(custom.to_path_buf(), matches!(custom.extension().and_then(|s| s.to_str()), Some("js" | "cjs" | "mjs")))
} else if let Some(manifest) = find_up(file, Path::new("node_modules/prettier/package.json")) {
(package_bin(manifest.parent().unwrap())?, true)
} else if self.root.join("node_modules/prettier/package.json").is_file() {
(package_bin(&self.root.join("node_modules/prettier"))?, true)
} else if let Some(manifest) = find_up(file, &manifest) {
(package_bin(manifest.parent().unwrap(), tool)?, true)
} else if self.root.join(&manifest).is_file() {
(package_bin(&self.root.join(&package), tool)?, true)
} else {
(self.which("prettier").ok_or_else(|| IdeError::missing_tool("prettier"))?, false)
(self.which(tool).ok_or_else(|| IdeError::missing_tool(tool))?, false)
};
if node {
let node = self.which("node").ok_or_else(|| IdeError::unavailable("Prettier: Node.js is required"))?;
let name = display_name(tool);
let node =
self.which("node").ok_or_else(|| IdeError::unavailable(format!("{name}: Node.js is required")))?;
let mut cmd = self.command(node);
cmd.arg(path);
Ok(cmd)
@@ -59,34 +73,40 @@ impl Tools {
}
}
/// Project configuration overrides these defaults; Prettier resolves config and plugins itself.
/// Both tools resolve their configuration and plugins themselves. Prettier's
/// project configuration overrides the editor indentation passed here; oxfmt has
/// no such flags and reads its configuration and `.editorconfig` only.
pub fn arguments(
tool: &str,
config: &FormatterConfig,
file: &Path,
tab_size: u32,
insert_spaces: bool,
range: Option<(u32, u32)>,
) -> Vec<OsString> {
let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") {
"mdx"
} else {
&config.parser
};
let mut args: Vec<OsString> = [
"--parser",
parser,
"--config-precedence",
"file-override",
"--tab-width",
&tab_size.max(1).to_string(),
"--use-tabs",
if insert_spaces { "false" } else { "true" },
]
.into_iter()
.map(Into::into)
.collect();
let mut args: Vec<OsString> = Vec::new();
if tool == "prettier" {
let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") {
"mdx"
} else {
&config.parser
};
args.extend(
[
"--parser",
parser,
"--config-precedence",
"file-override",
"--tab-width",
&tab_size.max(1).to_string(),
"--use-tabs",
if insert_spaces { "false" } else { "true" },
]
.map(OsString::from),
);
}
args.extend(["--stdin-filepath".into(), file.as_os_str().to_owned()]);
if config.range
if supports_range(tool, config)
&& let Some((start, end)) = range
{
args.extend(["--range-start".into(), start.to_string().into(), "--range-end".into(), end.to_string().into()]);
@@ -100,8 +120,8 @@ pub fn arguments(
args
}
pub fn run(mut command: Command, text: &str, cancel: &CancellationToken) -> IdeResult<String> {
crate::process::run_input(&mut command, text, Duration::from_secs(15), cancel).map_err(|e| e.with_tool("prettier"))
pub fn run(tool: &str, mut command: Command, text: &str, cancel: &CancellationToken) -> IdeResult<String> {
crate::process::run_input(&mut command, text, Duration::from_secs(15), cancel).map_err(|e| e.with_tool(tool))
}
#[cfg(test)]
@@ -118,7 +138,7 @@ mod tests {
assert_eq!(missing.kind, ErrorKind::NotFound);
assert_eq!(missing.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: true }));
let custom = tools.formatter_command("prettier", &file, Some(&dir.path().join("absent-prettier"))).unwrap();
let failure = run(custom, "text", &Default::default()).unwrap_err();
let failure = run("prettier", custom, "text", &Default::default()).unwrap_err();
assert_eq!(failure.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: false }));
}
@@ -127,7 +147,7 @@ mod tests {
fn stderr_is_preserved_verbatim_even_when_longer_than_four_thousand_characters() {
let mut command = Command::new("sh");
command.args(["-c", "i=0; while [ $i -lt 1000 ]; do printf 'error\\n' >&2; i=$((i+1)); done; exit 1"]);
let failure = run(command, "", &Default::default()).unwrap_err();
let failure = run("prettier", command, "", &Default::default()).unwrap_err();
assert_eq!(failure.message, "error\n".repeat(1000));
assert_eq!(failure.data, Some(ide_core::error::ErrorData::Tool { tool: "prettier".into(), missing: false }));
}
@@ -161,7 +181,8 @@ mod tests {
("vue", true),
] {
let config = FormatterConfig { tool: "prettier".into(), parser: parser.into(), range: supports_range };
let args = arguments(&config, Path::new("/project with spaces/file.md"), 4, false, Some((3, 9)));
let args =
arguments("prettier", &config, Path::new("/project with spaces/file.md"), 4, false, Some((3, 9)));
let args: Vec<_> = args.iter().map(|a| a.to_string_lossy()).collect();
assert!(args.windows(2).any(|a| a == ["--config-precedence", "file-override"]));
assert!(args.windows(2).any(|a| a == ["--stdin-filepath", "/project with spaces/file.md"]));
@@ -171,4 +192,41 @@ mod tests {
assert!(!args.contains(&"--write".into()));
}
}
#[test]
fn oxfmt_runs_the_nearest_package_without_prettier_flags() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("node_modules/oxfmt/bin")).unwrap();
std::fs::write(root.join("node_modules/oxfmt/package.json"), r#"{"bin":{"oxfmt":"bin/oxfmt"}}"#).unwrap();
std::fs::write(root.join("node_modules/oxfmt/bin/oxfmt"), "").unwrap();
std::fs::write(root.join(".prettierignore"), "dist").unwrap();
let file = root.join("packages/web/src/app.ts");
let path = std::env::var_os("PATH").unwrap_or_default();
let tools = Tools::with_paths(root.join("tools"), path, crate::platform::Platform::current());
let command = tools.formatter_command("oxfmt", &file, None).unwrap();
let program = Path::new(command.get_program()).file_stem().unwrap().to_string_lossy().into_owned();
assert_eq!(program, "node");
let script: Vec<_> = command.get_args().collect();
// Compare components: `package_bin` joins the manifest's `bin` entry
// (`bin/oxfmt`) onto a platform path, so separators differ on Windows.
assert_eq!(
Path::new(&script[0]).components().collect::<Vec<_>>(),
root.join("node_modules/oxfmt/bin/oxfmt").components().collect::<Vec<_>>()
);
let config = FormatterConfig { tool: "prettier".into(), parser: "typescript".into(), range: true };
let args = arguments("oxfmt", &config, &file, 4, false, Some((3, 9)));
let ignore = root.join(".prettierignore").into_os_string();
assert_eq!(
args[..4],
["--stdin-filepath".into(), file.clone().into_os_string(), "--ignore-path".into(), ignore]
);
assert!(args[4..].chunks(2).all(|pair| pair[0] == "--ignore-path"), "{args:?}");
assert!(!supports_range("oxfmt", &config));
let unknown = tools.formatter_command("rust-analyzer", &file, None).unwrap_err();
assert!(unknown.message.contains("Unknown external formatter"), "{}", unknown.message);
}
}
+57 -49
Переглянути файл
@@ -108,26 +108,7 @@ fn adoptium_arch(arch: Arch) -> &'static str {
/// The latest Temurin JDK build of Java `feature` for `platform`.
pub fn adoptium_assets_url(feature: u32, platform: Platform) -> String {
assets_url(feature, platform, ImageType::Jdk)
}
#[derive(Clone, Copy)]
enum ImageType {
Jdk,
Jre,
}
impl ImageType {
fn name(self) -> &'static str {
match self {
Self::Jdk => "jdk",
Self::Jre => "jre",
}
}
}
fn assets_url(feature: u32, platform: Platform, image: ImageType) -> String {
let image = image.name();
let image = "jdk";
format!(
"{ADOPTIUM_API}/assets/latest/{feature}/hotspot?architecture={}&image_type={image}&os={}&vendor=eclipse",
adoptium_arch(platform.arch),
@@ -190,16 +171,12 @@ impl AssetVersion {
/// The JDK archive (`.tar.gz` on macOS / Linux, `.zip` on Windows) in an Adoptium
/// `assets/latest` response; `None` when there is no build for the platform.
pub fn adoptium_pick(json: &str, platform: Platform) -> IdeResult<Option<(Download, u32)>> {
pick_image(json, platform, ImageType::Jdk)
}
fn pick_image(json: &str, platform: Platform, image: ImageType) -> IdeResult<Option<(Download, u32)>> {
let assets: Vec<Asset> =
serde_json::from_str(json).map_err(|e| proto(format!("unexpected Adoptium response: {e}")))?;
let ext = if platform.os == Os::Windows { ".zip" } else { ".tar.gz" };
let os = adoptium_os(platform.os);
let found = assets.into_iter().find(|a| {
a.binary.image_type.as_deref().is_none_or(|t| t == image.name())
a.binary.image_type.as_deref().is_none_or(|t| t == "jdk")
&& a.binary.heap_size.as_deref().is_none_or(|h| h == "normal")
&& a.binary.os.as_deref().is_none_or(|o| o == os)
&& a.binary.package.name.ends_with(ext)
@@ -249,6 +226,10 @@ pub fn find_jdk_home(dir: &Path, platform: Platform) -> Option<PathBuf> {
subdirs.iter().flat_map(|d| candidates(d)).find(|h| is_jdk_home(h, platform))
}
fn usable_java_home(dir: &Path, platform: Platform, runtime: bool) -> Option<PathBuf> {
find_jdk_home(dir, platform).filter(|home| !runtime || ide_core::java_runtime::supports_java_bundles(home))
}
/// The directory to move into place: the archive's single top-level folder
/// holding the JDK, else everything that was unpacked.
fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
@@ -283,8 +264,8 @@ impl Tools {
self.download_java(vendor, feature, location, false, cancel, emit)
}
/// Downloads a runtime for a language server, preferring a JRE. Only a
/// platform without a JRE build falls back to a full JDK.
/// Downloads a full JDK for a language server and its bundles (java-debug
/// needs `jdk.jdi`). Kept outside project JDK discovery roots.
pub fn download_java_runtime(
&self,
feature: u32,
@@ -310,19 +291,8 @@ impl Tools {
let http = self.http()?;
let location = location.map(Path::to_path_buf).unwrap_or_else(|| self.root.join("jdks"));
emit(InstallEvent::Line { text: format!("Resolving the latest Eclipse Temurin {feature}…") });
let mut picked = if runtime {
pick_image(
&http.get_text_or_empty_on_404(&assets_url(feature, self.platform, ImageType::Jre), cancel)?,
self.platform,
ImageType::Jre,
)?
} else {
None
};
if picked.is_none() {
picked =
adoptium_pick(&http.get_text(&adoptium_assets_url(feature, self.platform), cancel)?, self.platform)?;
}
let mut picked =
adoptium_pick(&http.get_text(&adoptium_assets_url(feature, self.platform), cancel)?, self.platform)?;
if picked.is_none() && matches!(self.platform.os, Os::Mac | Os::Windows) && self.platform.arch == Arch::Arm64 {
// Older JDKs may need the OS-provided x64 emulation.
let intel = Platform { os: self.platform.os, arch: Arch::X64 };
@@ -336,7 +306,7 @@ impl Tools {
})?;
let target = location.join(jdk_dir_name(vendor, &dl.version));
let done = |home: PathBuf| DownloadedJdk { home: home.into(), version: dl.version.clone(), major };
if let Some(home) = find_jdk_home(&target, self.platform) {
if let Some(home) = usable_java_home(&target, self.platform, runtime) {
emit(InstallEvent::Line { text: format!("{} is already installed", target.display()) });
return Ok(done(home));
}
@@ -351,7 +321,7 @@ impl Tools {
emit(InstallEvent::Line { text: "Extracting…".into() });
let pkg = staging.join("pkg");
archive::extract(&archive, archive::ArchiveKind::from_name(&dl.name), &pkg, "java", cancel)?;
let home = find_jdk_home(&pkg, self.platform)
let home = usable_java_home(&pkg, self.platform, runtime)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("no JDK found in {}", dl.name)))?;
// Last point to stop: from here the JDK replaces what is at `target`.
if cancel.is_cancelled() {
@@ -362,7 +332,7 @@ impl Tools {
}
std::fs::rename(unpacked_root(&pkg, &home), &target)?;
clear_quarantine(&target);
find_jdk_home(&target, self.platform)
usable_java_home(&target, self.platform, runtime)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("no JDK found in {}", target.display())))
})();
let _ = std::fs::remove_dir_all(&staging);
@@ -437,18 +407,56 @@ mod tests {
}
#[test]
fn runtime_assets_use_jre_without_changing_jdk_downloads() {
fn runtime_assets_require_jdk_images() {
for platform in [MAC_ARM, LINUX_X64, WIN_X64] {
assert!(assets_url(25, platform, ImageType::Jre).contains("image_type=jre"));
assert!(adoptium_assets_url(25, platform).contains("image_type=jdk"));
let ext = if platform.os == Os::Windows { "zip" } else { "tar.gz" };
let jdk = asset(&format!("java.{ext}"), adoptium_os(platform.os), "normal", "");
let jre = jdk.replace("\"image_type\":\"jdk\"", "\"image_type\":\"jre\"");
assert!(pick_image(&format!("[{jre}]"), platform, ImageType::Jre).unwrap().is_some());
assert!(adoptium_pick(&format!("[{jre},{jdk}]"), platform).unwrap().is_some());
assert!(adoptium_pick(&format!("[{jre}]"), platform).unwrap().is_none());
assert!(pick_image(&format!("[{jdk}]"), platform, ImageType::Jre).unwrap().is_none());
assert!(pick_image("[]", platform, ImageType::Jre).unwrap().is_none());
assert!(pick_image("offline", platform, ImageType::Jre).is_err());
}
}
#[test]
fn stale_runtime_is_replaced_even_at_the_same_version() {
for platform in [MAC_ARM, LINUX_X64, WIN_X64] {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join(jdk_dir_name(TEMURIN, "25.0.1"));
let home = if platform.os == Os::Mac { target.join("Contents/Home") } else { target.clone() };
fake_jdk(&home, platform);
let javac = home.join("bin").join(if cfg!(windows) { "javac.exe" } else { "javac" });
std::fs::write(&javac, "").unwrap();
for modules in [None, Some("java.base java.compiler jdk.jdix"), Some("java.base jdk.jdi.agent")] {
let line = modules.map(|m| format!("MODULES=\"{m}\"\n")).unwrap_or_default();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"25.0.1\"\n{line}")).unwrap();
assert!(usable_java_home(&target, platform, true).is_none(), "{modules:?}");
assert_eq!(usable_java_home(&target, platform, false), Some(home.clone()));
}
std::fs::write(
home.join("release"),
"JAVA_VERSION=\"25.0.1\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
assert_eq!(usable_java_home(&target, platform, true), Some(home.clone()));
std::fs::write(home.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
std::fs::create_dir_all(home.join("jmods")).unwrap();
for module in ["jdk.compiler", "jdk.jdi", "jdk.unsupported"] {
std::fs::write(home.join("jmods").join(format!("{module}.jmod")), "").unwrap();
}
assert_eq!(usable_java_home(&target, platform, true), Some(home.clone()));
std::fs::write(
home.join("release"),
"IMAGE_TYPE=\"JRE\"\nMODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n",
)
.unwrap();
assert!(usable_java_home(&target, platform, true).is_none(), "Temurin JRE release can list absent modules");
std::fs::write(home.join("release"), "MODULES=\"java.base jdk.compiler jdk.jdi jdk.unsupported\"\n")
.unwrap();
std::fs::remove_file(javac).unwrap();
assert!(usable_java_home(&target, platform, true).is_none(), "custom runtime without compiler");
std::fs::write(home.join("release"), "MODULES=\"java.base\"\n").unwrap();
assert!(usable_java_home(&target, platform, true).is_none(), "release describes the runtime image");
}
}
+85 -10
Переглянути файл
@@ -134,6 +134,28 @@ pub static TOOLS: &[ToolSpec] = &[
needs: NODE,
homepage: "https://prettier.io",
},
ToolSpec {
name: "oxfmt",
display: "oxfmt",
kind: Formatter,
commands: &["oxfmt"],
method: Method::Npm { packages: &["oxfmt"] },
fallback: None,
version: ver("oxfmt"),
needs: NODE,
homepage: "https://oxc.rs/docs/guide/usage/formatter",
},
ToolSpec {
name: "oxlint",
display: "oxlint",
kind: LanguageServer,
commands: &["oxlint"],
method: Method::Npm { packages: &["oxlint"] },
fallback: None,
version: ver("oxlint"),
needs: NODE,
homepage: "https://oxc.rs/docs/guide/usage/linter",
},
ToolSpec {
name: "rust-analyzer",
display: "rust-analyzer",
@@ -614,15 +636,25 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Kotlin/kotlin-lsp" },
assets: &[
// Current releases (kotlin-server-*): the CLI distribution is a
// .sit on macOS, .tar.gz on Linux and .win.zip on Windows. x64 ships as the
// un-suffixed archive, aarch64 as `-aarch64`; the un-suffixed one
// comes first in the release notes, which is what the x64 pattern
// matches first. Without a matching rule the installer used to fall
// through to a loose `kotlin-*.zip` pattern and POSIX picked the
// Windows archive (#723).
rule(Mac, Arm64, "kotlin-server-*-aarch64.sit"),
rule(Mac, X64, "kotlin-server-*.sit"),
rule(Linux, Arm64, "kotlin-server-*-aarch64.tar.gz"),
rule(Linux, X64, "kotlin-server-*.tar.gz"),
rule(Windows, X64, "kotlin-server-*.win.zip"),
rule(Windows, Arm64, "kotlin-server-*-aarch64.win.zip"),
// Old releases named the archives kotlin-lsp-*.
rule(Mac, Arm64, "kotlin-lsp-*-mac-aarch64.zip"),
rule(Mac, X64, "kotlin-lsp-*-mac-x64.zip"),
rule(Linux, X64, "kotlin-lsp-*-linux-x64.zip"),
rule(Linux, Arm64, "kotlin-lsp-*-linux-aarch64.zip"),
rule(Windows, X64, "kotlin-lsp-*-win-x64.zip"),
// Older releases ship one platform-independent archive.
any_arch(Mac, "kotlin-*.zip"),
any_arch(Linux, "kotlin-*.zip"),
any_arch(Windows, "kotlin-*.zip"),
],
locate: &["kotlin-lsp", "kotlin-lsp.sh", "kotlin-lsp.cmd"],
},
@@ -955,12 +987,8 @@ mod tests {
known.insert((d.adapter.clone(), d.command.clone()));
}
}
for l in &langs {
if let Some(f) = &l.formatter {
known.insert((f.tool.clone(), f.tool.clone()));
}
}
for t in TOOLS.iter().filter(|t| t.kind != Plugin) {
// The host selects the formatter of each file (Prettier or oxfmt).
for t in TOOLS.iter().filter(|t| !matches!(t.kind, Plugin | Formatter)) {
assert!(
known.contains(&(t.name.to_string(), t.commands[0].to_string())),
"{} / {} is not referenced by languages/*.toml",
@@ -988,4 +1016,51 @@ mod tests {
}
}
}
/// The v263 kotlin-server-* release notes: the CLI distribution archives plus
/// the VS Code extension and checksums; each platform must pick its native
/// distribution and the aarch64 archive must never be picked on x64.
#[test]
fn kotlin_lsp_picks_the_native_archive_for_each_platform() {
use crate::platform::{Platform, select_asset};
let names = [
"kotlin-server-0.0.27-mac-amd64.vsix",
"kotlin-server-0.0.27-mac-amd64.vsix.sha256",
"kotlin-server-0.0.27-mac-aarch64.vsix",
"kotlin-server-0.0.27-mac-aarch64.vsix.sha256",
"kotlin-server-0.0.27-linux-amd64.vsix",
"kotlin-server-0.0.27-linux-amd64.vsix.sha256",
"kotlin-server-0.0.27-linux-aarch64.vsix",
"kotlin-server-0.0.27-linux-aarch64.vsix.sha256",
"kotlin-server-0.0.27-win-amd64.vsix",
"kotlin-server-0.0.27-win-amd64.vsix.sha256",
"kotlin-server-0.0.27-win-aarch64.vsix",
"kotlin-server-0.0.27-win-aarch64.vsix.sha256",
"kotlin-server-263.7084.0.sit",
"kotlin-server-263.7084.0.sit.sha256",
"kotlin-server-263.7084.0-aarch64.sit",
"kotlin-server-263.7084.0-aarch64.sit.sha256",
"kotlin-server-263.7084.0.tar.gz",
"kotlin-server-263.7084.0.tar.gz.sha256",
"kotlin-server-263.7084.0-aarch64.tar.gz",
"kotlin-server-263.7084.0-aarch64.tar.gz.sha256",
"kotlin-server-263.7084.0.win.zip",
"kotlin-server-263.7084.0.win.zip.sha256",
"kotlin-server-263.7084.0-aarch64.win.zip",
"kotlin-server-263.7084.0-aarch64.win.zip.sha256",
];
let rules = find("kotlin-lsp").unwrap().asset_rules();
let mac_arm = Platform { os: Mac, arch: Arm64 };
assert_eq!(select_asset(&names, rules, mac_arm), Some("kotlin-server-263.7084.0-aarch64.sit"));
let mac_x64 = Platform { os: Mac, arch: X64 };
assert_eq!(select_asset(&names, rules, mac_x64), Some("kotlin-server-263.7084.0.sit"));
let linux_x64 = Platform { os: Linux, arch: X64 };
assert_eq!(select_asset(&names, rules, linux_x64), Some("kotlin-server-263.7084.0.tar.gz"));
let linux_arm = Platform { os: Linux, arch: Arm64 };
assert_eq!(select_asset(&names, rules, linux_arm), Some("kotlin-server-263.7084.0-aarch64.tar.gz"));
let win_x64 = Platform { os: Windows, arch: X64 };
assert_eq!(select_asset(&names, rules, win_x64), Some("kotlin-server-263.7084.0.win.zip"));
let win_arm = Platform { os: Windows, arch: Arm64 };
assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip"));
}
}
+2 -2
Переглянути файл
@@ -19,8 +19,8 @@ fn format(
};
let mut cmd = tools.formatter_command("prettier", path, None)?;
cmd.current_dir(path.parent().unwrap());
cmd.args(formatter::arguments(&config, path, 4, true, range));
formatter::run(cmd, text, &CancellationToken::new())
cmd.args(formatter::arguments("prettier", &config, path, 4, true, range));
formatter::run("prettier", cmd, text, &CancellationToken::new())
}
#[test]
+22 -9
Переглянути файл
@@ -89,15 +89,28 @@ pub(crate) fn blame(
return Ok(uncommitted_lines(line_count));
}
// Restricted blame reads committed blobs only. Feeding working-tree bytes to
// Git's --contents path would run configured clean filters.
let out = if crate::execution_allowed() {
run(
r.root(),
&["--literal-pathspecs", "blame", "--porcelain", "--contents", "-", revision, "--", &rel],
Some(&contents),
)?
// Git's --contents path would run configured clean filters, so it blames the
// revision plain. Git learned to combine `--contents` with a revision in 2.41;
// older releases reject the pair (`fatal: cannot use --contents with final
// commit object name`) and take the same plain path — the edited lines are
// marked uncommitted below either way (issue #755).
let contents_args = ["--literal-pathspecs", "blame", "--porcelain", "--contents", "-", revision, "--", &rel];
let plain_args: &[&str] = if crate::execution_allowed() {
&["--literal-pathspecs", "blame", "--porcelain", revision, "--", &rel]
} else {
run(r.root(), &["--literal-pathspecs", "blame", "--no-textconv", "--porcelain", revision, "--", &rel], None)?
&["--literal-pathspecs", "blame", "--no-textconv", "--porcelain", revision, "--", &rel]
};
let (out, contents_blame) = if crate::execution_allowed() {
let out = cli::run_raw(r.root(), &contents_args, Some(&contents))?;
if out.code == Some(0) {
(out, true)
} else if String::from_utf8_lossy(&out.stderr).contains("cannot use --contents") {
(run(r.root(), plain_args, None)?, false)
} else {
return Err(cli::failure(&contents_args, &out.stderr, &out.stdout, out.code));
}
} else {
(run(r.root(), plain_args, None)?, false)
};
let mut lines = crate::blame::parse_porcelain(&out.stdout_str());
for line in &mut lines {
@@ -106,7 +119,7 @@ pub(crate) fn blame(
line.summary = String::new();
}
}
if !crate::execution_allowed() {
if !contents_blame {
let base = r.file_at(path, Some(revision), encoding)?.unwrap_or_default();
for hunk in crate::diff::line_hunks(&base, &text).into_iter().rev() {
let start = (hunk.old_start as usize).min(lines.len());
+69
Переглянути файл
@@ -2,6 +2,29 @@
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
/// Platform adapters supply the system's tab preference and active project state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabbingPreference {
Always,
InFullScreen,
Manually,
}
pub fn should_group_new_project(
preference: TabbingPreference,
fullscreen: bool,
active_project: bool,
light_edit: bool,
) -> bool {
active_project
&& !light_edit
&& match preference {
TabbingPreference::Always => true,
TabbingPreference::InFullScreen => fullscreen,
TabbingPreference::Manually => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WindowGroup {
pub members: Vec<String>,
@@ -39,6 +62,13 @@ impl WindowGroups {
Ok(())
}
/// Adds a window to the anchor's group without merging unrelated groups.
pub fn join(&mut self, anchor: &str, member: &str) -> IdeResult<()> {
let mut members = self.group(anchor).map(|g| g.members.clone()).unwrap_or_else(|| vec![anchor.to_owned()]);
members.push(member.to_owned());
self.merge(members, anchor)
}
pub fn select(&mut self, caller: &str, target: &str) -> IdeResult<WindowGroup> {
let group = self
.groups
@@ -94,6 +124,45 @@ mod tests {
values.iter().map(|s| (*s).into()).collect()
}
#[test]
fn new_project_grouping_follows_system_preference_and_excludes_light_edit() {
for preference in [TabbingPreference::Always, TabbingPreference::InFullScreen, TabbingPreference::Manually] {
for fullscreen in [false, true] {
for active_project in [false, true] {
for light_edit in [false, true] {
let expected = matches!(
(preference, fullscreen, active_project, light_edit),
(TabbingPreference::Always, _, true, false)
| (TabbingPreference::InFullScreen, true, true, false)
);
assert_eq!(
should_group_new_project(preference, fullscreen, active_project, light_edit),
expected,
"{preference:?}, fullscreen={fullscreen}, active={active_project}, light={light_edit}"
);
}
}
}
}
}
#[test]
fn joining_new_windows_preserves_the_active_group_and_other_groups() {
let mut groups = WindowGroups::default();
groups.merge(members(&["other-a", "other-b"]), "other-b").unwrap();
groups.join("a", "b").unwrap();
assert_eq!(groups.group("a").unwrap().members, members(&["a", "b"]));
let before = groups.select("a", "b").unwrap();
assert_eq!(before.selected, "a");
groups.join("b", "c").unwrap();
let before = groups.select("b", "c").unwrap();
assert_eq!(before.selected, "b");
assert_eq!(groups.group("c").unwrap().members, members(&["a", "b", "c"]));
assert_eq!(groups.group("c").unwrap().selected, "c");
assert_eq!(groups.group("other-a").unwrap().members, members(&["other-a", "other-b"]));
assert_eq!(groups.group("other-a").unwrap().selected, "other-b");
}
#[test]
fn selecting_and_detaching_preserve_the_other_sessions() {
let mut groups = WindowGroups::default();
+6
Переглянути файл
@@ -0,0 +1,6 @@
id = "asciidoc"
name = "AsciiDoc"
extensions = ["adoc", "asciidoc"]
line-comment = "//"
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "AsciiDoc"
+13
Переглянути файл
@@ -0,0 +1,13 @@
id = "d"
name = "D"
extensions = ["d", "di"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 4, insert-spaces = true }
ui-mode = "D"
[[language-servers]]
name = "serve-d"
command = "serve-d"
root-markers = ["dub.json", "dub.sdl", "dub.selections.json"]
install-hint = "Install serve-d (https://github.com/symmetryinvestments/serve-d) and expose it as `serve-d`"
+8
Переглянути файл
@@ -27,6 +27,14 @@ args = ["--stdio"]
root-markers = ["jsconfig.json", "tsconfig.json", "package.json"]
install-hint = "npm i -g typescript@6 typescript-language-server"
[[language-servers]]
name = "oxlint"
command = "oxlint"
args = ["--lsp"]
root-markers = [".oxlintrc.json", ".oxlintrc.jsonc", "oxlint.config.ts", "oxlint.config.mts"]
require-root-marker = true
install-hint = "npm i -D oxlint"
[debugger]
adapter = "js-debug"
command = "js-debug-adapter"
+8
Переглянути файл
@@ -26,6 +26,14 @@ args = ["--stdio"]
root-markers = ["jsconfig.json", "tsconfig.json", "package.json"]
install-hint = "npm i -g typescript@6 typescript-language-server"
[[language-servers]]
name = "oxlint"
command = "oxlint"
args = ["--lsp"]
root-markers = [".oxlintrc.json", ".oxlintrc.jsonc", "oxlint.config.ts", "oxlint.config.mts"]
require-root-marker = true
install-hint = "npm i -D oxlint"
[debugger]
adapter = "js-debug"
command = "js-debug-adapter"
+8
Переглянути файл
@@ -13,3 +13,11 @@ command = "svelteserver"
args = ["--stdio"]
root-markers = ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts", "package.json"]
install-hint = "npm i -g svelte-language-server"
[[language-servers]]
name = "oxlint"
command = "oxlint"
args = ["--lsp"]
root-markers = [".oxlintrc.json", ".oxlintrc.jsonc", "oxlint.config.ts", "oxlint.config.mts"]
require-root-marker = true
install-hint = "npm i -D oxlint"
+8
Переглянути файл
@@ -37,6 +37,14 @@ root-markers = ["angular.json", "node_modules/@angular/core"]
require-root-marker = true
install-hint = "npm i -g @angular/language-server"
[[language-servers]]
name = "oxlint"
command = "oxlint"
args = ["--lsp"]
root-markers = [".oxlintrc.json", ".oxlintrc.jsonc", "oxlint.config.ts", "oxlint.config.mts"]
require-root-marker = true
install-hint = "npm i -D oxlint"
[debugger]
adapter = "js-debug"
command = "js-debug-adapter"
+8
Переглянути файл
@@ -26,6 +26,14 @@ args = ["--stdio"]
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
install-hint = "npm i -g typescript@6 typescript-language-server"
[[language-servers]]
name = "oxlint"
command = "oxlint"
args = ["--lsp"]
root-markers = [".oxlintrc.json", ".oxlintrc.jsonc", "oxlint.config.ts", "oxlint.config.mts"]
require-root-marker = true
install-hint = "npm i -D oxlint"
[debugger]
adapter = "js-debug"
command = "js-debug-adapter"
+8
Переглянути файл
@@ -22,3 +22,11 @@ command = "vtsls"
args = ["--stdio"]
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
install-hint = "npm i -g @vtsls/language-server"
[[language-servers]]
name = "oxlint"
command = "oxlint"
args = ["--lsp"]
root-markers = [".oxlintrc.json", ".oxlintrc.jsonc", "oxlint.config.ts", "oxlint.config.mts"]
require-root-marker = true
install-hint = "npm i -D oxlint"
+1
Переглянути файл
@@ -298,6 +298,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_changelists_save,
vcs::vcs_write_patch,
term::term_spawn,
term::term_store_image,
term::term_write,
term::term_resize,
term::term_kill,
+11
Переглянути файл
@@ -24,6 +24,17 @@ pub async fn term_spawn(
)
}
#[tauri::command]
#[specta::specta]
pub async fn term_store_image(
state: State<'_, AppState>,
id: TerminalId,
data: Vec<u8>,
mime: String,
) -> IdeResult<String> {
ide_host::ops::term::store_image(&state.host, id, data, mime).await
}
#[tauri::command]
#[specta::specta]
pub fn term_write(state: State<'_, AppState>, id: TerminalId, data: String) -> IdeResult<()> {
+6 -1
Переглянути файл
@@ -11,6 +11,8 @@ mod events;
#[cfg(any(target_os = "linux", test))]
mod linux_window_state;
mod logging;
#[cfg(target_os = "macos")]
mod macos;
mod menu;
mod remote_dev;
@@ -172,7 +174,10 @@ pub fn run() {
tauri::WindowEvent::Focused(false) => application_focus::changed(window.app_handle(), false),
tauri::WindowEvent::Destroyed => {
#[cfg(target_os = "macos")]
titlebar::forget(window);
{
titlebar::forget(window);
macos::forget_fullscreen(window.label());
}
window_groups::destroyed(window.app_handle(), window.label());
if let Some(settings) = window.app_handle().get_webview_window(&windows::settings_label(window.label())) {
let _ = settings.destroy();
+98
Переглянути файл
@@ -0,0 +1,98 @@
//! macOS window tab preferences, applied to application-drawn project tabs.
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
use objc2::{MainThreadMarker, rc::Retained, runtime::ProtocolObject};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
use tauri::{AppHandle, Manager, WebviewWindow};
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
fn read(mtm: MainThreadMarker) -> TabbingPreference {
match NSWindow::userTabbingPreference(mtm) {
NSWindowUserTabbingPreference::Always => TabbingPreference::Always,
NSWindowUserTabbingPreference::InFullScreen => TabbingPreference::InFullScreen,
_ => TabbingPreference::Manually,
}
}
if let Some(mtm) = MainThreadMarker::new() {
return Ok(read(mtm));
}
let (tx, rx) = std::sync::mpsc::sync_channel(1);
app.run_on_main_thread(move || {
let _ = tx.send(read(MainThreadMarker::new().expect("AppKit main thread")));
})
.map_err(|e| IdeError::internal(e.to_string()))?;
rx.recv().map_err(|e| IdeError::internal(e.to_string()))
}
/// Capture before building the new window, which takes focus itself.
pub fn new_project_tab_target(app: &AppHandle, launch: &Launch) -> IdeResult<Option<WebviewWindow>> {
let windows = app.webview_windows();
let active = windows
.values()
.find(|w| w.is_focused().unwrap_or(false))
.cloned()
.or_else(|| app.state::<WindowsState>().last_focused().and_then(|label| windows.get(&label).cloned()));
let active = active.and_then(|w| {
let label = crate::windows::settings_parent(w.label()).unwrap_or(w.label());
windows.get(label).cloned()
});
let active = active.filter(|w| {
let host = app.state::<crate::state::AppState>();
host.project(w.label()).is_ok_and(|p| !p.light) || host.remote_dev.get(w.label()).is_some()
});
let fullscreen = active.as_ref().is_some_and(|w| w.is_fullscreen().unwrap_or(false));
let light_edit = launch.project.is_none() && launch.remote.is_none();
Ok(should_group_new_project(tabbing_preference(app)?, fullscreen, active.is_some(), light_edit)
.then_some(active)
.flatten())
}
struct FullscreenObserver(Retained<ProtocolObject<dyn NSObjectProtocol>>);
impl Drop for FullscreenObserver {
fn drop(&mut self) {
let observer: &ProtocolObject<dyn NSObjectProtocol> = &self.0;
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
}
thread_local! {
static FULLSCREEN_TRANSFERS: std::cell::RefCell<std::collections::HashMap<String, FullscreenObserver>> = std::cell::RefCell::default();
}
pub fn forget_fullscreen(label: &str) {
FULLSCREEN_TRANSFERS.with_borrow_mut(|observers| observers.remove(label));
}
/// AppKit cannot enter another window's fullscreen Space until the old one has exited.
pub fn transfer_fullscreen(from: &WebviewWindow, to: &WebviewWindow) -> tauri::Result<()> {
let source = from.label().to_owned();
let to = to.clone();
from.with_webview(move |webview| unsafe {
let native = &*webview.ns_window().cast::<NSWindow>();
forget_fullscreen(&source);
let label = source.clone();
let block = block2::RcBlock::new(move |_| {
forget_fullscreen(&label);
let app = to.app_handle();
let selected = app.state::<WindowsState>().groups.lock().group(to.label()).map(|g| g.selected.clone());
if let Some(selected) = selected {
// Exiting fullscreen can show the old window again; reapply group visibility.
let _ = crate::window_groups::select(app, &selected, &selected);
if selected == to.label() {
let _ = to.set_fullscreen(true);
}
}
});
let observer = NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
Some(objc2_app_kit::NSWindowDidExitFullScreenNotification),
Some(native),
None,
&block,
);
FULLSCREEN_TRANSFERS.with_borrow_mut(|observers| observers.insert(source, FullscreenObserver(observer)));
native.toggleFullScreen(None);
})
}
+15 -3
Переглянути файл
@@ -51,8 +51,13 @@ fn copy_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let fullscreen = from.is_fullscreen().map_err(err)?;
if fullscreen {
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
#[cfg(target_os = "macos")]
crate::macos::transfer_fullscreen(from, to).map_err(err)?;
#[cfg(not(target_os = "macos"))]
{
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
}
return Ok(());
}
to.set_fullscreen(false).map_err(err)?;
@@ -109,6 +114,13 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
result
}
#[cfg(target_os = "macos")]
pub fn join(app: &AppHandle, anchor: &str, new_window: &str) -> IdeResult<()> {
let state = app.state::<WindowsState>();
state.groups.lock().join(anchor, new_window)?;
select(app, anchor, new_window)
}
pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
let members = windows::project_window_labels(app)
.into_iter()
@@ -235,7 +247,7 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
} else if path.is_dir() {
let window = match windows::find_project_window(app, path) {
Some(w) => w,
None => windows::create_window(app, Some(path.clone()))?,
None => windows::create_restored_window(app, path.clone())?,
};
Some(window.label().to_owned())
} else {
+30 -8
Переглянути файл
@@ -357,18 +357,35 @@ pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
/// Creates a new project window; `project` is opened by its frontend on load.
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
create_window_with(app, project, Vec::new())
create_window_with(app, project, Vec::new(), false)
}
/// [`create_window`] that also opens `files` (without `project`: in LightEdit).
fn create_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathBuf>) -> IdeResult<WebviewWindow> {
fn create_window_with(
app: &AppHandle,
project: Option<PathBuf>,
files: Vec<PathBuf>,
restoring: bool,
) -> IdeResult<WebviewWindow> {
let title = project.as_deref().or(files.first().map(PathBuf::as_path)).and_then(Path::file_name);
let title = title.map(|n| n.to_string_lossy().into_owned());
let files = files.into_iter().map(Into::into).collect();
create_window_for(app, title, Launch { project: project.map(Into::into), files, ..Default::default() })
create_window_for(app, title, Launch { project: project.map(Into::into), files, ..Default::default() }, restoring)
}
fn create_window_for(app: &AppHandle, title: Option<String>, launch: Launch) -> IdeResult<WebviewWindow> {
/// Restoring a saved group preserves its membership and selected tab.
pub fn create_restored_window(app: &AppHandle, project: PathBuf) -> IdeResult<WebviewWindow> {
create_window_with(app, Some(project), Vec::new(), true)
}
fn create_window_for(
app: &AppHandle,
title: Option<String>,
launch: Launch,
_restoring: bool,
) -> IdeResult<WebviewWindow> {
#[cfg(target_os = "macos")]
let tab_target = if _restoring { None } else { crate::macos::new_project_tab_target(app, &launch)? };
let windows = app.webview_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = window_config(app)?;
@@ -388,6 +405,11 @@ fn create_window_for(app: &AppHandle, title: Option<String>, launch: Launch) ->
}
app.state::<WindowsState>().set_launch(&label, launch);
let window = build_project_window(app, config)?;
#[cfg(target_os = "macos")]
if let Some(target) = tab_target {
crate::window_groups::join(app, target.label(), window.label())?;
return Ok(window);
}
focus(&window);
Ok(window)
}
@@ -401,7 +423,7 @@ pub fn spawn_window(app: &AppHandle, project: Option<PathBuf>) {
fn spawn_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathBuf>) {
let app = app.clone();
tauri::async_runtime::spawn(async move {
if let Err(e) = create_window_with(&app, project, files) {
if let Err(e) = create_window_with(&app, project, files, false) {
tracing::warn!("cannot open window: {}", e.message);
}
});
@@ -440,7 +462,7 @@ pub fn open_project_window(
if !new_window {
return Ok(OpenOutcome::Current);
}
let window = create_window_with(app, Some(root), files)?;
let window = create_window_with(app, Some(root), files, false)?;
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
}
@@ -450,7 +472,7 @@ pub fn open_project_window(
/// detach an editor tab out of its window.
pub fn open_file_in_new_window(app: &AppHandle, project: Option<PathBuf>, file: PathBuf) -> IdeResult<OpenOutcome> {
tracing::info!("open_file_in_new_window {} project={:?}", file.display(), project);
let window = create_window_with(app, project, vec![file])?;
let window = create_window_with(app, project, vec![file], false)?;
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
}
@@ -478,7 +500,7 @@ pub fn open_remote_window(app: &AppHandle, ssh_config: &str, path: &str, new_win
}
let title = path.trim_end_matches('/').rsplit('/').next().filter(|n| !n.is_empty() && *n != "~").map(str::to_owned);
let remote = RemoteLaunch { ssh_config: ssh_config.to_owned(), path: path.to_owned() };
let window = create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() })?;
let window = create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() }, false)?;
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
}
+5
Переглянути файл
@@ -551,6 +551,7 @@ export const commands = {
* to start the shell takes tens of milliseconds, a frozen UI if run there.
*/
termSpawn: (options: TerminalOptions, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("term_spawn", { options, onOutput })),
termStoreImage: (id: TerminalId, data: number[], mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termWrite: (id: TerminalId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("term_write", { id, data })),
termResize: (id: TerminalId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("term_resize", { id, cols, rows })),
termKill: (id: TerminalId) => typedError<null, IdeError>(__TAURI_INVOKE("term_kill", { id })),
@@ -3349,6 +3350,8 @@ export type GitOperation =
{ op: "interactiveRebase"; base: string | null; entries: RebaseEntry[] };
export type GitSettings = {
/** Show blame after the current editor line. */
inlineBlame?: boolean,
/** Path to the git executable; empty = auto-detect. */
executable?: string,
/** Default of Update Project: `merge` | `rebase`. */
@@ -3618,6 +3621,8 @@ cancellable: boolean } |
{ type: "indexState"; indexing: boolean; files: number; symbols: number } |
/** Git status / branch information should be refreshed. */
{ type: "vcsChanged"; root: IpcPath } | { type: "languageServer"; server: ServerId; name: string; status: ServerStatus; message: string | null } |
/** A running server lacks a capability; the UI offers the managed tool as a replacement. */
{ type: "languageServerWarning"; name: string; message: string; installTool: string } |
/**
* A stopped language server left the project's list (disabled in settings, or a
* fallback that a preferred server took over from again).
+3
Переглянути файл
@@ -32,6 +32,9 @@ import type { LanguageDescription } from "@codemirror/language";
import { create } from "zustand";
import { maybeEditorService } from "@/workbench/contributions";
/** Documents above this size (UTF-16 units) skip per-line decorations. */
export const HEAVY_LIMIT = 8_000_000;
export interface EditorDocContext {
doc: number;
path: string;
+11
Переглянути файл
@@ -119,6 +119,8 @@ const EXT_LANG: Record<string, string> = {
go: "go",
json: "json",
md: "markdown",
adoc: "asciidoc",
asciidoc: "asciidoc",
css: "css",
html: "html",
yml: "yaml",
@@ -218,6 +220,15 @@ const MEM_LANGUAGES: LanguageInfo[] = [
blockComment: null,
indent: { tabSize: 2, insertSpaces: true },
},
{
id: "asciidoc",
name: "AsciiDoc",
extensions: ["adoc", "asciidoc"],
uiMode: "AsciiDoc",
lineComment: "//",
blockComment: null,
indent: { tabSize: 2, insertSpaces: true },
},
{
id: "markdown",
name: "Markdown",
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { StreamLanguage, type StreamParser } from "@codemirror/language";
type State = { block: string | null };
const parser: StreamParser<State> = {
startState: () => ({ block: null }),
copyState: ({ block }) => ({ block }),
token(stream, state) {
if (stream.sol()) {
const line = stream.string;
const delimiter = line.trim();
if (state.block) {
if (delimiter === state.block) {
state.block = null;
stream.skipToEnd();
return "meta";
}
stream.skipToEnd();
return "monospace";
}
if (/^={1,6}\s+\S/.test(line)) {
stream.skipToEnd();
return "heading";
}
if (/^:[\w-]+:/.test(line)) {
stream.skipToEnd();
return "attributeName";
}
if (["----", "....", "____", "++++"].includes(delimiter)) {
state.block = delimiter;
stream.skipToEnd();
return "meta";
}
if (/^\s*\/\//.test(line)) {
stream.skipToEnd();
return "comment";
}
}
if (stream.eatSpace()) return null;
if (stream.match(/^https?:\/\/[^\s[\]<>]+/)) return "link";
if (stream.match(/^\*[^*\n]+\*/)) return "strong";
if (stream.match(/^_[^_\n]+_/)) return "emphasis";
if (stream.match(/^\x60[^\x60\n]+\x60/)) return "monospace";
stream.next();
return null;
},
languageData: { commentTokens: { line: "//" } },
};
export const asciidocLanguage = StreamLanguage.define(parser);
+48
Переглянути файл
@@ -3,6 +3,54 @@ import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
describe("language modes", () => {
it("recognizes AsciiDoc files and loads their lightweight syntax mode", async () => {
for (const path of ["/docs/guide.adoc", "/docs/guide.asciidoc"]) {
const description = findLanguageDescription("AsciiDoc", path);
expect(description?.name).toBe("AsciiDoc");
const support = await loadSupport(description!);
expect(support?.language).toBeTruthy();
}
});
it("assigns highlight tags to AsciiDoc syntax", async () => {
const support = await loadSupport(findLanguageDescription("AsciiDoc", "/docs/guide.adoc")!);
const doc = [
"= Guide",
":toc: left",
"----",
"const example = true;",
"----",
"*bold* _italic_ `code` https://example.com",
"// Comment",
].join("\n");
const highlighter = tagHighlighter([
{ tag: t.heading, class: "heading" },
{ tag: t.attributeName, class: "attribute" },
{ tag: t.meta, class: "meta" },
{ tag: t.monospace, class: "monospace" },
{ tag: t.strong, class: "strong" },
{ tag: t.emphasis, class: "emphasis" },
{ tag: t.link, class: "link" },
{ tag: t.comment, class: "comment" },
]);
const highlighted: [string, string][] = [];
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) => {
highlighted.push([doc.slice(from, to), style]);
});
expect(highlighted).toEqual([
["= Guide", "heading"],
[":toc: left", "attribute"],
["----", "meta"],
["const example = true;", "monospace"],
["----", "meta"],
["*bold*", "strong"],
["_italic_", "emphasis"],
["`code`", "monospace"],
["https://example.com", "link"],
["// Comment", "comment"],
]);
});
it("styles `?.` like `.` in JavaScript and TypeScript", async () => {
const highlighter = tagHighlighter([{ tag: t.derefOperator, class: "deref" }]);
for (const [mode, path] of [
+6 -1
Переглянути файл
@@ -68,6 +68,11 @@ const OWN_MODES = [
filename: /^(?:CMakeLists\.txt|.*\.cmake(?:\.in)?)$/,
load: async () => new LanguageSupport((await import("./cmake")).cmakeLanguage),
}),
LanguageDescription.of({
name: "AsciiDoc",
extensions: ["adoc", "asciidoc"],
load: () => import("./asciidoc").then((m) => new LanguageSupport(m.asciidocLanguage)),
}),
LanguageDescription.of({
name: "Shell",
load: async () => {
@@ -245,7 +250,7 @@ const DEDENT_STATEMENT = /^\s*(?:pass|break|continue|return)\b/;
const KEYWORD_OPEN_LANGS = new Set(["elixir", "ruby", "lua"]);
const KEYWORD_OPEN =
/\b(?:do(?:\s*\|[^|]*\|)?|then|->)$|^\s*(?:def|defp|defmodule|class|module|function|local\s+function|if|unless|elsif|elseif|else|while|until|for|case|begin|cond|with|receive|try)\b/;
const NO_INDENT_LANGS = new Set(["plaintext", "markdown", "log", "diff", "ignore", "gitattributes"]);
const NO_INDENT_LANGS = new Set(["plaintext", "markdown", "asciidoc", "log", "diff", "ignore", "gitattributes"]);
function opensBlock(code: string, language: string | undefined): boolean {
if (!code) return false;
+2 -3
Переглянути файл
@@ -28,7 +28,7 @@ import type { EditorConfigProps } from "@/bindings";
import type { EditorSettings } from "@/platform/ipc";
import { editorPrefs, lineCommentStyleFor, type EditorExtras } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import { editorContributions, type EditorDocContext } from "@/editor/api";
import { editorContributions, HEAVY_LIMIT, type EditorDocContext } from "@/editor/api";
import { distractionFreeWidth, isDistractionFree } from "@/workbench/distractionFree";
import { openideaHighlightStyle } from "./highlight";
import { openideaTheme } from "./theme";
@@ -78,8 +78,7 @@ export function prefsOf(settings: EditorSettings | undefined): EditorExtras {
return editorPrefs({ editor: settings });
}
/** Documents above this size (UTF-16 units) skip per-line decorations. */
export const HEAVY_LIMIT = 8_000_000;
export { HEAVY_LIMIT } from "@/editor/api";
export interface EffectiveIndent {
tabSize: number;
+95 -21
Переглянути файл
@@ -171,6 +171,14 @@ function isTextTab(tab: Tab | null | undefined): tab is Tab & { input: { path: s
type EditorKinds = ReturnType<typeof useContributions.getState>["editorKinds"];
interface OpenRequest {
project: number;
admission: number;
sequence: number;
activation: number;
pane: string;
}
/** Tab title of an editor input: the file name, or what its editor kind calls it. */
export function tabTitle(input: EditorInput, kinds: EditorKinds): string {
if (input.kind === "file") return basename(input.path ?? input.key);
@@ -223,6 +231,10 @@ export class EditorController implements SlotHost {
private closeCommitted = false;
private projectGeneration = 0;
private admissionGeneration = 0;
private openSequence = 0;
private selectionRequests = new Map<string, number>();
private activationGeneration = 0;
private admitting = false;
private closeRequests = 0;
private projectTransition: Promise<void> = Promise.resolve();
@@ -246,6 +258,11 @@ export class EditorController implements SlotHost {
useTabs.subscribe((s) => {
const prev = prevTabs;
prevTabs = s;
if (
!this.admitting &&
(s.activePane !== prev.activePane || s.panes[s.activePane]?.active !== prev.panes[prev.activePane]?.active)
)
++this.activationGeneration;
this.stampActive(s);
this.onTabsChanged(prev, s);
}),
@@ -347,6 +364,7 @@ export class EditorController implements SlotHost {
this.preparedDocuments.clear();
for (const slot of this.slots.values()) slot.dispose();
this.slots.clear();
this.selectionRequests.clear();
this.manager.stop();
useTabs.setState(initialTabsState(), true);
void this.releaseDocuments(documents.values()).catch((e) => this.documentError(e));
@@ -361,6 +379,7 @@ export class EditorController implements SlotHost {
private onTabsChanged(prev: TabsState, next: TabsState) {
const live = new Set<string>();
for (const p of Object.values(next.panes)) for (const t of p.tabs) live.add(t.id);
for (const id of this.selectionRequests.keys()) if (!live.has(id)) this.selectionRequests.delete(id);
for (const [id, slot] of this.slots) {
if (!live.has(id)) {
this.slots.delete(id);
@@ -529,7 +548,9 @@ export class EditorController implements SlotHost {
if (active?.id === slot.tabId) this.setActiveSlot(slot);
if (slot.wantsFocus) {
slot.wantsFocus = false;
requestAnimationFrame(() => slot.focus());
requestAnimationFrame(() => {
if (!slot.disposed && this.activeTabOf()?.id === slot.tabId) slot.focus();
});
}
}
@@ -849,8 +870,15 @@ export class EditorController implements SlotHost {
// --- opening ---------------------------------------------------------------------------
private openingGeneration() {
const generation = { project: this.projectGeneration, admission: this.admissionGeneration };
private openingGeneration(o: OpenOptions): OpenRequest {
const s = useTabs.getState();
const generation = {
project: this.projectGeneration,
admission: this.admissionGeneration,
sequence: ++this.openSequence,
activation: this.activationGeneration,
pane: o.pane && s.panes[o.pane] ? o.pane : s.activePane,
};
this.checkOpening(generation);
return generation;
}
@@ -861,16 +889,28 @@ export class EditorController implements SlotHost {
throw new Error("The project is closing");
}
private isCurrentOpening(generation: OpenRequest) {
return (
generation.project === this.projectGeneration &&
generation.admission === this.admissionGeneration &&
generation.sequence === this.openSequence &&
generation.activation === this.activationGeneration
);
}
async openFile(path: string, o: OpenOptions = {}): Promise<void> {
const generation = this.openingGeneration();
if (isVirtualUri(path)) return this.openVirtual(path, o);
return this.openFileRequest(path, o, this.openingGeneration(o));
}
private async openFileRequest(path: string, o: OpenOptions, generation: OpenRequest): Promise<void> {
if (isVirtualUri(path)) return this.openVirtualRequest(path, o, generation);
if (isClassFile(path)) {
await this.projectTransition;
this.checkOpening(generation);
try {
const target = await call(commands.lspResolveClassFile(path));
this.checkOpening(generation);
return isVirtualUri(target) ? this.openVirtual(target, o) : this.openFile(target, o);
return this.openFileRequest(target, o, generation);
} catch (e) {
notifications().notify({ level: "warning", title: "Cannot open library class", body: String(e), group: "lsp" });
return;
@@ -895,7 +935,10 @@ export class EditorController implements SlotHost {
/** Opens the library class (or other server-provided document) behind `uri` read-only. */
async openVirtual(uri: string, o: OpenOptions = {}) {
const generation = this.openingGeneration();
return this.openVirtualRequest(uri, o, this.openingGeneration(o));
}
private async openVirtualRequest(uri: string, o: OpenOptions, generation: OpenRequest) {
await this.projectTransition;
this.checkOpening(generation);
let vd: VirtualDocument;
@@ -915,13 +958,13 @@ export class EditorController implements SlotHost {
async openInput(input: EditorInput, o: OpenOptions = {}) {
if (input.path && isClassFile(input.path)) return this.openFile(input.path, o);
return this.admitInput(input, o, this.openingGeneration());
return this.admitInput(input, o, this.openingGeneration(o));
}
private async admitInput(
input: EditorInput,
o: OpenOptions,
generation: { project: number; admission: number },
generation: OpenRequest,
resolution?: FileEditorResolution,
) {
await this.projectTransition;
@@ -931,7 +974,14 @@ export class EditorController implements SlotHost {
this.navSuppress++;
try {
let s = useTabs.getState();
let paneId = o.pane && s.panes[o.pane] ? o.pane : s.activePane;
const activate = this.isCurrentOpening(generation);
const preview =
!!o.preview &&
editorPrefs().tabs.previewTab &&
!documentLifecycle(input, useContributions.getState().editorKinds);
if (!activate && preview) return;
let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null;
if (!paneId) return;
if (o.side) {
const right = neighbourPane(s, paneId);
if (right) paneId = right;
@@ -942,34 +992,44 @@ export class EditorController implements SlotHost {
// The new pane starts with only the requested input.
const pane = s.panes[paneId]!;
s = { ...s, panes: { ...s.panes, [paneId]: { ...pane, tabs: [], active: null, mru: [] } } };
if (!activate) s = { ...s, activePane: useTabs.getState().activePane };
}
}
const found = findTab(s, input.key, paneId);
let tabId: string;
if (found && (!(o.side || o.pane) || found.paneId === paneId)) {
paneId = found.paneId;
s = activateTab(setActivePane(s, paneId), paneId, found.tab.id);
if (activate) s = activateTab(setActivePane(s, paneId), paneId, found.tab.id);
if (!o.preview || documentLifecycle(input, useContributions.getState().editorKinds))
s = promoteTab(s, paneId, found.tab.id);
tabId = found.tab.id;
if (found.tab.input.data !== input.data && input.data !== undefined)
if (activate && found.tab.input.data !== input.data && input.data !== undefined)
s = openTab(s, paneId, input, {
preview: o.preview && !documentLifecycle(input, useContributions.getState().editorKinds),
activate,
}).state;
} else {
const tabs = editorPrefs().tabs;
const preview =
!!o.preview && tabs.previewTab && !documentLifecycle(input, useContributions.getState().editorKinds);
const r = openTab(s, paneId, input, {
preview,
activate,
preservePreview: !activate,
...(tabs.openAtEnd ? { index: s.panes[paneId]?.tabs.length ?? 0 } : {}),
});
s = r.state;
tabId = r.tabId;
if (tabs.sortAlphabetically) s = sortTabs(s, paneId, (t) => tabSortKey(t.input));
}
resolution?.admit();
useTabs.setState(s, true);
if (o.selection)
this.selectionRequests.set(tabId, Math.max(generation.sequence, this.selectionRequests.get(tabId) ?? 0));
this.admitting = true;
try {
resolution?.admit();
useTabs.setState(s, true);
} finally {
this.admitting = false;
}
const canFocus = () => this.isCurrentOpening(generation) && this.activeTabOf()?.id === tabId;
const tabPrefs = editorPrefs().tabs;
await this.removeGuarded(
(current) =>
@@ -982,19 +1042,26 @@ export class EditorController implements SlotHost {
(tab) =>
inputDirty(tab.input, useContributions.getState().editorKinds) ??
!!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
tabId,
activate ? tabId : (current.panes[paneId]?.active ?? tabId),
(tab) => inputDirty(tab.input, useContributions.getState().editorKinds) === true,
)
: current,
{ protect: (tab) => inputDirty(tab.input, useContributions.getState().editorKinds) === true },
);
if (!isTextInput(input)) {
if (o.focus !== false) requestAnimationFrame(() => this.focus());
if (o.focus !== false)
requestAnimationFrame(() => {
if (canFocus()) this.focus();
});
return;
}
const slot = await this.ensureSlot(tabId);
if (!slot) return;
if (o.selection) {
if (
o.selection &&
this.selectionRequests.get(tabId) === generation.sequence &&
generation.activation === this.activationGeneration
) {
const state = slot.currentState();
const toOffset = (line: number, col: number) => {
const l = state.doc.line(Math.min(Math.max(1, line + 1), state.doc.lines));
@@ -1006,7 +1073,7 @@ export class EditorController implements SlotHost {
// Selection runs anchor→head; place the caret at the start like IDEA's navigation.
slot.reveal({ anchor: head, head: anchor, center: true });
}
if (o.focus !== false) {
if (o.focus !== false && canFocus()) {
if (slot.view) slot.focus();
else slot.wantsFocus = true;
}
@@ -1017,12 +1084,19 @@ export class EditorController implements SlotHost {
}
activate(paneId: string, tabId: string, focus = true) {
++this.activationGeneration;
useTabs.setState((s) => activateTab(setActivePane(s, paneId), paneId, tabId), true);
if (focus) {
const slot = this.slots.get(tabId);
if (slot?.view) slot.focus();
else if (slot) slot.wantsFocus = true;
else void this.ensureSlot(tabId).then((sl) => sl && (sl.view ? sl.focus() : (sl.wantsFocus = true)));
else
void this.ensureSlot(tabId).then((sl) => {
if (sl && this.activeTabOf()?.id === tabId) {
if (sl.view) sl.focus();
else sl.wantsFocus = true;
}
});
}
}
+300
Переглянути файл
@@ -0,0 +1,300 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerFileEditorProvider } from "@/workbench/contributions";
import { EditorController, openFilePaths, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { initialTabsState } from "./model/tabs";
import { useProject } from "@/platform/project";
let ctrl: EditorController | null = null;
let dispose: (() => void) | undefined;
const initialSettings = useProject.getState().settings;
afterEach(() => {
dispose?.();
dispose = undefined;
ctrl?.stop();
ctrl = null;
useTabs.setState(initialTabsState(), true);
useProject.setState({ settings: initialSettings });
});
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
});
return { promise, resolve };
}
function activePath() {
const state = useTabs.getState();
const pane = state.panes[state.activePane]!;
return pane.tabs.find((tab) => tab.id === pane.active)?.input.path;
}
function setup() {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a\nsecond", "/p/b.ts": "b", "/p/c.ts": "c" }));
ctrl.start();
return ctrl;
}
function delayProvider(path = "/p/a.ts") {
const started = deferred();
const response = deferred();
let delayed = false;
dispose = registerFileEditorProvider({
id: "delayed-file",
resolve: async (requested) => {
if (requested === path && !delayed) {
delayed = true;
started.resolve();
await response.promise;
}
return null;
},
});
return { started, response };
}
function tabFor(path: string) {
return Object.values(useTabs.getState().panes)
.flatMap((pane) => pane.tabs)
.find((tab) => tab.input.path === path);
}
describe("file open order", () => {
it.each([1, 30])("keeps the newer file active after an earlier probe (tab limit: %s)", async (tabLimit) => {
useProject.setState({ settings: { editor: { tabs: { tabLimit } } } as never });
const { started, response } = delayProvider();
const controller = setup();
const first = controller.openFile("/p/a.ts", { focus: false });
await started.promise;
await controller.openFile("/p/b.ts", { focus: false });
expect(activePath()).toBe("/p/b.ts");
response.resolve();
await first;
expect(openFilePaths(useTabs.getState()).sort()).toEqual(tabLimit === 1 ? ["/p/b.ts"] : ["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
expect(controller.activeSlot?.model.path).toBe("/p/b.ts");
});
it("activates the newer file after an earlier probe finishes while both are pending", async () => {
const a = { started: deferred(), response: deferred() };
const b = { started: deferred(), response: deferred() };
dispose = registerFileEditorProvider({
id: "two-delayed-files",
resolve: async (path) => {
const pending = path === "/p/a.ts" ? a : b;
pending.started.resolve();
await pending.response.promise;
return null;
},
});
const controller = setup();
const first = controller.openFile("/p/a.ts", { focus: false });
await a.started.promise;
const second = controller.openFile("/p/b.ts", { focus: false });
await b.started.promise;
a.response.resolve();
await first;
b.response.resolve();
await second;
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
it("discards an earlier preview without replacing the newer preview", async () => {
const { started, response } = delayProvider();
const controller = setup();
const first = controller.openFile("/p/a.ts", { preview: true, focus: false });
await started.promise;
await controller.openFile("/p/b.ts", { preview: true, focus: false });
response.resolve();
await first;
expect(openFilePaths(useTabs.getState())).toEqual(["/p/b.ts"]);
expect(tabFor("/p/b.ts")?.preview).toBe(true);
expect(activePath()).toBe("/p/b.ts");
});
it("keeps an earlier regular file without removing the newer preview", async () => {
const { started, response } = delayProvider();
const controller = setup();
const first = controller.openFile("/p/a.ts", { focus: false });
await started.promise;
await controller.openFile("/p/b.ts", { preview: true, focus: false });
response.resolve();
await first;
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(tabFor("/p/a.ts")?.preview).toBe(false);
expect(tabFor("/p/b.ts")?.preview).toBe(true);
expect(activePath()).toBe("/p/b.ts");
});
it("keeps manual tab activation while an earlier probe is pending", async () => {
const { started, response } = delayProvider();
const controller = setup();
await controller.openFile("/p/b.ts", { focus: false });
await controller.openFile("/p/c.ts", { focus: false });
const first = controller.openFile("/p/a.ts", { focus: false });
await started.promise;
controller.activate(useTabs.getState().activePane, tabFor("/p/b.ts")!.id, false);
response.resolve();
await first;
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts", "/p/c.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
it("keeps a newer explicit open regular when the same file's preview resolves late", async () => {
const { started, response } = delayProvider();
const controller = setup();
const preview = controller.openFile("/p/a.ts", { preview: true, focus: false });
await started.promise;
await controller.openFile("/p/a.ts", { focus: false });
response.resolve();
await preview;
expect(openFilePaths(useTabs.getState())).toEqual(["/p/a.ts"]);
expect(tabFor("/p/a.ts")?.preview).toBe(false);
expect(activePath()).toBe("/p/a.ts");
});
it("promotes an admitted preview when the same file is opened explicitly", async () => {
const controller = setup();
await controller.openFile("/p/a.ts", { preview: true, focus: false });
const tabId = tabFor("/p/a.ts")!.id;
expect(tabFor("/p/a.ts")?.preview).toBe(true);
await controller.openFile("/p/a.ts", { focus: false });
expect(openFilePaths(useTabs.getState())).toEqual(["/p/a.ts"]);
expect(tabFor("/p/a.ts")).toMatchObject({ id: tabId, preview: false });
expect(activePath()).toBe("/p/a.ts");
});
it("keeps the newer selection when an earlier open of the same file resolves late", async () => {
const { started, response } = delayProvider();
const controller = setup();
const first = controller.openFile("/p/a.ts", { selection: { line: 0, col: 0 }, focus: false });
await started.promise;
await controller.openFile("/p/a.ts", { selection: { line: 1, col: 0 }, focus: false });
response.resolve();
await first;
const state = controller.slotFor(tabFor("/p/a.ts")!.id)!.currentState();
expect(state.doc.lineAt(state.selection.main.head).number).toBe(2);
});
it.each([false, true])("keeps a pending navigation selection after a plain open (same file: %s)", async (same) => {
const backend = createMemoryBackend({ "/p/a.ts": "a\nsecond", "/p/b.ts": "b" });
const started = deferred();
const response = deferred();
const open = backend.open.bind(backend);
backend.open = async (path) => {
if (path === "/p/a.ts") {
started.resolve();
await response.promise;
}
return open(path);
};
ctrl = new EditorController(backend);
ctrl.start();
const navigation = ctrl.openFile("/p/a.ts", { selection: { line: 1, col: 2 } });
await started.promise;
const plain = ctrl.openFile(same ? "/p/a.ts" : "/p/b.ts", { focus: false });
if (!same) await plain;
response.resolve();
await Promise.all([navigation, plain]);
const slot = ctrl.slotFor(tabFor("/p/a.ts")!.id)!;
expect(slot.caret()).toMatchObject({ line: 1, col: 2 });
expect(slot.wantsFocus).toBe(false);
expect(activePath()).toBe(same ? "/p/a.ts" : "/p/b.ts");
});
it.each([true, false])("keeps a delayed open in its origin pane (explicit: %s)", async (explicit) => {
const { started, response } = delayProvider();
const controller = setup();
await controller.openFile("/p/b.ts", { focus: false });
const origin = useTabs.getState().activePane;
controller.split(origin, "row");
const other = useTabs.getState().activePane;
expect(other).not.toBe(origin);
controller.activate(origin, tabFor("/p/b.ts")!.id, false);
const first = controller.openFile("/p/a.ts", { ...(explicit ? { pane: origin } : {}), focus: false });
await started.promise;
await controller.openFile("/p/c.ts", { pane: other, focus: false });
response.resolve();
await first;
const state = useTabs.getState();
expect(state.panes[origin]!.tabs.some((tab) => tab.input.path === "/p/a.ts")).toBe(true);
expect(state.panes[other]!.tabs.some((tab) => tab.input.path === "/p/a.ts")).toBe(false);
expect(activePath()).toBe("/p/c.ts");
});
it("does not request focus when an earlier document finishes loading late", async () => {
const backend = createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" });
const started = deferred();
const response = deferred();
const open = backend.open.bind(backend);
backend.open = async (path) => {
if (path === "/p/a.ts") {
started.resolve();
await response.promise;
}
return open(path);
};
ctrl = new EditorController(backend);
ctrl.start();
const first = ctrl.openFile("/p/a.ts");
await started.promise;
await ctrl.openFile("/p/b.ts", { focus: false });
response.resolve();
await first;
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
expect(ctrl.slotFor(tabFor("/p/a.ts")!.id)?.wantsFocus).toBe(false);
});
it("does not run queued mount focus after a newer file becomes active", async () => {
const controller = setup();
await controller.openFile("/p/a.ts");
const slot = controller.slotFor(tabFor("/p/a.ts")!.id)!;
expect(slot.wantsFocus).toBe(true);
const focus = vi.spyOn(slot, "focus");
const frames: FrameRequestCallback[] = [];
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => frames.push(callback));
try {
controller.onMounted(slot);
expect(frames.length).toBeGreaterThan(0);
await controller.openFile("/p/b.ts", { focus: false });
for (const frame of frames) frame(0);
expect(focus).not.toHaveBeenCalled();
expect(activePath()).toBe("/p/b.ts");
} finally {
vi.unstubAllGlobals();
focus.mockRestore();
}
});
it("rolls back a superseded custom preview before provider admission", async () => {
const started = deferred();
const response = deferred();
const commit = vi.fn();
const rollback = vi.fn(async () => {});
dispose = registerFileEditorProvider({
id: "delayed-custom-preview",
resolve: async (path, context) => {
if (path !== "/p/a.ts") return null;
context.onAdmission(commit, rollback);
started.resolve();
await response.promise;
return { kind: "image", key: "image:/p/a.ts", path };
},
});
const controller = setup();
const first = controller.openFile("/p/a.ts", { preview: true, focus: false });
await started.promise;
await controller.openFile("/p/b.ts", { preview: true, focus: false });
response.resolve();
await first;
expect(commit).not.toHaveBeenCalled();
expect(rollback).toHaveBeenCalledOnce();
expect(activePath()).toBe("/p/b.ts");
expect(tabFor("/p/a.ts")).toBeUndefined();
});
});
+120
Переглянути файл
@@ -0,0 +1,120 @@
import { afterEach, expect, it, vi } from "vitest";
import { LanguageSupport, StreamLanguage } from "@codemirror/language";
import { createMemoryBackend } from "../backend";
import { _resetLanguages, loadLanguageInfos, loadSupport } from "../cm/languages";
import { DocumentManager } from "./document";
vi.mock("../cm/languages", async (importOriginal) => {
const actual = await importOriginal<typeof import("../cm/languages")>();
return { ...actual, loadSupport: vi.fn(actual.loadSupport) };
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
afterEach(() => {
_resetLanguages();
vi.mocked(loadSupport).mockClear();
});
it.each(["/p/a.ts", "jdt://contents/a.ts"])("starts reading %s before the catalog resolves", async (path) => {
const backend = createMemoryBackend({ [path]: "const a = 1" });
const languages = await backend.languages();
const catalog = deferred<typeof languages>();
vi.spyOn(backend, "languages").mockReturnValue(catalog.promise);
const open = vi.spyOn(backend, path.startsWith("jdt:") ? "openVirtual" : "open");
const manager = new DocumentManager(backend, { settings: () => ({}), notify: vi.fn() });
let exposed = false;
const pending = manager.acquire(path).then((model) => {
exposed = true;
return model;
});
try {
expect(open).toHaveBeenCalledWith(path);
await open.mock.results[0]!.value;
expect(exposed).toBe(false);
expect(manager.get(path)).toBeUndefined();
} finally {
catalog.resolve(languages);
const model = await pending;
model.dispose();
manager.stop();
}
});
it("starts the known mode while document content is still pending", async () => {
const path = "/p/a.ts";
const backend = createMemoryBackend({ [path]: "const a = 1" });
const info = await backend.open(path);
const content = deferred<typeof info>();
vi.spyOn(backend, "open").mockReturnValue(content.promise);
const manager = new DocumentManager(backend, { settings: () => ({}), notify: vi.fn() });
const pending = manager.acquire(path);
await loadLanguageInfos(backend);
try {
expect(loadSupport).toHaveBeenCalledWith(expect.objectContaining({ name: "TypeScript" }));
} finally {
content.resolve(info);
const model = await pending;
model.dispose();
manager.stop();
}
});
it("handles a speculative mode rejection when opening the document fails", async () => {
const backend = createMemoryBackend();
const failure = new Error("cannot read document");
vi.spyOn(backend, "open").mockRejectedValue(failure);
vi.mocked(loadSupport).mockRejectedValueOnce(new Error("cannot preload mode"));
const manager = new DocumentManager(backend, { settings: () => ({}), notify: vi.fn() });
try {
await expect(manager.acquire("/p/a.ts")).rejects.toBe(failure);
expect(loadSupport).toHaveBeenCalledWith(expect.objectContaining({ name: "TypeScript" }));
} finally {
manager.stop();
}
});
it("opens within 50 ms with catalog, read and cold mode budgets of 20, 40 and 30 ms", async () => {
const path = "/p/cold.rs";
const backend = createMemoryBackend({ [path]: "fn main() {}" });
const catalog = await backend.languages();
const info = await backend.open(path);
const originalSupport = vi.mocked(loadSupport).getMockImplementation()!;
const support = new LanguageSupport(StreamLanguage.define({ token: (stream) => (stream.skipToEnd(), null) }));
let loading: Promise<LanguageSupport> | undefined;
let readyAt: number | undefined;
const manager = new DocumentManager(backend, { settings: () => ({}), notify: vi.fn() });
vi.useFakeTimers();
const start = Date.now();
vi.spyOn(backend, "languages").mockImplementation(
() => new Promise((resolve) => setTimeout(() => resolve(catalog), 20)),
);
vi.spyOn(backend, "open").mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(info), 40)));
vi.mocked(loadSupport).mockImplementation(
() => (loading ??= new Promise((resolve) => setTimeout(() => resolve(support), 30))),
);
const pending = manager.acquire(path).then((model) => {
readyAt = Date.now() - start;
return model;
});
try {
await vi.advanceTimersByTimeAsync(90);
expect(readyAt).toBeLessThanOrEqual(50);
expect((await pending).language).toBe(support);
} finally {
try {
await vi.runAllTimersAsync();
(await pending).dispose();
} finally {
manager.stop();
vi.mocked(loadSupport).mockImplementation(originalSupport);
vi.useRealTimers();
}
}
});
+12 -2
Переглянути файл
@@ -36,6 +36,7 @@ import {
loadSupport,
loadedSupport,
commentTokens,
uiModeForPath,
} from "../cm/languages";
import { foldEffect } from "@codemirror/language";
import { backendFolds, setBackendFolds } from "../cm/folding";
@@ -683,8 +684,17 @@ export class DocumentManager {
let p = this.opening.get(path);
if (!p) {
p = (async () => {
await loadLanguageInfos(this.backend);
const info = isVirtualUri(path) ? await this.backend.openVirtual(path) : await this.backend.open(path);
const catalog = loadLanguageInfos(this.backend);
void catalog
.then(() => {
const desc = findLanguageDescription(uiModeForPath(path) ?? null, path);
if (desc) return loadSupport(desc);
})
.catch(() => {});
const [info] = await Promise.all([
isVirtualUri(path) ? this.backend.openVirtual(path) : this.backend.open(path),
catalog,
]);
const raced = this.byPath.get(path);
if (raced) {
void this.backend.close(info.id);
+3 -1
Переглянути файл
@@ -9,7 +9,7 @@ const loading = vi.hoisted(() => {
const ready = new Promise<void>((resolve) => {
finish = resolve;
});
return { ready, finish, started: false };
return { ready, finish, started: false, modes: [] as string[] };
});
vi.mock("../cm/languages", async (importOriginal) => {
@@ -18,6 +18,7 @@ vi.mock("../cm/languages", async (importOriginal) => {
...actual,
loadSupport: async (...args: Parameters<typeof actual.loadSupport>) => {
loading.started = true;
loading.modes.push(args[0].name);
await loading.ready;
return actual.loadSupport(...args);
},
@@ -49,6 +50,7 @@ it("waits for the lazy mode before exposing an Angular document to its first slo
onContextMenu() {},
});
expect(slot.currentState().facet(languageFacet)?.name).toBe("angular");
expect(loading.modes).toEqual(expect.arrayContaining(["HTML", "Angular Template"]));
slot.dispose();
manager.stop();
});
+2 -1
Переглянути файл
@@ -113,6 +113,7 @@ export interface OpenTabOptions {
/** Insert at this index instead of after the active tab. */
index?: number;
activate?: boolean;
preservePreview?: boolean;
}
export function openTab(
@@ -152,7 +153,7 @@ export function openTab(
tabs.splice(index, 0, tab);
}
let active = pane.active;
if (!tab.preview && tabs.some((t) => t.preview)) {
if (!tab.preview && !opts.preservePreview && tabs.some((t) => t.preview)) {
// A new regular editor closes the preview tab (IDEA trims previews on every open).
const previews = new Set(tabs.filter((t) => t.preview).map((t) => t.id));
tabs.splice(0, tabs.length, ...tabs.filter((t) => !previews.has(t.id)));
+8 -5
Переглянути файл
@@ -118,19 +118,22 @@ async function format(
try {
edits = await lspRequest(() => commands.lspFormat(doc.doc, range, { ...options, onSave: opts.onSave }));
} catch (e) {
if (e instanceof IpcError && e.data?.type === "tool" && e.data.tool === "prettier") {
if (e instanceof IpcError && e.data?.type === "tool" && (e.data.tool === "prettier" || e.data.tool === "oxfmt")) {
const tool = e.data.tool;
if (e.kind === "notFound" && e.data.missing) {
await executeAction("tools.promptInstall", { name: "prettier", sticky: !opts.onSave });
await executeAction("tools.promptInstall", { name: tool, sticky: !opts.onSave });
} else if (e.kind !== "cancelled") {
notifications().notify({
group: "tools",
level: "error",
title: tx("Prettier formatting failed"),
title: tool === "oxfmt" ? tx("oxfmt formatting failed") : tx("Prettier formatting failed"),
body:
e.kind === "timedOut"
? tx("Prettier formatting timed out")
? tool === "oxfmt"
? tx("oxfmt formatting timed out")
: tx("Prettier formatting timed out")
: createElement("span", { className: styles.diagnostics }, e.message),
key: `prettier-format-error:${doc.path}`,
key: `${tool}-format-error:${doc.path}`,
sticky: false,
});
}
+7 -6
Переглянути файл
@@ -18,7 +18,6 @@ import {
import { formatDocument } from "./format";
import * as lsp from "./lsp";
const tool = { type: "tool", tool: "prettier", missing: false } as const;
const views: EditorView[] = [];
const viewFor = (path = "/project/file.css") => {
const view = new EditorView({
@@ -43,7 +42,9 @@ afterEach(() => {
_resetI18nForTests();
});
describe("external formatter errors", () => {
describe.each(["prettier", "oxfmt"])("%s formatter errors", (name) => {
const tool = { type: "tool", tool: name, missing: false } as const;
const display = name === "prettier" ? "Prettier" : name;
it("uses structured missing-tool information to request the shared install prompt", async () => {
const prompt = vi.fn();
const dispose = registerAction({
@@ -54,9 +55,9 @@ describe("external formatter errors", () => {
try {
failWith({ kind: "notFound", message: "unrelated diagnostic", data: { ...tool, missing: true } });
await formatDocument(viewFor());
expect(prompt).toHaveBeenCalledWith({ name: "prettier", sticky: true });
expect(prompt).toHaveBeenCalledWith({ name, sticky: true });
await formatDocument(viewFor(), { explicit: false, onSave: true });
expect(prompt).toHaveBeenLastCalledWith({ name: "prettier", sticky: false });
expect(prompt).toHaveBeenLastCalledWith({ name, sticky: false });
expect(useNotifications.getState().items).toHaveLength(0);
} finally {
dispose();
@@ -95,7 +96,7 @@ describe("external formatter errors", () => {
for (let i = 0; i < 3; i++) await formatDocument(view, { explicit: false, onSave: true });
const notes = useNotifications.getState().items;
expect(notes).toHaveLength(1);
expect(notes[0]).toMatchObject({ sticky: false, title: "Prettier 格式化失败" });
expect(notes[0]).toMatchObject({ sticky: false, title: `${display} 格式化失败` });
expect(balloonTimeout(notes[0]!)).toBe(10000);
render(<Balloons />);
expect(screen.getByRole("alert")).toHaveTextContent(stderr);
@@ -115,7 +116,7 @@ describe("external formatter errors", () => {
const request = failWith({ kind: "timedOut", message: "arbitrary backend text", data: tool });
const view = viewFor();
await formatDocument(view);
expect(useNotifications.getState().items[0]).toMatchObject({ body: "Prettier 格式化超时", sticky: false });
expect(useNotifications.getState().items[0]).toMatchObject({ body: `${display} 格式化超时`, sticky: false });
clearNotifications();
request.mockRejectedValue(new IpcError({ kind: "cancelled", message: "cancelled", data: tool }));
await formatDocument(view);
+2 -2
Переглянути файл
@@ -5,7 +5,7 @@ import { basename, dirname, useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { tx } from "@/platform/i18n";
import { Button, Dialog, Icon, IconButton, Input, T } from "@/ui";
import { openProjectInWindow } from "./windows";
import { openProjectWithPolicy } from "./windows";
import styles from "./WorkspaceDialog.module.css";
const useWorkspaceDialog = create<{ mode: "create" | "manage" | null }>(() => ({ mode: null }));
@@ -53,7 +53,7 @@ function WorkspaceDialog({ mode, onClose }: { mode: "create" | "manage"; onClose
const included = adding.trim() ? [...new Set([...projects, adding.trim()])] : projects;
if (mode === "create") {
const root = await call(commands.workspaceCreate(path.trim(), name.trim(), included));
await openProjectInWindow(root, !!project);
await openProjectWithPolicy(root);
} else {
const updated = await call(commands.workspaceUpdate(name.trim(), included));
useProject.setState({ project: updated, settings: updated.settings });
+18 -3
Переглянути файл
@@ -3,13 +3,14 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { WorkspaceDialogHost, showWorkspaceDialog } from "../WorkspaceDialog";
import { openProjectInWindow } from "../windows";
import { openProjectWithPolicy } from "../windows";
vi.mock("../windows", () => ({ openProjectInWindow: vi.fn(async () => {}) }));
vi.mock("../windows", () => ({ openProjectWithPolicy: vi.fn(async () => {}) }));
vi.mock("@/platform/remote", () => ({ isRemoteWindow: () => false }));
beforeEach(() => {
vi.restoreAllMocks();
vi.mocked(openProjectWithPolicy).mockClear();
useProject.setState({ project: null, settings: null, lightEdit: false });
});
@@ -21,7 +22,21 @@ it("creates a workspace from the pending project field without an extra Add clic
fireEvent.change(screen.getByLabelText("Project folder path"), { target: { value: "/work/frontend" } });
fireEvent.click(screen.getByRole("button", { name: /^Create$/ }));
await waitFor(() => expect(save).toHaveBeenCalledWith("/work/full", "Workspace", ["/work/frontend"]));
expect(openProjectInWindow).toHaveBeenCalledWith("/work/full", false);
expect(openProjectWithPolicy).toHaveBeenCalledWith("/work/full");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("uses the shared opening policy after creation from an already open project", async () => {
useProject.setState({
project: { root: "/work/frontend", name: "frontend", trusted: true, isGit: false, settings: {} },
settings: { general: { openProjectIn: "ask" } },
} as never);
vi.spyOn(commands, "workspaceCreate").mockResolvedValue({ status: "ok", data: "/work/full" });
showWorkspaceDialog("create");
render(<WorkspaceDialogHost />);
fireEvent.change(screen.getByLabelText("Workspace location"), { target: { value: "/work/full" } });
fireEvent.click(screen.getByRole("button", { name: /^Create$/ }));
await waitFor(() => expect(openProjectWithPolicy).toHaveBeenCalledWith("/work/full"));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
+29
Переглянути файл
@@ -172,6 +172,9 @@ describe("ProjectView", () => {
act(() => setViewOption("previewTab", true));
fireEvent.click(content, { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
openFile.mockClear();
fireEvent.click(content, { detail: 3 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", false));
});
@@ -207,6 +210,32 @@ describe("ProjectView", () => {
act(() => setViewOption("singleClickExpand", false));
});
it("toggles folders once for each rapid double-click pair", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
act(() => setViewOption("singleClickExpand", true));
const content = () => row("src").querySelector("[data-project-path]")!;
const click = (detail: number) => {
fireEvent.mouseDown(row("src"), { detail });
fireEvent.click(content(), { detail });
};
click(1);
click(2);
fireEvent.doubleClick(content(), { detail: 2 });
await waitFor(() => expect(rows()).toContain("App.kt"));
click(3);
click(4);
fireEvent.doubleClick(content(), { detail: 4 });
expect(rows()).not.toContain("App.kt");
act(() => setViewOption("singleClickExpand", false));
click(5);
click(6);
expect(rows()).not.toContain("App.kt");
fireEvent.doubleClick(content(), { detail: 6 });
await waitFor(() => expect(rows()).toContain("App.kt"));
});
it("cancels a new file when its name field loses focus", async () => {
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
+2 -1
Переглянути файл
@@ -529,10 +529,11 @@ export function ProjectView() {
const dragged = useRef(false);
const onRowClick = useCallback((node: ProjectNode, e: ReactMouseEvent) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey || e.altKey || e.detail > 1) return;
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey || e.altKey) return;
if (node.placeholder || dragged.current) return;
const { options: o, editing: ed } = useProjectTree.getState();
if (ed) return;
if (e.detail > 1 && !(node.dir && o.singleClickExpand && e.detail % 2 === 1)) return;
if (node.dir) {
if (o.singleClickExpand) toggleExpanded(node);
return;
+1
Переглянути файл
@@ -45,6 +45,7 @@ describe("inspections tree", () => {
it("groups servers by language with seen and configured codes, built-ins by category", () => {
expect(tree.map((g) => g.name)).toEqual([
"Cargo",
"General",
"JavaScript",
"Other",
+1
Переглянути файл
@@ -492,6 +492,7 @@ export const VCS_PAGES: PageSpec[] = [
keywords: ["Test", "git version"],
component: GitExecutableRow,
},
{ kind: "toggle", key: "vcs.git.inlineBlame", label: "Show inline blame for the current line" },
],
},
{
+1 -2
Переглянути файл
@@ -31,7 +31,6 @@ import {
type PaneLayout,
type TerminalTab,
} from "./store";
import { pasteTerminalClipboard } from "./paste";
import { TerminalFindBar } from "./FindBar";
import styles from "./Terminal.module.css";
@@ -103,7 +102,7 @@ function paneMenu(e: MouseEvent, key: string) {
{
label: "Paste",
shortcut: mac ? "⌘V" : "Ctrl+Shift+V",
run: () => void pasteTerminalClipboard((text) => session.paste(text)),
run: () => void session.pasteClipboard(),
},
{ label: "Select All", run: () => session.term.selectAll() },
{ kind: "separator" },
+8 -6
Переглянути файл
@@ -60,14 +60,14 @@ export function findTerminalLinks(text: string): TerminalLink[] {
return links.sort((a, b) => a.start - b.start);
}
/** Resolves `path` against `cwd` (POSIX); `~` expands with `home` when known. */
/** Resolves `path` against `cwd` (POSIX, or Windows drive paths); `~` expands with `home` when known. */
export function resolvePath(path: string, cwd: string, home?: string | null): string {
let p = path;
let p = path.replace(/\\/g, "/");
if (p === "~" || p.startsWith("~/")) {
if (!home) return p;
p = home + p.slice(1);
} else if (!p.startsWith("/")) {
p = `${cwd.replace(/\/+$/, "")}/${p}`;
p = home.replace(/\\/g, "/") + p.slice(1);
} else if (!p.startsWith("/") && !/^[A-Za-z]:\//.test(p)) {
p = `${cwd.replace(/\\/g, "/").replace(/\/+$/, "")}/${p}`;
}
const parts: string[] = [];
for (const seg of p.split("/")) {
@@ -75,5 +75,7 @@ export function resolvePath(path: string, cwd: string, home?: string | null): st
if (seg === "..") parts.pop();
else parts.push(seg);
}
return "/" + parts.join("/");
const joined = parts.join("/");
// A Windows drive prefix is its own root; POSIX results keep the leading slash.
return /^[A-Za-z]:\//.test(joined) ? joined : `/${joined}`;
}
+286 -2
Переглянути файл
@@ -1,9 +1,16 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Terminal } from "@xterm/xterm";
import { commands } from "@/platform/ipc";
import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
import { installTerminalPaste, pasteTerminalClipboard, type RemotePasteTarget } from "./paste";
beforeEach(() => vi.stubGlobal("__TAURI_INTERNALS__", {}));
const notify = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify }) }));
beforeEach(() => {
vi.stubGlobal("__TAURI_INTERNALS__", {});
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
notify.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -78,3 +85,280 @@ it("passes recovered multiline paths through xterm bracketed paste", async () =>
term.dispose();
}
});
function image(buffer: () => Promise<ArrayBuffer> = async () => new Uint8Array([1, 2]).buffer, size = 2): Blob {
return { type: "image/png", size, arrayBuffer: buffer } as Blob;
}
function imageEvent(blob: Blob, text = "") {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => text, files: [blob], types: ["Files"] },
});
return event;
}
function remoteTarget(current = () => true): RemotePasteTarget {
return { id: 42 as RemotePasteTarget["id"], supported: true, current };
}
it.each(["event", "menu"])("rejects oversized %s images before reading or uploading", async (route) => {
const read = vi.fn(async () => new ArrayBuffer(0));
const blob = image(read, 20 * 1024 * 1024 + 1);
const store = vi.spyOn(commands, "termStoreImage");
const paste = vi.fn();
const host = document.createElement("div");
const remove = installTerminalPaste(host, paste, () => remoteTarget());
if (route === "event") {
const event = imageEvent(blob);
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
} else {
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType: async () => blob }] },
});
await pasteTerminalClipboard(paste, () => remoteTarget());
}
await vi.waitFor(() =>
expect(notify).toHaveBeenCalledWith({
level: "error",
title: "Cannot paste image",
body: "Image is too large to paste (limit 20 MB).",
}),
);
expect(read).not.toHaveBeenCalled();
expect(store).not.toHaveBeenCalled();
expect(paste).not.toHaveBeenCalled();
remove();
});
it("allows images at the size limit", async () => {
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.dispatchEvent(imageEvent(image(undefined, 20 * 1024 * 1024)));
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/remote/image.png'"));
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(notify).not.toHaveBeenCalled();
remove();
});
it("claims remote image events before xterm and pastes a quoted path only after upload", async () => {
let finish!: (result: { status: "ok"; data: string }) => void;
const store = vi.spyOn(commands, "termStoreImage").mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.addEventListener("paste", () => paste("xterm"));
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png"));
expect(paste).not.toHaveBeenCalled();
finish({ status: "ok", data: "/tmp/a'b c.png" });
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/tmp/a'\\''b c.png'"));
remove();
});
it("reads an image from the explicit paste menu after text and file recovery", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/stale.png"] });
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
const getType = vi.fn(async () => image());
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType }] },
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(getType).toHaveBeenCalledWith("image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
});
it("recovers remote menu file paths when image clipboard reading is unavailable", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/file.txt"] });
const store = vi.spyOn(commands, "termStoreImage");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "" } });
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(paste).toHaveBeenCalledWith("/local/file.txt");
expect(store).not.toHaveBeenCalled();
});
it("uploads a menu image even if reading clipboard text is rejected", async () => {
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: {
readText: async () => {
throw new Error("no text");
},
read: async () => [{ types: ["image/png"], getType: async () => image() }],
},
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
expect(notify).not.toHaveBeenCalled();
});
it("uploads image events instead of recovering a local image path", async () => {
const list = vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/photo.png"] });
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/photo.png" });
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/remote/photo.png'"));
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(list).not.toHaveBeenCalled();
remove();
});
it("does not upload a menu image when the target changes while reading", async () => {
let valid = true;
let finish!: (value: Blob) => void;
const getType = vi.fn(
() =>
new Promise<Blob>((resolve) => {
finish = resolve;
}),
);
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType }] },
});
const store = vi.spyOn(commands, "termStoreImage");
const paste = vi.fn();
const pending = pasteTerminalClipboard(paste, () => remoteTarget(() => valid));
await vi.waitFor(() => expect(getType).toHaveBeenCalled());
valid = false;
finish(image());
await pending;
expect(store).not.toHaveBeenCalled();
expect(paste).not.toHaveBeenCalled();
});
it.each(["read", "upload", "unsupported"])("reports image %s failure without pasting", async (failure) => {
const store = vi.spyOn(commands, "termStoreImage").mockRejectedValue(new Error("upload failed"));
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => ({ ...remoteTarget(), supported: failure !== "unsupported" }));
host.dispatchEvent(
imageEvent(
image(
failure === "read"
? async () => {
throw new Error("read failed");
}
: undefined,
),
),
);
await vi.waitFor(() => expect(notify).toHaveBeenCalled());
expect(paste).not.toHaveBeenCalled();
if (failure !== "upload") expect(store).not.toHaveBeenCalled();
remove();
});
it.each(["read", "upload"])("ignores an image after its target is replaced during %s", async (stage) => {
let valid = true;
let finishRead!: (value: ArrayBuffer) => void;
let finishUpload!: (value: { status: "ok"; data: string }) => void;
const store = vi.spyOn(commands, "termStoreImage").mockImplementation(
() =>
new Promise((resolve) => {
finishUpload = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget(() => valid));
host.dispatchEvent(
imageEvent(
image(
() =>
new Promise((resolve) => {
finishRead = resolve;
}),
),
),
);
await vi.waitFor(() => expect(finishRead).toBeDefined());
if (stage === "upload") {
finishRead(new Uint8Array([1]).buffer);
await vi.waitFor(() => expect(store).toHaveBeenCalled());
}
valid = false;
if (stage === "read") finishRead(new Uint8Array([1]).buffer);
else finishUpload({ status: "ok", data: "/remote/image.png" });
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(paste).not.toHaveBeenCalled();
if (stage === "read") expect(store).not.toHaveBeenCalled();
remove();
});
it("does not paste after the event handler is disposed during upload", async () => {
let finish!: (value: { status: "ok"; data: string }) => void;
const store = vi.spyOn(commands, "termStoreImage").mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.dispatchEvent(imageEvent(image()));
await vi.waitFor(() => expect(store).toHaveBeenCalled());
remove();
finish({ status: "ok", data: "/remote/image.png" });
await Promise.resolve();
await Promise.resolve();
expect(paste).not.toHaveBeenCalled();
});
it("keeps local image-only file recovery unchanged", async () => {
const list = vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/photo.png"] });
const store = vi.spyOn(commands, "termStoreImage");
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste);
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("/local/photo.png"));
expect(list).toHaveBeenCalled();
expect(store).not.toHaveBeenCalled();
remove();
});
it("leaves local image and remote text events to existing paste handlers", () => {
const store = vi.spyOn(commands, "termStoreImage");
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
const event = imageEvent(image(), "plain");
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
expect(store).not.toHaveBeenCalled();
remove();
const local = installTerminalPaste(host, paste);
const text = imageEvent(image(), "plain");
host.dispatchEvent(text);
expect(text.defaultPrevented).toBe(false);
expect(store).not.toHaveBeenCalled();
local();
});
+85 -6
Переглянути файл
@@ -1,8 +1,50 @@
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
import { call, commands, type TerminalId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
export function installTerminalPaste(host: HTMLElement, paste: (text: string) => void): () => void {
export interface RemotePasteTarget {
id: TerminalId;
supported: boolean;
current: () => boolean;
}
type Target = () => RemotePasteTarget | null;
const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
async function pasteImage(image: Blob, target: RemotePasteTarget, paste: (text: string) => void) {
try {
if (image.size > MAX_IMAGE_BYTES) throw new Error(tx`Image is too large to paste (limit ${20} MB).`);
const data = Array.from(new Uint8Array(await image.arrayBuffer()));
if (!target.current()) return;
if (!target.supported) throw new Error(tx("Remote server does not support image paste."));
const path = await call(commands.termStoreImage(target.id, data, image.type));
if (target.current()) paste(`'${path.replaceAll("'", "'\\''")}'`);
} catch (error) {
if (target.current())
notifications().notify({
level: "error",
title: tx("Cannot paste image"),
body: error instanceof Error ? error.message : String(error),
});
}
}
export function installTerminalPaste(host: HTMLElement, paste: (text: string) => void, getTarget?: Target): () => void {
let alive = true;
const onPaste = (event: ClipboardEvent) => {
const transfer = event.clipboardData;
const target = getTarget?.();
if (!event.defaultPrevented && target && transfer && !transfer.getData("text/plain")) {
const image = Array.from(transfer.files).find((file) => file.type.startsWith("image/"));
if (image) {
event.preventDefault();
event.stopImmediatePropagation();
void pasteImage(image, { ...target, current: () => alive && target.current() }, paste);
return;
}
}
pasteClipboardFiles(event, (text) => {
if (alive) paste(text);
});
@@ -14,11 +56,48 @@ export function installTerminalPaste(host: HTMLElement, paste: (text: string) =>
};
}
export async function pasteTerminalClipboard(paste: (text: string) => void) {
export async function pasteTerminalClipboard(paste: (text: string) => void, getTarget?: Target) {
const target = getTarget?.();
try {
const text = await readClipboardText();
if (text) paste(text);
} catch {
/* Clipboard access may be denied. */
// Native paste preserves clipboard blobs where Clipboard.read() is unavailable.
if (target && document.queryCommandSupported?.("paste") && document.execCommand("paste")) return;
const images =
target && navigator.clipboard?.read
? navigator.clipboard.read().then(
(items) => ({ items }),
(error: unknown) => ({ error }),
)
: null;
const text = target ? ((await navigator.clipboard?.readText().catch(() => "")) ?? "") : await readClipboardText();
if (target && !target.current()) return;
if (text) {
paste(text);
return;
}
if (!target) return;
if (images) {
const result = await images;
if ("error" in result) throw result.error;
if (!target.current()) return;
for (const item of result.items) {
const mime = item.types.find((type) => type.startsWith("image/"));
if (mime) {
const image = await item.getType(mime);
if (target.current()) await pasteImage(image, target, paste);
return;
}
}
}
const paths = await readClipboardText();
if (!target.current()) return;
if (paths) paste(paths);
else if (!images) throw new Error(tx("Clipboard image reading is unavailable."));
} catch (error) {
if (target?.current())
notifications().notify({
level: "error",
title: tx("Cannot paste image"),
body: error instanceof Error ? error.message : String(error),
});
}
}
+74
Переглянути файл
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { findTerminalLinks, type TerminalLink } from "./links";
import { openFileLink } from "./session";
const ipc = vi.hoisted(() => ({
call: vi.fn(async (v: unknown) => v),
commands: { fsReadDir: vi.fn(), findFiles: vi.fn() },
}));
const workbench = vi.hoisted(() => ({
openFile: vi.fn(async () => undefined),
notify: vi.fn(),
}));
vi.mock("@/platform/ipc", () => ({ call: ipc.call, commands: ipc.commands, isTauri: () => true }));
vi.mock("@/workbench/contributions", () => ({
editorService: () => ({ openFile: workbench.openFile }),
notifications: () => ({ notify: workbench.notify }),
OWNS_FILE_DROP: { "data-owner": true },
}));
const fileLink = (text: string): Extract<TerminalLink, { kind: "file" }> => {
const [l] = findTerminalLinks(text);
if (!l || l.kind !== "file") throw new Error(`not a file link: ${text}`);
return l;
};
describe("openFileLink", () => {
beforeEach(() => vi.clearAllMocks());
it("opens the resolved path when the directory lists it", async () => {
ipc.commands.fsReadDir.mockResolvedValue([{ name: "main.php", kind: "file" }]);
await openFileLink(fileLink("a/main.php:2"), "C:\\Users\\me\\proj");
expect(ipc.commands.fsReadDir).toHaveBeenCalledWith("C:/Users/me/proj/a");
expect(workbench.openFile).toHaveBeenCalledWith("C:/Users/me/proj/a/main.php", {
selection: { line: 1, col: 0 },
focus: true,
});
expect(ipc.commands.findFiles).not.toHaveBeenCalled();
});
it("ranks the link's directory over the bare name in the project-wide fallback (#705)", async () => {
ipc.commands.fsReadDir.mockResolvedValue([]);
ipc.commands.findFiles.mockImplementation(async (q: string) =>
q === "a/main.php"
? [
{ path: "/p/b/main.php", relPath: "b/main.php" },
{ path: "/p/a/main.php", relPath: "a/main.php" },
]
: [{ path: "/p/c/main.php", relPath: "c/main.php" }],
);
await openFileLink(fileLink("a/main.php:2"), "/p");
expect(ipc.commands.findFiles).toHaveBeenCalledWith("a/main.php", 5);
expect(workbench.openFile).toHaveBeenCalledWith("/p/a/main.php", {
selection: { line: 1, col: 0 },
focus: true,
});
});
it("falls back to the bare name for a basename-only link", async () => {
ipc.commands.fsReadDir.mockResolvedValue([]);
ipc.commands.findFiles.mockResolvedValue([{ path: "/p/x/main.php", relPath: "x/main.php" }]);
await openFileLink(fileLink("main.php:1"), "/p");
expect(ipc.commands.findFiles).toHaveBeenCalledTimes(1);
expect(workbench.openFile).toHaveBeenCalledWith("/p/x/main.php", { selection: { line: 0, col: 0 }, focus: true });
});
it("warns when nothing matches", async () => {
ipc.commands.fsReadDir.mockResolvedValue([]);
ipc.commands.findFiles.mockResolvedValue([]);
await openFileLink(fileLink("gone.php:1"), "/p");
expect(workbench.openFile).not.toHaveBeenCalled();
expect(workbench.notify).toHaveBeenCalledWith({ level: "warning", title: "File not found", body: "gone.php" });
});
});
+40 -12
Переглянути файл
@@ -17,6 +17,7 @@ import { ImeCommitGate } from "./imeCommit";
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
import { splitCommandLine } from "@/platform/commandLine";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings";
import { editorPrefs } from "@/platform/editorSettings";
import {
@@ -136,25 +137,32 @@ export const LINK_HANDLER: ILinkHandler = {
export async function openFileLink(link: Extract<TerminalLink, { kind: "file" }>, cwd: string) {
const selection = link.line ? { line: link.line - 1, col: Math.max(0, (link.col ?? 1) - 1) } : undefined;
const path = resolvePath(link.path, cwd);
const name = link.path.split("/").pop() ?? link.path;
const rel = link.path.replace(/\\/g, "/");
const name = rel.split("/").pop() ?? rel;
try {
const slash = path.lastIndexOf("/");
const entries = await call(commands.fsReadDir(path.slice(0, slash) || "/"));
const entries = await call(commands.fsReadDir(slash > 0 ? path.slice(0, slash) : "/"));
if (entries.some((e) => e.name === name && e.kind !== "dir")) {
await editorService().openFile(path, { selection, focus: true });
return;
}
} catch {
/* fall back to a project-wide lookup by file name */
/* fall back to a project-wide lookup */
}
try {
const [hit] = await call(commands.findFiles(name, 1));
if (hit && hit.path.endsWith(name)) {
await editorService().openFile(hit.path, { selection, focus: true });
return;
// The basename alone is ambiguous (`a/x.ts` vs `b/x.ts`): rank the link's
// directory part too and verify the hit actually sits on that path, settling
// for a basename match only when the link names no directory.
for (const q of rel === name ? [name] : [rel, name]) {
try {
const hits = await call(commands.findFiles(q, 5));
const hit = hits.find((h) => h.relPath === q || h.relPath.endsWith(`/${q}`));
if (hit) {
await editorService().openFile(hit.path, { selection, focus: true });
return;
}
} catch {
/* ignore */
}
} catch {
/* ignore */
}
notifications().notify({ level: "warning", title: "File not found", body: link.path });
}
@@ -278,7 +286,7 @@ export class TerminalSession {
}),
);
this.disposables.push(
{ dispose: installTerminalPaste(this.host, (text) => this.paste(text)) },
{ dispose: installTerminalPaste(this.host, (text) => this.paste(text), this.remotePasteTarget) },
{ dispose: installTerminalDrop(this.host, (text) => this.paste(text)) },
);
this.host.addEventListener("mousedown", this.onMiddleClick);
@@ -287,9 +295,29 @@ export class TerminalSession {
private onMiddleClick = (e: MouseEvent) => {
if (e.button !== 1 || !workflowSettings().terminal.pasteOnMiddleClick) return;
e.preventDefault();
void pasteTerminalClipboard((text) => this.paste(text));
void this.pasteClipboard();
};
private remotePasteTarget = () => {
const remote = useRemote.getState().session;
const id = this.ptyId;
if (!remote || id === null || this.disposed) return null;
const generation = this.generation;
return {
id,
supported: remote.commands.includes("term_store_image"),
current: () =>
!this.disposed &&
this.ptyId === id &&
this.generation === generation &&
useRemote.getState().session === remote,
};
};
pasteClipboard() {
if (this.remotePasteTarget()) this.focus();
return pasteTerminalClipboard((text) => this.paste(text), this.remotePasteTarget);
}
/** Applies Settings › Tools › Terminal changes to a live session. */
applySettings(t: TerminalSettingsValid) {
const font = fontFor(t);
+8
Переглянути файл
@@ -96,6 +96,14 @@ describe("terminal links", () => {
expect(resolvePath("/abs/c.ts", "/p")).toBe("/abs/c.ts");
expect(resolvePath("~/d.ts", "/p", "/Users/me")).toBe("/Users/me/d.ts");
});
it("resolves paths against a Windows cwd (#705)", () => {
expect(resolvePath("a/main.php", "C:\\Users\\me\\proj")).toBe("C:/Users/me/proj/a/main.php");
expect(resolvePath("a\\main.php", "C:/Users/me/proj")).toBe("C:/Users/me/proj/a/main.php");
expect(resolvePath("C:\\abs\\d.ts", "C:/p")).toBe("C:/abs/d.ts");
expect(resolvePath("~/e.ts", "C:/p", "C:\\Users\\me")).toBe("C:/Users/me/e.ts");
expect(resolvePath("../f.ts", "C:/p/web")).toBe("C:/p/f.ts");
});
});
describe("terminal keys", () => {
+47 -1
Переглянути файл
@@ -7,7 +7,7 @@ import { useTasks } from "@/workbench/tasks";
import { MemoryToolsBackend, sampleTools, setToolsBackend } from "../backend";
import { cancelInstall, installTool, refreshTools, uninstallTool, useTools } from "../store";
import { filterTools, LanguageServersPage } from "../LanguageServersPage";
import { installMissingServerPrompts, missingKey, promptInstall } from "../missing";
import { installMissingServerPrompts, installServerWarningPrompts, missingKey, promptInstall } from "../missing";
import { resetTestForm, stagedFor, TestSettingsForm } from "./settingsForm";
type Note = Parameters<NotificationService["notify"]>[0];
@@ -273,3 +273,49 @@ describe("tools.install action", () => {
}
});
});
describe("language server capability warning", () => {
const event = {
type: "languageServerWarning",
name: "clangd",
message:
"Apple's clangd does not run clang-tidy, so checks from .clang-tidy are not shown. Install clangd (LLVM) to get them.",
installTool: "clangd",
} as const;
it("offers a managed replacement for system clangd once and restarts it after installation", async () => {
backend.tools.push({
...sampleTools()[0]!,
name: "clangd",
displayName: "clangd",
command: "clangd",
status: "onPath",
path: "/usr/bin/clangd",
languages: ["C", "C++", "Objective-C", "Objective-C++"],
});
const off = installServerWarningPrompts();
try {
emitLocalIdeEvent(event);
emitLocalIdeEvent(event);
await waitFor(() => expect(notes).toHaveLength(1));
expect(notes[0]).toMatchObject({ title: "clangd", level: "warning", sticky: true, body: event.message });
expect(notes[0]!.actions!.map((a) => a.label)).toEqual(["Install", "Language Servers…"]);
notes[0]!.actions![0]!.run();
await waitFor(() => expect(backend.restarted).toEqual(["clangd"]));
expect(notes.at(-1)).toMatchObject({ title: "clangd installed", key: notes[0]!.key });
} finally {
off();
}
});
it("keeps the Settings action when the tool cannot be installed", async () => {
const off = installServerWarningPrompts();
try {
emitLocalIdeEvent(event);
await waitFor(() => expect(notes).toHaveLength(1));
expect(notes[0]!.actions!.map((a) => a.label)).toEqual(["Language Servers…"]);
} finally {
off();
}
});
});
+2 -1
Переглянути файл
@@ -9,7 +9,7 @@ import { lazyComponent } from "@/ui";
import { executeAction, registerActions } from "@/platform/actions";
import { registerSettingsPage } from "@/workbench/contributions";
import { installJdkPrompts, registerJdkActions } from "./jdk";
import { installMissingServerPrompts, promptInstall } from "./missing";
import { installMissingServerPrompts, installServerWarningPrompts, promptInstall } from "./missing";
import { installTool, refreshTools, SETTINGS_PAGE_ID, toolByName, useTools } from "./store";
/** The Language Servers page (also used by the Settings window). */
@@ -79,6 +79,7 @@ export function activate(): () => void {
},
]),
installMissingServerPrompts(),
installServerWarningPrompts(),
registerJdkActions(),
installJdkPrompts(),
];
+28
Переглянути файл
@@ -56,3 +56,31 @@ export function installMissingServerPrompts(): () => void {
void promptInstall(e.name).catch(() => {});
});
}
/** A system server that lacks a capability can be replaced by the managed tool. */
export function installServerWarningPrompts(): () => void {
const prompted = new Set<string>();
return onIdeEvent("languageServerWarning", (e) => {
const key = `lsp-warning-${e.name}-${e.installTool}`;
if (prompted.has(key)) return;
prompted.add(key);
void (async () => {
if (!useTools.getState().loaded) await refreshTools();
const tool = toolByName(e.installTool);
notifications().notify({
group: "lsp",
level: "warning",
title: e.name,
body: tx(e.message),
key,
sticky: true,
actions: [
...(tool?.canInstall
? [{ label: "Install", run: () => void installTool(e.installTool, { notificationKey: key }) }]
: []),
{ label: "Language Servers…", run: () => void executeAction("file.settings", SETTINGS_PAGE_ID) },
],
});
})();
});
}
+255
Переглянути файл
@@ -0,0 +1,255 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView, activateHover, closeHoverTooltips, hasHoverTooltips } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BlameLine, Settings } from "@/bindings";
import { HEAVY_LIMIT, _emitEditorEvent } from "@/editor/api";
import { useProject } from "@/platform/project";
import { useI18n } from "@/platform/i18n";
import { formatInlineBlame, inlineBlame, relativeBlameDate } from "../inlineBlame";
import { useVcs } from "../store";
const mocks = vi.hoisted(() => ({ blame: vi.fn(), file: vi.fn(), log: vi.fn(), action: vi.fn() }));
vi.mock("@/platform/actions", async (original) => ({
...(await original<typeof import("@/platform/actions")>()),
executeAction: mocks.action,
}));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: { ...actual.commands, vcsBlame: mocks.blame, vcsFileAt: mocks.file, vcsLog: mocks.log },
};
});
const now = Date.UTC(2026, 10, 2, 12);
const alice: BlameLine = {
commit: "a".repeat(40),
author: "Alice Smith",
timeMs: now - 86400_000,
summary: "First line",
};
const bob: BlameLine = { commit: "b".repeat(40), author: "Bob Jones", timeMs: now - 3600_000, summary: "Second line" };
const uncommitted: BlameLine = { commit: "0".repeat(40), author: "Not Committed Yet", timeMs: now, summary: "" };
const ctx = { doc: 1, path: "/repo/file.ts", language: "typescript", uiMode: null, readOnly: false };
let view: EditorView | undefined;
function settings(enabled: boolean) {
useProject.setState({ settings: { vcs: { git: { inlineBlame: enabled } } } as Settings });
}
function editor(doc = "one\ntwo\nthree", context = ctx) {
view = new EditorView({
parent: document.body,
state: EditorState.create({ doc, extensions: [inlineBlame(context)] }),
});
return view;
}
const hint = () => view?.dom.querySelector<HTMLElement>(".cm-vcs-inline-blame");
const tick = () => vi.advanceTimersByTimeAsync(300);
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(now);
vi.clearAllMocks();
useI18n.setState({ locale: "en", texts: {} });
settings(true);
useVcs.setState({ available: true, roots: ["/repo"], statusLoaded: true, byPath: new Map(), version: 0 });
mocks.file.mockResolvedValue({ status: "ok", data: "one\ntwo\nthree" });
mocks.blame.mockResolvedValue({ status: "ok", data: [alice, bob, uncommitted] });
});
afterEach(() => {
view?.destroy();
view = undefined;
useProject.setState({ settings: null });
vi.useRealTimers();
});
describe("inline blame formatting", () => {
it("formats authors, relative dates, summaries and missing dates", () => {
expect(formatInlineBlame(alice, now)).toBe("Alice Smith, 1 day ago · First line");
expect(formatInlineBlame({ ...bob, timeMs: null, summary: "Long\nmessage" }, now)).toBe("Bob Jones · Long message");
expect(formatInlineBlame(uncommitted, now)).toBe("You, now · Uncommitted changes");
expect(relativeBlameDate(now + 1000, now)).toBe("now");
expect(relativeBlameDate(now - 120_000, now)).toBe("2 minutes ago");
expect(relativeBlameDate(now - 400 * 86400_000, now)).toBe("1 year ago");
});
});
describe("current line decoration", () => {
it("debounces caret moves and reuses blame for the same document version", async () => {
const v = editor();
await vi.advanceTimersByTimeAsync(299);
expect(mocks.blame).not.toHaveBeenCalled();
v.dispatch({ selection: { anchor: 4 } });
await vi.advanceTimersByTimeAsync(299);
expect(mocks.blame).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(hint()?.textContent).toContain("Bob Jones");
v.dispatch({ selection: { anchor: 0 } });
expect(hint()).toBeNull();
await tick();
expect(hint()?.textContent).toContain("Alice Smith");
expect(mocks.blame).toHaveBeenCalledTimes(1);
expect(mocks.file).toHaveBeenCalledTimes(1);
expect(hint()?.contentEditable).toBe("false");
hint()?.click();
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", alice.commit);
});
it("uses only the primary selection and hides multiline selections", async () => {
const v = editor();
v.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(4)], 1) });
await tick();
expect(hint()?.textContent).toContain("Bob Jones");
v.dispatch({ selection: { anchor: 0, head: 5 } });
await tick();
expect(hint()).toBeNull();
v.dispatch({ selection: { anchor: 4, head: 6 } });
await tick();
expect(hint()?.textContent).toContain("Bob Jones");
});
it("loads and caches the full commit message on hover and closes it on caret movement", async () => {
const message = "First line\n\nThe complete commit body.";
mocks.log.mockResolvedValue({ status: "ok", data: [{ message }] });
const v = editor();
await tick();
activateHover(v, 3, 1);
await vi.advanceTimersByTimeAsync(0);
expect(hasHoverTooltips(v.state)).toBe(true);
const tooltip = v.dom.querySelector(".cm-vcs-inline-blame-tooltip");
expect(tooltip?.textContent).toContain(message);
expect(tooltip?.textContent).toContain(alice.author);
expect(tooltip?.textContent).toContain(alice.commit);
expect(tooltip?.textContent).toContain(new Date(alice.timeMs!).toLocaleString());
v.dispatch({ effects: closeHoverTooltips });
activateHover(v, 3, 1);
await vi.advanceTimersByTimeAsync(0);
expect(mocks.log).toHaveBeenCalledTimes(1);
v.dispatch({ selection: { anchor: 4 } });
expect(hasHoverTooltips(v.state)).toBe(false);
});
it("closes an open tooltip when the setting is disabled", async () => {
mocks.log.mockResolvedValue({ status: "ok", data: [{ message: "Full message" }] });
const v = editor();
await tick();
activateHover(v, 3, 1);
await vi.advanceTimersByTimeAsync(0);
expect(hasHoverTooltips(v.state)).toBe(true);
settings(false);
expect(hasHoverTooltips(v.state)).toBe(false);
});
it("refetches edits, saves and VCS refreshes", async () => {
const v = editor();
await tick();
mocks.blame.mockResolvedValue({ status: "ok", data: [uncommitted, bob, uncommitted] });
v.dispatch({ changes: { from: 0, insert: "x" } });
expect(hint()).toBeNull();
await tick();
expect(mocks.blame).toHaveBeenLastCalledWith(ctx.path, "xone\ntwo\nthree", null);
expect(hint()?.textContent).toBe("You, now · Uncommitted changes");
_emitEditorEvent({ type: "docSaved", doc: 1, path: ctx.path });
await tick();
useVcs.setState({ version: 1 });
await tick();
expect(mocks.blame).toHaveBeenCalledTimes(4);
});
it("discards a response from an older document version", async () => {
let resolve!: (result: { status: "ok"; data: BlameLine[] }) => void;
mocks.blame.mockReturnValueOnce(new Promise((done) => (resolve = done)));
const v = editor();
await tick();
v.dispatch({ changes: { from: 0, insert: "x" } });
resolve({ status: "ok", data: [alice] });
await vi.advanceTimersByTimeAsync(0);
expect(hint()).toBeNull();
mocks.blame.mockResolvedValue({ status: "ok", data: [uncommitted] });
await tick();
expect(hint()?.textContent).toBe("You, now · Uncommitted changes");
});
it("coalesces an in-flight blame when the caret moves", async () => {
let resolve!: (result: { status: "ok"; data: BlameLine[] }) => void;
mocks.blame.mockReturnValueOnce(new Promise((done) => (resolve = done)));
const v = editor();
await tick();
v.dispatch({ selection: { anchor: 4 } });
await tick();
resolve({ status: "ok", data: [alice, bob] });
await vi.advanceTimersByTimeAsync(0);
expect(hint()?.textContent).toContain("Bob Jones");
expect(mocks.blame).toHaveBeenCalledTimes(1);
});
it("responds to the setting immediately", async () => {
settings(false);
editor();
await tick();
expect(mocks.blame).not.toHaveBeenCalled();
settings(true);
await tick();
expect(hint()).not.toBeNull();
settings(false);
expect(hint()).toBeNull();
await tick();
expect(mocks.blame).toHaveBeenCalledTimes(1);
});
it("ignores a pending response after disabling", async () => {
let resolve!: (result: { status: "ok"; data: BlameLine[] }) => void;
mocks.blame.mockReturnValueOnce(new Promise((done) => (resolve = done)));
editor();
await tick();
settings(false);
resolve({ status: "ok", data: [alice] });
await vi.advanceTimersByTimeAsync(0);
expect(hint()).toBeNull();
await tick();
expect(hint()).toBeNull();
});
it.each(["untracked", "ignored"] as const)("skips %s paths", async (unstaged) => {
useVcs.setState({
byPath: new Map([[ctx.path, { path: ctx.path, relPath: "file.ts", unstaged, staged: null, renamedFrom: null }]]),
});
editor();
await tick();
expect(mocks.file).not.toHaveBeenCalled();
expect(hint()).toBeNull();
});
it("skips ignored paths missing from status and HEAD", async () => {
mocks.file.mockResolvedValue({ status: "ok", data: null });
editor();
await tick();
expect(mocks.blame).not.toHaveBeenCalled();
expect(hint()).toBeNull();
});
it("skips paths outside repositories", async () => {
editor("one", { ...ctx, path: "/elsewhere/file.ts" });
await tick();
expect(mocks.file).not.toHaveBeenCalled();
});
it("skips large, virtual and read-only documents", async () => {
editor("x".repeat(HEAVY_LIMIT + 1));
await tick();
expect(mocks.file).not.toHaveBeenCalled();
expect(inlineBlame({ ...ctx, virtual: true })).toEqual([]);
expect(inlineBlame({ ...ctx, readOnly: true })).toEqual([]);
});
it("cancels pending work when the view is destroyed", async () => {
editor().destroy();
view = undefined;
await tick();
expect(mocks.file).not.toHaveBeenCalled();
});
});
+2 -1
Переглянути файл
@@ -23,6 +23,7 @@ import { registerHistoryActions, trackOperationContext } from "./historyActions"
import { registerLogPaneActions } from "./logPaneActions";
import { controlLabel, controlOperation, inProgress } from "./operations";
import { annotationsShown, blameSlot } from "./blame";
import { inlineBlame } from "./inlineBlame";
import { BranchWidget, useBranchesPopup } from "./BranchWidget";
import { showConflictsDialog } from "./conflictsUi";
import { registerCompareActions } from "./compare";
@@ -212,7 +213,7 @@ export function activate(): () => void {
registerEditorContribution({
id: "vcs.changeMarkers",
order: 60,
extensions: (ctx) => [changeMarkers(ctx), blameSlot()],
extensions: (ctx) => [changeMarkers(ctx), blameSlot(), inlineBlame(ctx)],
}),
registerMenuGroup({
id: "vcs.gutter",
+281
Переглянути файл
@@ -0,0 +1,281 @@
import { StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import {
Decoration,
EditorView,
ViewPlugin,
WidgetType,
hoverTooltip,
type DecorationSet,
type ViewUpdate,
} from "@codemirror/view";
import type { BlameLine } from "@/bindings";
import { HEAVY_LIMIT, onEditorEvent, type EditorDocContext } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { tx, useI18n } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { isUncommitted } from "./blame";
import { repoOf, statusOf, useVcs } from "./store";
export function relativeBlameDate(timeMs: number | null, now = Date.now()): string {
if (timeMs === null) return "";
const seconds = Math.max(0, (now - timeMs) / 1000);
const units = [
["year", 365 * 86400],
["month", 30 * 86400],
["day", 86400],
["hour", 3600],
["minute", 60],
] as const;
const unit = units.find(([, size]) => seconds >= size);
return unit
? new Intl.RelativeTimeFormat(useI18n.getState().locale, { numeric: "always" }).format(
-Math.floor(seconds / unit[1]),
unit[0],
)
: tx("now");
}
export function formatInlineBlame(line: BlameLine, now = Date.now()): string {
if (isUncommitted(line)) return tx("You, now · Uncommitted changes");
const date = relativeBlameDate(line.timeMs, now);
return `${line.author}${date ? `, ${date}` : ""} · ${line.summary.replace(/\s+/g, " ")}`;
}
/** Only the current document version is retained, including its in-flight request. */
class BlameCache {
private doc: Text | undefined;
private pending: Promise<BlameLine[]> | undefined;
clear() {
this.doc = undefined;
this.pending = undefined;
}
get(doc: Text, load: () => Promise<BlameLine[]>): Promise<BlameLine[]> {
if (doc !== this.doc || !this.pending) {
this.doc = doc;
this.pending = load();
}
return this.pending;
}
}
class BlameWidget extends WidgetType {
constructor(readonly line: BlameLine) {
super();
}
eq(other: BlameWidget) {
return formatInlineBlame(other.line) === formatInlineBlame(this.line) && other.line.commit === this.line.commit;
}
toDOM() {
const el = document.createElement("span");
el.className = "cm-vcs-inline-blame";
el.textContent = formatInlineBlame(this.line);
el.contentEditable = "false";
if (!isUncommitted(this.line)) {
el.setAttribute("role", "button");
el.tabIndex = 0;
const open = () => void executeAction("vcs.showCommit", this.line.commit);
el.addEventListener("mousedown", (e) => e.preventDefault());
el.addEventListener("click", open);
el.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
open();
}
});
}
return el;
}
}
const setInlineBlame = StateEffect.define<DecorationSet>();
const inlineBlameField = StateField.define<DecorationSet>({
create: () => Decoration.none,
update(value, tr) {
if (tr.docChanged || tr.selection) return Decoration.none;
for (const effect of tr.effects) if (effect.is(setInlineBlame)) return effect.value;
return value;
},
provide: (field) => EditorView.decorations.from(field),
});
export function inlineBlame(ctx: EditorDocContext): Extension {
if (ctx.virtual || ctx.readOnly) return [];
const plugin = ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
private readonly cache = new BlameCache();
private readonly messages = new Map<string, Promise<string>>();
private readonly off: (() => void)[];
private generation = 0;
private destroyed = false;
line: BlameLine | undefined;
constructor(readonly view: EditorView) {
this.off = [
useVcs.subscribe((s, prev) => {
if (s.version !== prev.version) this.invalidate();
}),
onEditorEvent((e) => {
if (e.type === "docSaved" && e.path === ctx.path) this.invalidate();
}),
onWorkflowSettingsChange(
(s) => s.vcs.git.inlineBlame,
() => this.invalidate(),
),
useI18n.subscribe(() => this.invalidate()),
];
this.schedule();
}
private enabled() {
const vcs = useVcs.getState();
const status = statusOf(ctx.path);
return (
workflowSettings().vcs.git.inlineBlame &&
isTauri() &&
vcs.available &&
vcs.statusLoaded &&
!!repoOf(ctx.path) &&
status?.unstaged !== "untracked" &&
status?.unstaged !== "ignored" &&
this.view.state.doc.length <= HEAVY_LIMIT
);
}
private clear() {
this.line = undefined;
if (this.view.state.field(inlineBlameField).size)
this.view.dispatch({ effects: setInlineBlame.of(Decoration.none) });
}
private invalidate() {
this.cache.clear();
this.clear();
this.schedule();
}
update(update: ViewUpdate) {
if (update.docChanged) this.cache.clear();
if (update.docChanged || update.selectionSet) {
this.line = undefined;
this.schedule();
}
}
private schedule() {
clearTimeout(this.timer);
++this.generation;
this.timer = setTimeout(() => void this.refresh(), 300);
}
private async refresh() {
if (this.destroyed || !this.enabled()) return;
const { doc, selection } = this.view.state;
const caret = doc.lineAt(selection.main.head);
if (doc.lineAt(selection.main.from).number !== doc.lineAt(selection.main.to).number) return;
const generation = this.generation;
try {
const lines = await this.cache.get(doc, async () => {
// Blame also returns synthetic entries for paths absent from HEAD (ignored / new files).
if ((await call(commands.vcsFileAt(ctx.path, "HEAD"))) === null) return [];
return call(commands.vcsBlame(ctx.path, doc.toString(), null));
});
if (this.destroyed || generation !== this.generation || doc !== this.view.state.doc || !this.enabled())
return;
this.line = lines[caret.number - 1];
if (this.line) {
const widget = Decoration.widget({ widget: new BlameWidget(this.line), side: 1 }).range(caret.to);
this.view.dispatch({ effects: setInlineBlame.of(Decoration.set([widget])) });
}
} catch {
// Repository removed, unborn HEAD, inaccessible file, etc.: leave the line undecorated.
}
}
message(line: BlameLine): Promise<string> {
if (isUncommitted(line)) return Promise.resolve(tx("You, now · Uncommitted changes"));
let message = this.messages.get(line.commit);
if (!message) {
message = call(
commands.vcsLog(repoOf(ctx.path), {
branch: line.commit,
path: null,
author: null,
text: null,
skip: 0,
limit: 1,
}),
).then(
(commits) => commits[0]?.message ?? line.summary,
() => line.summary,
);
if (this.messages.size >= 100) this.messages.delete(this.messages.keys().next().value!);
this.messages.set(line.commit, message);
}
return message;
}
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
this.cache.clear();
this.off.forEach((off) => off());
}
},
);
return [
inlineBlameField,
plugin,
hoverTooltip(
async (view, pos, side) => {
const instance = view.plugin(plugin);
const line = instance?.line;
const end = view.state.doc.lineAt(view.state.selection.main.head).to;
if (!instance || !line || pos !== end || side < 0) return null;
const message = await instance.message(line);
if (view.plugin(plugin)?.line !== line) return null;
return {
pos: end,
above: true,
create() {
const dom = document.createElement("div");
dom.className = "cm-vcs-inline-blame-tooltip";
dom.textContent = isUncommitted(line)
? message
: `${line.author}\n${line.timeMs === null ? "" : new Date(line.timeMs).toLocaleString()}\n${line.commit}\n\n${message}`;
return { dom };
},
};
},
{
hideOnChange: true,
hideOn: (tr) => tr.effects.some((effect) => effect.is(setInlineBlame)),
},
),
EditorView.baseTheme({
".cm-vcs-inline-blame": {
color: "var(--fg-inlay)",
marginLeft: "3ch",
display: "inline-block",
maxWidth: "min(60ch, 50vw)",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
verticalAlign: "bottom",
userSelect: "none",
},
'.cm-vcs-inline-blame[role="button"]': { cursor: "pointer" },
".cm-vcs-inline-blame-tooltip": {
padding: "8px 12px",
maxWidth: "min(70ch, 80vw)",
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
},
}),
];
}
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { commands, type FileProbe } from "@/platform/ipc";
import { resolveFileEditor } from "@/workbench/contributions";
import { activate } from "./index";
let dispose: (() => void) | undefined;
afterEach(() => {
dispose?.();
dispose = undefined;
vi.restoreAllMocks();
});
describe("file probes", () => {
it.each([false, true])("shares an in-flight probe without caching its result (binary: %s)", async (binary) => {
let finish!: (result: { status: "ok"; data: FileProbe }) => void;
const pending = new Promise<{ status: "ok"; data: FileProbe }>((resolve) => {
finish = resolve;
});
const probe = vi.spyOn(commands, "fsProbe").mockReturnValue(pending);
dispose = activate();
const first = resolveFileEditor("/p/a.ts");
const second = resolveFileEditor("/p/a.ts");
await vi.waitFor(() => expect(probe).toHaveBeenCalled());
finish({ status: "ok", data: { size: 12, binary, tooLarge: false } });
const resolutions = await Promise.all([first, second]);
expect(probe).toHaveBeenCalledTimes(1);
expect(resolutions.map((r) => r?.input.kind ?? "file")).toEqual(binary ? ["binary", "binary"] : ["file", "file"]);
if (binary) expect(resolutions[0]).not.toBe(resolutions[1]);
probe.mockResolvedValue({ status: "ok", data: { size: 20, binary: !binary, tooLarge: false } });
expect((await resolveFileEditor("/p/a.ts"))?.input.kind ?? "file").toBe(binary ? "file" : "binary");
expect(probe).toHaveBeenCalledTimes(2);
});
it("retries a failed probe", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const probe = vi
.spyOn(commands, "fsProbe")
.mockRejectedValueOnce(new Error("read failed"))
.mockResolvedValue({ status: "ok", data: { size: 20, binary: true, tooLarge: false } });
dispose = activate();
expect(await resolveFileEditor("/p/a.ts")).toBeNull();
expect((await resolveFileEditor("/p/a.ts"))?.input.kind).toBe("binary");
expect(probe).toHaveBeenCalledTimes(2);
});
it("probes different files independently", async () => {
const probe = vi.spyOn(commands, "fsProbe").mockResolvedValue({
status: "ok",
data: { size: 20, binary: false, tooLarge: false },
});
dispose = activate();
await Promise.all([resolveFileEditor("/p/a.ts"), resolveFileEditor("/p/b.ts")]);
expect(probe.mock.calls).toEqual([["/p/a.ts"], ["/p/b.ts"]]);
});
});
+8 -2
Переглянути файл
@@ -5,7 +5,7 @@
* Editor / Editor and Preview / Preview layouts around the text editor.
*/
import { registerActions, type Action } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { call, commands, type FileProbe } from "@/platform/ipc";
import { getContext } from "@/platform/context";
import { basename } from "@/platform/project";
import { fileIconName, lazyComponent } from "@/ui";
@@ -78,6 +78,7 @@ function markdownActions(): Action[] {
}
export function activate(): () => void {
const probes = new Map<string, Promise<FileProbe>>();
const disposers = [
registerEditorKind({ kind: IMAGE_KIND, component: ImageViewer, title: titleOf, icon: iconOf }),
registerEditorKind({ kind: BINARY_KIND, component: HexViewer, title: titleOf, icon: iconOf }),
@@ -90,7 +91,12 @@ export function activate(): () => void {
id: "viewers.hex",
order: 50,
resolve: async (path) => {
const probe = await call(commands.fsProbe(path));
let pending = probes.get(path);
if (!pending) {
pending = call(commands.fsProbe(path)).finally(() => probes.delete(path));
probes.set(path, pending);
}
const probe = await pending;
return wantsHexView(probe) ? binaryInput(path, probe) : null;
},
}),
+1
Переглянути файл
@@ -77,6 +77,7 @@ export const CLIENT_SETTINGS_KEYS = [
"run.confirmTerminate",
"run.showOnStart",
"vcs.showDirtyDirectories",
"vcs.git.inlineBlame",
"vcs.git.showPushDialog",
"vcs.git.pushDialogOnlyProtected",
"vcs.git.combineStashAndShelf",
+18 -7
Переглянути файл
@@ -1,4 +1,6 @@
{
"The language server JDK ({path}) must be a full JDK with jdk.compiler, jdk.jdi and jdk.unsupported for Java language support and debugging. jdtls needs JDK {version} or newer. Download JDK {version}, choose a full JDK in {setting}, or set it to Auto.": "语言服务器 JDK({path})必须是包含 jdk.compiler、jdk.jdi 和 jdk.unsupported 的完整 JDK,才能支持 Java 语言功能和调试。jdtls 需要 JDK {version} 或更高版本。请下载 JDK {version},在 {setting} 中选择完整 JDK,或设为自动。",
"Apple's clangd does not run clang-tidy, so checks from .clang-tidy are not shown. Install clangd (LLVM) to get them.": "Apple 的 clangd 不运行 clang-tidy,因此不会显示 .clang-tidy 中配置的检查。请安装 clangd(LLVM)以启用这些检查。",
"Newer dependency version available": "有更新的依赖版本可用",
"Reports newer crate versions that Cargo.toml requirements do not already allow.": "报告 Cargo.toml 版本要求尚未允许的较新 crate 版本。",
"Update to {latest}": "更新至 {latest}",
@@ -1613,16 +1615,18 @@
"Install Missing Tool": "安装缺失的工具",
"Prettier formatting failed": "Prettier 格式化失败",
"Prettier formatting timed out": "Prettier 格式化超时",
"Prettier does not support selection formatting for this language; formatted the whole file": "Prettier 不支持此语言的选区格式化,已格式化整个文件",
"oxfmt formatting failed": "oxfmt 格式化失败",
"oxfmt formatting timed out": "oxfmt 格式化超时",
"{name} does not support selection formatting for this language; formatted the whole file": "{name} 不支持此语言的选区格式化,已格式化整个文件",
"Formatting timed out": "格式化超时",
"Prettier: Node.js is required": "Prettier:需要 Node.js",
"{name}: Node.js is required": "{name}:需要 Node.js",
"Formatter": "格式化工具",
"JSON with Comments": "带注释的 JSON",
"Unknown external formatter: {tool}": "未知的外部格式化工具:{tool}",
"Prettier: package has no CLI entry point": "Prettier:软件包未提供命令行入口",
"Prettier: CLI does not exist: {path}": "Prettier:命令行程序不存在:{path}",
"Prettier: file has no directory": "Prettier:文件路径不含目录",
"Prettier: {error}": "Prettier:{error}",
"{name}: package has no CLI entry point": "{name}:软件包未提供命令行入口",
"{name}: CLI does not exist: {path}": "{name}:命令行程序不存在:{path}",
"{name}: file has no directory": "{name}:文件路径不含目录",
"{name}: {error}": "{name}:{error}",
"Reformat File": "重新格式化文件",
"Reformat code": "重新格式化代码",
"Reformat code on save": "保存时重新格式化代码",
@@ -5490,5 +5494,12 @@
"Invalid .NET project path": ".NET 项目路径无效",
".NET launch profile '{profile_name}' is missing or is not a Project profile": ".NET 启动配置“{profile_name}”不存在或不是 Project 类型",
".NET output resolution timed out": ".NET 构建产物路径查询超时",
".NET build output is missing; run dotnet build before debugging": ".NET 构建产物不存在,请在调试前运行 dotnet build"
".NET build output is missing; run dotnet build before debugging": ".NET 构建产物不存在,请在调试前运行 dotnet build",
"Cannot paste image": "无法粘贴图片",
"Remote server does not support image paste.": "远程服务器不支持粘贴图片。",
"Clipboard image reading is unavailable.": "无法读取剪贴板图片。",
"Image is too large to paste (limit {limit} MB).": "图片过大,无法粘贴(上限 {limit} MB)。",
"Show inline blame for the current line": "为当前行显示内联 Git Blame",
"You, now · Uncommitted changes": "你,刚刚 · 未提交的更改",
"now": "刚刚"
}
+6
Переглянути файл
@@ -3,6 +3,12 @@ import { splitCommandLine } from "./commandLine";
import { DEFAULT_WORKFLOW, validateWorkflow } from "./workflowSettings";
describe("validateWorkflow", () => {
it("defaults inline blame off and accepts only boolean values", () => {
expect(DEFAULT_WORKFLOW.vcs.git.inlineBlame).toBe(false);
expect(validateWorkflow({ vcs: { git: { inlineBlame: true } } }).vcs.git.inlineBlame).toBe(true);
expect(validateWorkflow({ vcs: { git: { inlineBlame: "true" } } }).vcs.git.inlineBlame).toBe(false);
});
it("falls back to defaults for missing or malformed values", () => {
expect(validateWorkflow(undefined)).toEqual(DEFAULT_WORKFLOW);
const v = validateWorkflow({
+3
Переглянути файл
@@ -18,6 +18,7 @@ export interface IssueLinkValid {
}
export interface GitSettingsValid {
inlineBlame: boolean;
executable: string;
updateMethod: UpdateMethod;
autoUpdateOnPushRejected: boolean;
@@ -183,6 +184,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
limitHistory: true,
historyLimit: 1000,
git: {
inlineBlame: false,
executable: "",
updateMethod: "merge",
autoUpdateOnPushRejected: false,
@@ -309,6 +311,7 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
limitHistory: bool(v.limitHistory, d.limitHistory),
historyLimit: num(v.historyLimit, d.historyLimit, L.historyLimit, true),
git: {
inlineBlame: bool(g.inlineBlame, d.git.inlineBlame),
executable: text(g.executable, d.git.executable).trim(),
updateMethod: oneOf(g.updateMethod, ["merge", "rebase"] as const, d.git.updateMethod),
autoUpdateOnPushRejected: bool(g.autoUpdateOnPushRejected, d.git.autoUpdateOnPushRejected),
+5 -1
Переглянути файл
@@ -130,6 +130,8 @@ const ICONS = {
"file-gdscript": "openidea/fileTypes/gdscript",
"file-godot": "openidea/fileTypes/godot",
"file-gdshader": "openidea/fileTypes/gdshader",
"file-asciidoc": "openidea/fileTypes/asciidoc",
"file-d": "openidea/fileTypes/d",
"file-dart": "openidea/fileTypes/dart",
"file-elixir": "openidea/fileTypes/elixir",
"file-erlang": "openidea/fileTypes/erlang",
@@ -825,7 +827,7 @@ const EXT_ICONS = table({
"file-rst": "rst",
"file-yaml": "yaml yml",
"file-toml": "toml",
"file-text": "txt text adoc",
"file-text": "txt text",
"file-log": "log",
"file-csv": "csv tsv",
"file-html": "html htm shtml html.tmpl",
@@ -878,6 +880,8 @@ const EXT_ICONS = table({
"file-gdscript": "gd",
"file-godot": "tscn tres godot import",
"file-gdshader": "gdshader gdshaderinc",
"file-asciidoc": "adoc asciidoc",
"file-d": "d di",
"file-dart": "dart",
"file-elixir": "ex exs",
"file-erlang": "erl hrl escript app.src",
+3
Переглянути файл
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#C94F6D"/><path d="M4.5 11.5L8 4L11.5 11.5" stroke="#2B2D30" stroke-linecap="round"/><path d="M5.9 8.5H10.1" stroke="#2B2D30"/></g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 399 B

+3
Переглянути файл
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#E0708A"/><path d="M4.5 11.5L8 4L11.5 11.5" stroke="#2B2D30" stroke-linecap="round"/><path d="M5.9 8.5H10.1" stroke="#2B2D30"/></g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 399 B

+3
Переглянути файл
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#BA4032"/><path transform="translate(4 3.5)" d="M0.5 0.5V8.5" stroke="#2B2D30"/><path transform="translate(4 3.5)" d="M0.5 0.5H2.7C5.8 0.5 7.4 2.2 7.4 4.5C7.4 6.8 5.8 8.5 2.7 8.5H0.5" stroke="#2B2D30"/></g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 474 B

+3
Переглянути файл
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#CE5B4C"/><path transform="translate(4 3.5)" d="M0.5 0.5V8.5" stroke="#2B2D30"/><path transform="translate(4 3.5)" d="M0.5 0.5H2.7C5.8 0.5 7.4 2.2 7.4 4.5C7.4 6.8 5.8 8.5 2.7 8.5H0.5" stroke="#2B2D30"/></g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 474 B