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

...
Автор SHA1 Повідомлення Дата
l0ng-ai ff01f23114 fix(libraries): write only SDKs in angle brackets under External Libraries
Every External Libraries group was shown as < name >, so a Maven or Gradle
project listed hundreds of bracketed dependencies. As in IntelliJ IDEA,
only SDKs (JDK, Python, Ruby, Go, Rust) keep the brackets; dependency
groups such as Maven: g:a:v and Gradle: g:a:v are shown as they are.

Refs #1977
2026-11-11 21:34:28 +08:00
Vadim LazukтаInf1mum f04658612f fix(plugins): plugins reach a project window group's member files (#2739)
In a project window group plugins only saw the container: projects() and project-of() reported the container root, read/write/find refused member paths, Find in Files dropped member matches and the document indexer skipped member documents. The plugin host now treats the members like the editor and language servers do: projects() lists them, project-of() resolves to the deepest member, the sandbox path checks accept paths inside any member (files outside every root stay refused), and find-files, symbol search and the indexer cover member files. No WIT change.

Fixes #2506

Co-authored-by: Inf1mum <[email protected]>
2026-11-11 21:31:23 +08:00
Qingтаqtvbwfn d5cb379cae feat(services): show only services the user added (#2740)
The Services tool window listed services nobody added: an injected Docker connection, Spring Boot by default and every configuration that had ever run. Now only added types, connections and registries are listed, removal takes effect at once, an untouched injected Docker connection is dropped from older docker.json files, and the detail pane has a single scrollbar with console controls only (Run/Debug/Stop stay on the window toolbar).

Co-authored-by: qtvbwfn <[email protected]>
2026-11-11 21:28:41 +08:00
Muuтаmuutot e3a818b607 feat(color-scheme): group Python color attributes as PyCharm does (#2735)
The Python page of Settings › Editor › Color Scheme listed its attributes flat. They now follow PyCharm's tree (String › f-string, Docstring, Braces and Operators, Functions, Parameters, Special names…), in its order; only display names change, so .icls files and existing overrides keep working.

Co-authored-by: muutot <[email protected]>
2026-11-11 21:26:31 +08:00
Vadim LazukтаInf1mum 0b1872937a fix(lsp): hint when Vue 2 Options API template navigation lacks strictFunctionTypes (#2728)
Vue 2.7's Options API types only infer methods and computed into this under strictFunctionTypes; without it template go-to-definition and hover return nothing. When vue-language-server serves a Vue 2 project whose jsconfig/tsconfig lacks the option (and doesn't extend a base), the IDE now shows a warning with the fix.

Fixes #1163

Co-authored-by: Inf1mum <[email protected]>
2026-11-11 21:25:01 +08:00
Vadim LazukтаInf1mum f11cd361a7 fix(color-scheme): import .xml scheme files and tolerate real-world IDEA variants (#2731)
The import chooser only offered .icls, so schemes distributed as .xml (Material Theme UI) could not be picked. It now offers .xml too, and the parser accepts a BOM, an encoding declaration, a DOCTYPE, a scheme wrapped in a settings export and a scheme without a name (named after its file); a rejected file shows the reason.

Fixes #2714

Co-authored-by: Inf1mum <[email protected]>
2026-11-11 21:23:38 +08:00
Vadim LazukтаInf1mum 7034fe1640 fix(debugger): offer to reinstall Delve when it is too old for the Go toolchain (#2730)
A Delve older than the Go toolchain refuses the launch with "Version of Delve is too old for Go version …". The debugger now recognises it and offers Reinstall and Debug, which runs the managed go install …/dlv@latest and starts the session again.

Fixes #2721

Co-authored-by: Inf1mum <[email protected]>
2026-11-11 21:23:03 +08:00
Vadim LazukтаInf1mum fc264d3f5c fix(ui): stop double-clicking tree rows from selecting label text (#2726)
The second press of a double-click started the browser's word selection, which in the virtualized tree spilled onto the rows an expanding folder had just inserted. Tree cancels the default of repeated presses; the first press still selects and dblclick still activates.

Fixes #2713

Co-authored-by: Inf1mum <[email protected]>
2026-11-11 21:22:02 +08:00
Vadim LazukтаInf1mum 8e90341b3a feat(build-tools): a Skip Tests toggle for the Gradle tool window (#2734)
The Gradle tool window gets an optional Skip Tests toggle (off by default, per project): task runs and saved configurations started from the tree get -x test, unless the command line already excludes test or the build has no test task (where -x test would fail the run). A run that skips tests is not marked as a test run.

Fixes #2688

Co-authored-by: Inf1mum <[email protected]>
2026-11-11 21:20:58 +08:00
l0ng-ai 3644956755 feat(terminal): activate the project's conda environment in new terminals (#2742)
Activate virtualenv only handled venvs, so a conda project interpreter left new terminals in (base). New terminals now run conda activate <prefix> through the installation's shell hook (cmd, PowerShell, bash, zsh, POSIX sh, fish), finding the installation from the env itself, the parent of envs/, CONDA_EXE or PATH.

Fixes #2697
2026-11-11 21:18:24 +08:00
l0ng-ai 90e7e3162e feat(mcp): run the IDE's tools without confirmation in brave mode (#2741)
Settings › Agents › IDE MCP Server gets Run tools without confirmation (brave mode): builds, run configurations and the other tools that change a project start without asking, so an unattended agent isn't left waiting on a confirmation. Read from the IDE's own settings only; the project layer already refuses mcpServer.*.

Fixes #2660
2026-11-11 21:17:24 +08:00
Yann 833ae4c3c4 feat(editor): add and remove UTF-8 BOM (#2717)
The encoding status menu of a UTF-8 file gets Add UTF-8 BOM / Remove UTF-8 BOM, and the status bar shows "UTF-8 BOM" for a file that has one. The change marks the document modified and is written on save (at once with auto-save).

Co-authored-by: YannABC <[email protected]>
2026-11-11 21:00:48 +08:00
Elmir Abkerimov 584baa3f71 feat(editor): code vision position per hint and a "no usages" switch (#2716)
Settings › Editor › Inlay Hints › Code Vision gets a Position for Usages and for Code author — Top (a row above the declaration, the default) or Right (after the end of the declaration's first line) — placed per hint, and Show "no usages" (on by default) to leave the usages hint off declarations nothing uses. The options sit under the hint they belong to.

Co-authored-by: w4terlaw <[email protected]>
2026-11-11 20:58:46 +08:00
Elmir Abkerimov 98010e6513 fix(editor): start every selected row at the text's left edge (#2724)
CodeMirror starts selection rows that run through a line start at the left padding rounded down to whole pixels, and a row that starts at a character at the real padding; with the 2.5px inset the two were half a pixel apart, a visible step on Retina. Rows that start at the real edge now move to the rounded one, and the sliver drawn on a line the selection ends at the start of is dropped after the rows are grown.

Co-authored-by: w4terlaw <[email protected]>
2026-11-11 20:56:38 +08:00
Muuтаmuutot a3640f655f fix(perf): name language server memory rows by their workspace root (#2702)
The memory indicator labelled every language server row with the project folder, so with additional content roots the servers of each root showed as identical rows. Each row now names the server's own workspace root.

Co-authored-by: muutot <[email protected]>
2026-11-11 20:56:07 +08:00
Shohruh Ismoilovтаshohruh-genius 8aaa7daf83 fix(project): keep workspace project icons stable on removal (#2699)
Removing a member from a workspace reset every detected project type, so the remaining members briefly showed folder icons and fell back to name order. The cached types of members still in the same workspace are kept while the rescan runs.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-11 20:54:16 +08:00
Bin 6a9a970df4 fix(editor): use JSX comments for expression children (#2703)
Ctrl+/ on a JSX expression child such as {label} read the JavaScript comment tokens at the opening brace; it now wraps the line in the surrounding JSX comment pair, {/* … */}, and takes it back out.

Co-authored-by: ffgenius <[email protected]>
2026-11-11 20:53:53 +08:00
l0ng-ai a309b7e6fa fix(java): import Gradle builds on the JVM the IDE's Gradle runs use (#2736)
With Gradle JVM at Project JDK the IDE's Gradle runs use the project JDK (or an installed JDK the Gradle version supports), but the jdtls import ran Gradle on jdtls's own JDK 21, so Gradle < 8.5 failed to import and no dependency resolved. The import now takes JAVA_HOME and GRADLE_USER_HOME from gradle_build_env for Gradle builds.

Refs #2681
2026-11-11 20:52:49 +08:00
95 змінених файлів з 2583 додано та 519 видалено

No files matched your search

+20
Переглянути файл
@@ -333,6 +333,23 @@ pub struct InlayHintsSettings {
pub code_vision_usages: bool,
/// Code vision: last author of a declaration (VCS blame) beside its usages.
pub code_vision_author: bool,
/// Code vision: "no usages" on declarations nothing uses (IDEA shows it; clicking searches everywhere).
pub code_vision_no_usages: bool,
/// Code vision: where the usages go, above the declaration or at the end of its line.
pub code_vision_usages_position: CodeVisionPosition,
/// Code vision: where the author goes, above the declaration or at the end of its line.
pub code_vision_author_position: CodeVisionPosition,
}
/// Editor › Inlay Hints › Code Vision position (IDEA's "Default position for metrics").
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum CodeVisionPosition {
/// A row of its own above the declaration.
#[default]
Top,
/// After the end of the declaration's first line.
Right,
}
impl Default for InlayHintsSettings {
@@ -344,6 +361,9 @@ impl Default for InlayHintsSettings {
disabled_languages: Vec::new(),
code_vision_usages: true,
code_vision_author: true,
code_vision_no_usages: true,
code_vision_usages_position: CodeVisionPosition::Top,
code_vision_author_position: CodeVisionPosition::Top,
}
}
}
+3
Переглянути файл
@@ -261,6 +261,9 @@ pub enum WhileRunning {
pub struct McpServerSettings {
/// Serve the tools on 127.0.0.1 while the IDE runs.
pub enabled: bool,
/// Run the tools that change the project or start processes without asking first
/// (IDEA's brave mode). Read from the IDE's own settings only, never a project's.
pub run_without_confirmation: bool,
}
/// Absent profiles retain automatic discovery for existing projects.
+12
Переглянути файл
@@ -342,4 +342,16 @@ mod tests {
assert_eq!(error_message(&msg), "cannot find a.py");
assert_eq!(error_message(&json!({"message": "nope"})), "nope");
}
#[test]
fn a_failed_launch_response_keeps_delves_too_old_error_verbatim() {
// The UI's repair offer keys off this exact wording (`missingAdapter`), so the
// conversion to the IPC error must not fold it into a generic message.
let message = "Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 \
(maximum supported version 1.26, suppress this error with --check-go-version=false)";
let e = ide_core::IdeError::from(DapError::Failed { command: "launch".into(), message: message.into() });
assert_eq!(e.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(e.message, format!("launch failed: {message}"));
assert!(e.message.contains("Version of Delve is too old for Go version go1.27.0"));
}
}
+44 -17
Переглянути файл
@@ -136,24 +136,19 @@ pub struct DockerRegistry {
pub username: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerSettings {
#[serde(default = "default_connections")]
#[serde(default)]
pub connections: Vec<DockerConnection>,
#[serde(default)]
pub registries: Vec<DockerRegistry>,
}
impl Default for DockerSettings {
fn default() -> Self {
Self { connections: default_connections(), registries: Vec::new() }
}
}
/// Before anything is configured the CLI's own daemon is shown, as before connections existed.
fn default_connections() -> Vec<DockerConnection> {
vec![DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default }]
/// Whether `c` is the connection older versions injected when nothing was configured:
/// Services lists only connections the user added, so this one is dropped on load.
fn is_injected_default(c: &DockerConnection) -> bool {
c.id == "default" && c.name == "Docker" && c.endpoint == DockerEndpoint::Default
}
const SETTINGS_FILE: &str = "docker.json";
@@ -161,10 +156,17 @@ const PASSWORDS_FILE: &str = "docker-passwords.json";
pub fn load_settings(data_dir: &Path) -> DockerSettings {
match std::fs::read(data_dir.join(SETTINGS_FILE)) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!("{SETTINGS_FILE}: {e}");
DockerSettings::default()
}),
// A file written before the opt-in Services rework carries the injected default
// (saved along with a registry or another connection); drop it unless edited.
Ok(bytes) => serde_json::from_slice(&bytes)
.map(|mut s: DockerSettings| {
s.connections.retain(|c| !is_injected_default(c));
s
})
.unwrap_or_else(|e| {
tracing::warn!("{SETTINGS_FILE}: {e}");
DockerSettings::default()
}),
Err(_) => DockerSettings::default(),
}
}
@@ -373,7 +375,8 @@ mod tests {
fn settings_round_trip_and_passwords() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
assert_eq!(load_settings(dir).connections[0].endpoint, DockerEndpoint::Default);
// Nothing configured: no connection is invented.
assert!(load_settings(dir).connections.is_empty());
let settings = DockerSettings {
connections: vec![DockerConnection {
id: "c1".into(),
@@ -395,8 +398,32 @@ mod tests {
assert!(auth_for(dir, "postgres").is_none());
save_settings(dir, &DockerSettings { registries: Vec::new(), ..settings }).unwrap();
assert_eq!(registry_password(dir, "r1"), None);
// An empty list stays empty (the default connection is only for a missing file).
// An empty list stays empty.
save_settings(dir, &DockerSettings { connections: Vec::new(), registries: Vec::new() }).unwrap();
assert!(load_settings(dir).connections.is_empty());
}
#[test]
fn load_drops_the_injected_default_connection() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let injected =
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
let registry =
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
save_settings(dir, &DockerSettings { connections: vec![injected()], registries: vec![registry.clone()] })
.unwrap();
let loaded = load_settings(dir);
assert!(loaded.connections.is_empty());
assert_eq!(loaded.registries, vec![registry]);
// A connection the user renamed or re-pointed stays theirs.
let renamed = DockerConnection { name: "Local engine".into(), ..injected() };
save_settings(dir, &DockerSettings { connections: vec![renamed.clone()], registries: Vec::new() }).unwrap();
assert_eq!(load_settings(dir).connections, vec![renamed]);
let repointed =
DockerConnection { endpoint: DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }, ..injected() };
save_settings(dir, &DockerSettings { connections: vec![repointed.clone()], registries: Vec::new() }).unwrap();
assert_eq!(load_settings(dir).connections, vec![repointed]);
}
}
+5
Переглянути файл
@@ -51,7 +51,12 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// Asks the user before a tool changes the project or starts a process, unless brave mode
/// is on — read from the IDE's own settings only, which a project's settings can't set.
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
if self.host.global_settings.effective().mcp_server.run_without_confirmation {
return self.project.require_trust();
}
self.ask(ide_core::event::McpUiRequest::Confirm {
client: self.client.clone(),
tool: self.tool.clone(),
+10 -3
Переглянути файл
@@ -5,7 +5,7 @@ use crate::rpc::Dispatcher;
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentInfo, HistoryEntry};
use ide_workspace::{DocumentEncoding, DocumentInfo, HistoryEntry};
use std::path::PathBuf;
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool,
@@ -29,18 +29,24 @@ pub async fn doc_ui_mode(host: &Host, window: &str, path: PathBuf) -> IdeResult<
blocking(move || Ok(project.documents.ui_mode_of(&path))).await
}
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state.
pub async fn doc_set_encoding(
host: &Host,
window: &str,
doc: DocId,
encoding: String,
reload: bool,
) -> IdeResult<String> {
) -> IdeResult<DocumentEncoding> {
let project = host.project(window)?;
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
}
/// Adds or removes the BOM on a UTF-8 document; the change is written on save.
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
let project = host.project(window)?;
host.blocking(move || project.documents.set_bom(doc, has_bom)).await
}
pub fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_ending: LineEnding) -> IdeResult<()> {
host.project(window)?.documents.set_line_ending(doc, line_ending)
}
@@ -175,6 +181,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("doc_set_encoding", |c| async move {
doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?).await
});
d.add("doc_set_bom", |c| async move { doc_set_bom(&c.host, &c.window, c.arg("doc")?, c.arg("hasBom")?).await });
d.add("doc_set_line_ending", |c| async move {
blocking(move || doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)).await
});
+139 -34
Переглянути файл
@@ -71,6 +71,12 @@ pub trait PluginWorkspace: Send + Sync {
/// Roots of the open projects.
fn projects(&self) -> Vec<PathBuf>;
/// Roots of the workspace members attached to the project at `root` (a
/// project window group's folders, as the editor and LSP resolve them).
/// Empty for a plain project.
fn member_roots(&self, _root: &Path) -> Vec<PathBuf> {
Vec::new()
}
/// Unsaved text of the open document at `path`.
fn buffer_text(&self, path: &Path) -> Option<String>;
/// A window's unsaved text, with the normal project overlay as fallback.
@@ -2019,6 +2025,10 @@ impl HostApi for PluginApi {
self.shared.workspace().map(|w| w.projects()).unwrap_or_default()
}
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
self.shared.workspace().map(|w| w.member_roots(root)).unwrap_or_default()
}
fn buffer_text(&self, path: &Path) -> Option<String> {
self.shared.workspace()?.buffer_text(path)
}
@@ -2159,23 +2169,29 @@ impl HostApi for PluginApi {
out.sort();
return Ok(out);
}
// A project window group's members are project scope too (their files
// are in the group's index, and a group root holds none of them).
let mut roots = vec![root.to_path_buf()];
roots.extend(self.member_roots(root));
let mut out = Vec::new();
for (n, entry) in ignore::WalkBuilder::new(root)
.hidden(false)
.filter_entry(|e| e.file_name() != ".git")
.build()
.flatten()
.enumerate()
{
if n >= MAX_WALK || out.len() >= limit {
break;
}
if !entry.file_type().is_some_and(|t| t.is_file()) {
continue;
}
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
if matcher.is_match(rel) {
out.push(to_ipc(entry.path()));
'walk: for root in &roots {
for (n, entry) in ignore::WalkBuilder::new(root)
.hidden(false)
.filter_entry(|e| e.file_name() != ".git")
.build()
.flatten()
.enumerate()
{
if n >= MAX_WALK || out.len() >= limit {
break 'walk;
}
if !entry.file_type().is_some_and(|t| t.is_file()) {
continue;
}
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
if matcher.is_match(rel) {
out.push(to_ipc(entry.path()));
}
}
}
out.sort();
@@ -2892,11 +2908,26 @@ impl HostWorkspace {
.and_then(|w| host.project(w).ok())
.filter(|p| p.root == root)
.or_else(|| host.windows_for_root(root).first().and_then(|w| host.project(w).ok()))
// A project window group's member root: its files belong to the
// group's project, like everywhere else in the editor.
.or_else(|| {
host.projects()
.into_iter()
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| m.as_path() == root))
})
}
fn projects(&self) -> Vec<Arc<crate::project::Project>> {
self.0.upgrade().map(|h| h.projects()).unwrap_or_default()
}
/// The open project whose workspace group contains `root` (the group root
/// itself matches `p.root == root` and needs no member lookup).
fn project_covering(&self, root: &Path) -> Option<Arc<crate::project::Project>> {
self.projects().into_iter().find(|p| {
p.root == root || crate::project::workspace_member_roots(&p.root).iter().any(|m| m.as_path() == root)
})
}
/// The project holding an open document at `path`, and its id.
fn open_document(&self, path: &Path) -> Option<(Arc<crate::project::Project>, ide_core::DocId)> {
self.projects().into_iter().find_map(|p| p.documents.by_path(path).map(|doc| (p, doc)))
@@ -2986,6 +3017,10 @@ impl PluginWorkspace for HostWorkspace {
) -> Result<ide_plugin::TextSearch, HostError> {
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
let project = self.project_for(client, root).ok_or_else(|| HostError::NotFound("project closed".into()))?;
// Matches must land in the project root or, for a project window group,
// in any of its members.
let mut roots = vec![root.to_path_buf()];
roots.extend(crate::project::workspace_member_roots(root));
if limit == 0 {
return Ok(ide_plugin::TextSearch::default());
}
@@ -3015,8 +3050,9 @@ impl PluginWorkspace for HostWorkspace {
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
// Restrict project.read to the project root, including symlink targets.
let Ok(path) = ide_plugin::resolve_in_root(root, &to_ipc(&file.path.0)) else {
// Restrict project.read to the project root and its workspace
// members, including symlink targets.
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &to_ipc(&file.path.0)) else {
continue;
};
let text = project.documents.text_of(&path).or_else(|| {
@@ -3082,12 +3118,19 @@ impl PluginWorkspace for HostWorkspace {
}
fn projects(&self) -> Vec<PathBuf> {
let mut roots: Vec<PathBuf> = HostWorkspace::projects(self).iter().map(|p| p.root.clone()).collect();
let mut roots: Vec<PathBuf> = HostWorkspace::projects(self)
.iter()
.flat_map(|p| std::iter::once(p.root.clone()).chain(crate::project::workspace_member_roots(&p.root)))
.collect();
roots.sort();
roots.dedup();
roots
}
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
crate::project::workspace_member_roots(root)
}
fn buffer_text(&self, path: &Path) -> Option<String> {
HostWorkspace::projects(self).iter().find_map(|p| p.documents.text_of(path))
}
@@ -3098,9 +3141,9 @@ impl PluginWorkspace for HostWorkspace {
}
fn indexed_files(&self, root: &Path, matches: &dyn Fn(&Path) -> bool, limit: usize) -> Option<Vec<PathBuf>> {
// The index of the project rooted at `root` (a workspace member's files are in its own).
let project = HostWorkspace::projects(self).into_iter().find(|p| p.root == root)?;
project.index.files_matching(root, matches, limit)
// The index covering `root`: the project rooted there, or the workspace
// group project whose member it is (a member's files are in the group's).
HostWorkspace::project_covering(self, root)?.index.files_matching(root, matches, limit)
}
fn symbols(
@@ -3111,9 +3154,7 @@ impl PluginWorkspace for HostWorkspace {
cancel: &CancellationToken,
deadline: Instant,
) -> Result<Vec<ide_plugin::SymbolInfo>, HostError> {
let project = HostWorkspace::projects(self)
.into_iter()
.find(|p| p.root == root)
let project = HostWorkspace::project_covering(self, root)
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?;
let stopped = || cancel.is_cancelled() || Instant::now() >= deadline;
let interrupted = || {
@@ -3123,15 +3164,13 @@ impl PluginWorkspace for HostWorkspace {
HostError::Failed("symbol search timed out".into())
}
};
// The symbols of the requested root and, for a project window group, of
// its members (a member's symbols are in the group's index).
let members = crate::project::workspace_member_roots(root);
let in_scope = |path: &Path| path.starts_with(root) || members.iter().any(|m| path.starts_with(m));
let symbols = project
.index
.find_symbols_until(
query,
ide_index::SymbolFilter::All,
limit.min(1000),
&|path| path.starts_with(root),
&stopped,
)
.find_symbols_until(query, ide_index::SymbolFilter::All, limit.min(1000), &in_scope, &stopped)
.ok_or_else(interrupted)?;
let mut out = Vec::new();
for s in symbols {
@@ -3173,7 +3212,8 @@ impl PluginWorkspace for HostWorkspace {
}
fn trusted(&self, root: &Path) -> bool {
HostWorkspace::projects(self).iter().any(|p| p.root == root && p.is_trusted())
// A workspace member is as trusted as the group's project it was opened with.
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
}
fn project_of(&self, window: &str) -> Option<PathBuf> {
@@ -3198,6 +3238,12 @@ impl PluginWorkspace for HostWorkspace {
.iter()
.filter(|p| path.starts_with(&p.root))
.max_by_key(|p| p.root.as_os_str().len())
// A project window group's member files report through the group's project.
.or_else(|| {
projects
.iter()
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| path.starts_with(m)))
})
.ok_or_else(|| HostError::Invalid(format!("{} is not in an open project", path.display())))?;
project.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.to_path_buf().into(),
@@ -3212,15 +3258,25 @@ impl PluginWorkspace for HostWorkspace {
.into_iter()
.filter(|p| path.starts_with(&p.root))
.max_by_key(|p| p.root.as_os_str().len())
.or_else(|| {
HostWorkspace::projects(self)
.into_iter()
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| path.starts_with(m)))
})
.and_then(|p| p.vcs_encoding(path, None).ok())
.unwrap_or_else(|| encoding_rs::UTF_8.into())
}
fn plugin_settings(&self, plugin: &str, root: Option<&Path>) -> serde_json::Map<String, serde_json::Value> {
let Some(host) = self.0.upgrade() else { return serde_json::Map::new() };
// A member root reads the settings of the group's project, like the
// group's own root does.
let settings = match root.and_then(|r| host.projects().into_iter().find(|p| p.root == r)) {
Some(p) => p.settings.effective(),
None => host.global_settings.effective(),
None => match root.map(|r| HostWorkspace::project_covering(self, r)) {
Some(Some(p)) => p.settings.effective(),
_ => host.global_settings.effective(),
},
};
settings.plugins.get(plugin).cloned().unwrap_or_default()
}
@@ -3526,6 +3582,55 @@ mod tests {
);
}
/// A workspace whose container root has no files: the member holds them.
struct Members(PathBuf, Vec<PathBuf>);
impl PluginWorkspace for Members {
fn projects(&self) -> Vec<PathBuf> {
vec![self.0.clone()]
}
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
if root == self.0 { self.1.clone() } else { Vec::new() }
}
fn buffer_text(&self, _: &Path) -> Option<String> {
None
}
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
Err(HostError::Stale)
}
fn trusted(&self, _: &Path) -> bool {
true
}
fn project_of(&self, _: &str) -> Option<PathBuf> {
None
}
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
Ok(())
}
}
#[test]
fn find_files_cover_workspace_members() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (root, member) = (base.join("workspace"), base.join("member"));
std::fs::create_dir_all(root.join(".openidea")).unwrap();
std::fs::create_dir_all(member.join("src")).unwrap();
std::fs::write(root.join(".openidea/workspace.json"), "{}").unwrap();
std::fs::write(member.join("src/UserMapper.xml"), "<mapper/>").unwrap();
let api = api(&root, Arc::default());
*api.shared.workspace.write() = Some(Arc::new(Members(root.clone(), vec![member.clone()])));
// The container holds no sources: the member's files are project scope.
assert_eq!(api.find_files(&root, "**/*Mapper.xml", 10).unwrap(), [to_ipc(&member.join("src/UserMapper.xml"))]);
// A member root lists its own files, like any project root.
assert_eq!(api.find_files(&member, "src/*.xml", 10).unwrap(), [to_ipc(&member.join("src/UserMapper.xml"))]);
// And a path outside the group is never listed.
std::fs::write(base.join("OutsideMapper.xml"), "<mapper/>").unwrap();
assert!(api.find_files(&root, "**/*Mapper.xml", 10).unwrap().len() == 1);
}
#[test]
fn process_environment_only_adds_variables() {
let tmp = tempfile::tempdir().unwrap();
+9 -2
Переглянути файл
@@ -27,8 +27,12 @@ pub async fn plugin_navigation_files(
if files.len() > 20_000 {
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
}
// A project window group's members are project scope: their files are
// in the group's index (the group root holds none of them).
let members = crate::project::workspace_member_roots(&project.root);
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
Ok(NavigationFiles {
paths: files.into_iter().filter(|p| p.starts_with(&project.root)).map(Into::into).collect(),
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
indexing,
extensions,
})
@@ -64,11 +68,14 @@ pub async fn plugin_navigation_index(
if !project.is_trusted() {
return Err(IdeError::unavailable("project is not trusted"));
}
// A project window group's members are project scope.
let mut roots = vec![project.root.clone()];
roots.extend(crate::project::workspace_member_roots(&project.root));
for path in paths {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(path) = ide_plugin::resolve_in_root(&project.root, &path.to_string_lossy()) else {
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else {
continue;
};
let extensions = plugins.navigation_extensions(&project.root);
+5 -1
Переглянути файл
@@ -204,7 +204,11 @@ impl PluginHost {
if text.len() > MAX_DOCUMENT_BYTES {
return Err(IdeError::invalid("navigation document is too large"));
}
let real = ide_plugin::resolve_in_root(root, &path.to_string_lossy()).map_err(IdeError::invalid)?;
// A project window group's members are project scope: a member's file
// is indexed into the group's graph like any file of the group root.
let mut roots = vec![root.to_path_buf()];
roots.extend(crate::project::workspace_member_roots(root));
let real = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()).map_err(IdeError::invalid)?;
if real != path {
return Err(IdeError::invalid("navigation requires a canonical project path"));
}
+14 -1
Переглянути файл
@@ -246,7 +246,7 @@ impl Host {
&bundles,
lombok.jar(),
);
ide_sdk::apply::configure_gradle_runtime(cfg, root, &effective);
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
ide_sdk::jdtls::launch_directly(cfg);
}
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
@@ -1188,6 +1188,19 @@ fn index_roots(root: &Path, folders: Vec<PathBuf>) -> ide_index::IndexRoots {
ide_index::IndexRoots { include_root: !container, folders: folders.into_iter().filter(|p| p != root).collect() }
}
/// The member roots of an explicit workspace container (empty for a plain
/// project): how the editor and the language servers resolve a file's own
/// project in a project window group. Also the roots the plugin surface may
/// reach into — see `plugins::api`.
pub(crate) fn workspace_member_roots(root: &Path) -> Vec<PathBuf> {
ide_workspace::workspace::Workspace::load(root)
.ok()
.flatten()
.filter(|w| w.is_container(root))
.map(|w| w.projects)
.unwrap_or_default()
}
/// Workspace members in manifest order, or extra Project Structure directories and the
/// Gradle project folders outside the project as of the last sync (`build_cache`).
fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec<PathBuf> {
+37
Переглянути файл
@@ -416,3 +416,40 @@ async fn rust_references_and_rename_through_mcp() {
assert!(project.documents.text_snapshot(doc.id).unwrap().text.contains("format_amount"));
assert!(std::fs::read_to_string(h.root.join("src/main.rs")).unwrap().contains("format_amount"));
}
#[tokio::test(flavor = "multi_thread")]
async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let p = h.host.project("main").unwrap();
// A project's own settings can't turn the confirmations off.
let project_layer =
p.settings.set(ide_workspace::SettingsScope::Project, "mcpServer.runWithoutConfirmation", json!(true));
assert!(project_layer.is_err());
let denied = h.error("build_project", json!({}));
let answer = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, answer);
assert!(error.contains("denied by the user"), "{error}");
h.events.lock().unwrap().clear();
h.host
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
.unwrap();
let (host, root) = (h.host.clone(), h.root.clone());
let result = tokio::time::timeout(
std::time::Duration::from_secs(60),
tokio::task::spawn_blocking(move || {
Registry::new(host).call(&root, "build_project", "{}", CancellationToken::new())
}),
)
.await
.expect("ran without waiting for an answer")
.unwrap();
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
+239
Переглянути файл
@@ -8,6 +8,7 @@
use ide_core::error::ErrorKind;
use ide_core::ipc_path::to_ipc;
use ide_host::plugins::*;
use ide_host::{Host, HostConfig};
use ide_plugin::{EditorContext, HostError, Invocation, Limits};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
@@ -6335,3 +6336,241 @@ fn api14_stage3_terminal_calls_are_denied_without_process_grants() {
f.host.set_capability("execution", "process:execution-tool", false).unwrap();
assert!(f.run("execution", "terminal", None).unwrap_err().contains("not granted"));
}
// ─── Project window groups ────────────────────────────────────────────────────
// A group's container root holds only `.openidea` metadata; the files live in
// the member projects. The plugin surface reaches them like the editor and the
// language servers do.
/// A real host over a project window group with the members `alpha` (holding a
/// nested `inner` member, for deepest resolution) and `beta`.
struct GroupFixture {
base: PathBuf,
host: Arc<Host>,
plugins: Arc<PluginHost>,
root: PathBuf,
alpha: PathBuf,
inner: PathBuf,
beta: PathBuf,
_runtime: tokio::runtime::Runtime,
_tmp: tempfile::TempDir,
}
impl GroupFixture {
fn new() -> Self {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (root, alpha, beta) = (base.join("workspace"), base.join("alpha"), base.join("beta"));
let inner = alpha.join("inner");
for dir in [alpha.join("src"), inner.join("mappers"), beta.join("src")] {
std::fs::create_dir_all(dir).unwrap();
}
ide_workspace::workspace::Workspace::save(
&root,
"Group",
vec![alpha.clone(), inner.clone(), beta.clone()],
true,
)
.unwrap();
std::fs::write(alpha.join("src/needle.php"), "alpha needle\n").unwrap();
std::fs::write(inner.join("mappers/route.idx"), "def route:item\nref route:item\n").unwrap();
std::fs::write(beta.join("src/Notes.txt"), "beta needle\n").unwrap();
std::fs::write(base.join("secret.txt"), "top secret").unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: runtime.handle().clone(),
project_environment: false,
}));
for dir in [&root, &alpha, &beta] {
host.trust.decide(dir, true, false).unwrap();
}
{
let _guard = runtime.enter();
let project = host.open_project("main", &root).unwrap();
assert!(project.index.wait_idle(Duration::from_secs(30)));
}
let plugins = Arc::new(
PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
);
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
plugins.set_project_policy(Arc::new(|_| true));
Self { base, host, plugins, root, alpha, inner, beta, _runtime: runtime, _tmp: tmp }
}
/// Runs an installed plugin's `command` with `root` (default: the group
/// container) as the invoking project.
fn run(&self, id: &str, command: &str, arg: Option<&str>, root: Option<&Path>) -> Result<Option<String>, String> {
let inv = Invocation {
client: Some("main".into()),
workspace_root: Some(dunce::canonicalize(root.unwrap_or(&self.root)).unwrap()),
..Default::default()
};
self.plugins.run_command(id, command, arg, inv).map_err(|e| e.message)
}
/// Installs `dir` with everything granted.
fn install(&self, dir: &Path) {
self.plugins.install_from_dir(dir, &Consent::all()).unwrap();
}
/// The roots the plugin surface lists, sorted and deduplicated.
fn listed_roots(&self) -> Vec<PathBuf> {
HostWorkspace(Arc::downgrade(&self.host)).projects()
}
}
impl Drop for GroupFixture {
fn drop(&mut self) {
self.host.close_project("main");
}
}
/// `projects()` lists the members with their own roots, and the member roots of
/// the container are exactly the workspace manifest's.
#[test]
fn projects_list_the_workspace_members() {
let f = GroupFixture::new();
assert_eq!(
f.listed_roots(),
[f.alpha.clone(), f.inner.clone(), f.beta.clone(), f.root.clone()]
.iter()
.map(|p| dunce::canonicalize(p).unwrap())
.collect::<Vec<_>>()
);
assert_eq!(
HostWorkspace(Arc::downgrade(&f.host)).member_roots(&f.root),
[f.alpha.clone(), f.inner.clone(), f.beta.clone()]
.iter()
.map(|p| dunce::canonicalize(p).unwrap())
.collect::<Vec<_>>()
);
// A member has no members of its own.
assert!(HostWorkspace(Arc::downgrade(&f.host)).member_roots(&f.alpha).is_empty());
}
/// `project-of(path)` resolves to the deepest member project containing the
/// path, where the container and every member appear.
#[test]
fn project_of_resolves_to_the_deepest_workspace_member() {
let f = GroupFixture::new();
f.install(&sample("path-events"));
let project =
|path: &Path| f.run("test.path-events", "project", Some(path.to_str().unwrap()), None).unwrap().unwrap();
assert_eq!(project(&f.alpha.join("src/needle.php")), to_ipc(&f.alpha));
// The nested member, not its containing member.
assert_eq!(project(&f.inner.join("mappers/route.idx")), to_ipc(&f.inner));
assert_eq!(project(&f.beta.join("src/Notes.txt")), to_ipc(&f.beta));
// The container itself is still a project.
assert_eq!(project(&f.root), to_ipc(&f.root));
// And a path in no project resolves to none.
assert!(
f.run("test.path-events", "project", Some(f.base.join("secret.txt").to_str().unwrap()), None)
.unwrap()
.is_none()
);
}
/// `project.read` and `project.write` reach the member files through the
/// group's project, and never leave the group's roots.
#[test]
fn project_reads_and_writes_reach_workspace_members() {
let f = GroupFixture::new();
f.install(&misbehave_with(f._tmp.path(), "misbehave-group-writer", "project.write"));
let notes = f.beta.join("src/Notes.txt");
assert_eq!(f.run("misbehave", "read", Some(notes.to_str().unwrap()), None).unwrap().unwrap(), "beta needle\n");
// Writing into a member creates its missing parent directories.
let fresh = f.beta.join("src/generated/mapper.xml");
f.run("misbehave", "projwrite", Some(fresh.to_str().unwrap()), None).unwrap();
assert_eq!(std::fs::read_to_string(&fresh).unwrap(), "written inside the project\n");
// `ctx.project()` is still the group's project.
assert_eq!(f.run("misbehave", "root", None, None).unwrap().unwrap(), to_ipc(&f.root));
// What is outside every root of the group stays refused, unwritten.
let outside = f.base.join("secret.txt");
let err = f.run("misbehave", "read", Some(outside.to_str().unwrap()), None).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
let err = f.run("misbehave", "projwrite", Some(outside.to_str().unwrap()), None).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
assert_eq!(std::fs::read_to_string(outside).unwrap(), "top secret");
// A member-scoped project reads its own files only: its root is the member.
assert_eq!(f.run("misbehave", "read", Some("src/Notes.txt"), Some(&f.beta)).unwrap().unwrap(), "beta needle\n");
}
/// Find in Files covers the members: search from the container finds member
/// matches, a member-scoped project sees only its own.
#[test]
fn project_search_reaches_workspace_members() {
let f = GroupFixture::new();
f.install(&sample("api14"));
let search = |root: &Path, needle: &str| f.run("api14", "search-text", Some(needle), Some(root)).unwrap().unwrap();
// From the container: matches in the members come through.
let all = search(&f.root, "needle");
assert!(all.contains("needle.php"), "{all}");
assert!(all.contains("Notes.txt"), "{all}");
// The container holds no sources: `.openidea` metadata never matches.
assert!(!all.contains("workspace.json"), "{all}");
// From a member: only that member's matches.
let own = search(&f.beta, "needle");
assert!(own.contains("Notes.txt"), "{own}");
assert!(!own.contains("needle.php"), "{own}");
// What is outside every root is never found.
assert!(!search(&f.root, "top secret").contains("secret.txt"));
}
/// The document-indexer covers member files: discovery offers them, indexing
/// one publishes its navigation, and files outside the group stay out.
#[test]
fn document_indexer_covers_workspace_members() {
let f = GroupFixture::new();
f.install(&sample("indexer"));
let mapping = f.inner.join("mappers/route.idx");
// Discovery: the member file is in the window's project scope.
let files = f
._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_files(&f.host, f.plugins.clone(), "main"))
.unwrap();
assert!(files.paths.iter().any(|p| p.0 == mapping), "{:?}", files.paths);
// Indexing the member file through the window's project publishes it: the
// open document is indexed at its version, like an editor click resolves.
let project = f.host.project("main").unwrap();
let doc = project.documents.open(&mapping).unwrap();
f._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_index(
&f.host,
f.plugins.clone(),
"main",
vec![mapping.clone()],
ide_core::RequestId::next(),
))
.unwrap();
let result = f
.plugins
.navigation_at(&f.root, &mapping, doc.version, ide_core::Pos::new(1, 5), Some("main"), |_| None)
.unwrap();
assert_eq!(result.targets[0].path.0, mapping);
// A file outside the group is never offered, and indexing skips it.
let outside = f.base.join("escape.idx");
std::fs::write(&outside, "def outside:item\n").unwrap();
let files = f
._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_files(&f.host, f.plugins.clone(), "main"))
.unwrap();
assert!(!files.paths.iter().any(|p| p.0 == outside), "{:?}", files.paths);
f._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_index(
&f.host,
f.plugins.clone(),
"main",
vec![outside.clone()],
ide_core::RequestId::next(),
))
.unwrap();
assert!(f.plugins.navigation_at(&f.root, &outside, 1, ide_core::Pos::new(0, 4), Some("main"), |_| None).is_none());
}
+5
Переглянути файл
@@ -33,6 +33,7 @@ mod tsserver_bridge;
pub mod types;
mod uri;
mod virtual_doc;
mod vue_navigation;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{FileInspection, InspectHost, InspectOptions};
@@ -843,6 +844,7 @@ impl LspManager {
self.schedule_pull(doc, Some(&server), Duration::ZERO);
}
self.check_clang_tidy(&server).await;
self.check_vue_navigation(&server).await;
server.refresh_busy_status(&self.sink);
server.announce_ready(generation);
self.spawn_supervisor(server, generation, peer);
@@ -1060,8 +1062,11 @@ impl LspManager {
if s.name == compose::SERVER && compose_added {
me.reconfigure_soon();
}
let hint = me.clone();
let server = s.clone();
self.runtime.spawn(async move { me.check_clang_tidy(&server).await });
let server = s.clone();
self.runtime.spawn(async move { hint.check_vue_navigation(&server).await });
}
}
}
+182
Переглянути файл
@@ -0,0 +1,182 @@
//! Vue 2 (Options API) template navigation: without `strictFunctionTypes`, the Vue 2.7
//! types infer `methods` / `computed` on `this` as `any`, so `textDocument/definition`
//! and hover in templates resolve to nothing (vuejs/language-tools#5257). The bundled
//! server can serve Vue 2.7 fine once the option is on (see #1164).
use crate::{LspManager, Server};
use ide_core::IdeEvent;
use std::path::Path;
pub(crate) const SERVER: &str = "vue-language-server";
pub(crate) const MESSAGE: &str = "Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.";
impl LspManager {
pub(crate) async fn check_vue_navigation(&self, server: &Server) {
if server.name != SERVER || self.shown_messages.lock().contains(&(SERVER.into(), MESSAGE.into())) {
return;
}
let Some(file) = self
.docs
.lock()
.values()
.find(|doc| {
doc.language.as_str() == "vue" && doc.servers.iter().any(|attached| attached.server.id == server.id)
})
.map(|doc| doc.path.clone())
else {
return;
};
let root = self.project_root_for(&file);
let Some(me) = self.me.upgrade() else { return };
let _ = tokio::task::spawn_blocking(move || {
if vue2_project(&root)
&& missing_strict_function_types(&root)
&& !me.shutting_down.load(std::sync::atomic::Ordering::Acquire)
&& me.first_message(SERVER, MESSAGE)
{
me.sink.emit(IdeEvent::LanguageServerWarning {
name: SERVER.into(),
message: MESSAGE.into(),
// No managed tool fixes this (the server itself is fine), so none is
// offered: the UI falls back to the settings shortcut only.
install_tool: String::new(),
});
}
})
.await;
}
}
/// The project's `package.json` depends on Vue 2 (2.7 is the version the Vue Language
/// Tools serve; older 2.x ranges resolve to it).
fn vue2_project(root: &Path) -> bool {
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else { return false };
let Ok(json) = serde_json::from_str::<serde_json::Value>(&manifest) else { return false };
["dependencies", "devDependencies"]
.iter()
.any(|section| json.get(section).and_then(|s| s.get("vue")).and_then(|v| v.as_str()).is_some_and(is_vue_2))
}
/// A `vue` version range whose major version is 2: `^2.7.16`, `~2.7`, `2.x`, `2`, `v2`.
fn is_vue_2(spec: &str) -> bool {
let rest = spec.trim().trim_start_matches(|c: char| !(c.is_ascii_digit() || c == 'v'));
let rest = rest.trim_start_matches('v');
let mut parts = rest.split('.');
parts.next().and_then(|major| major.parse::<u32>().ok()) == Some(2)
}
/// `jsconfig.json` / `tsconfig.json` at the root all lack the option: `strict` or
/// `strictFunctionTypes` is not `true` in their own `compilerOptions`. A config that
/// `extends` a base (which could set it) or can't be parsed stays quiet: a wrong hint
/// is worse than a missed one.
fn missing_strict_function_types(root: &Path) -> bool {
["jsconfig.json", "tsconfig.json"].iter().all(|name| match std::fs::read_to_string(root.join(name)) {
// No config there: nothing contradicts the hint (the option defaults to off).
Err(_) => true,
Ok(src) => strict_function_types(&src) == Some(false),
})
}
/// `strictFunctionTypes: true` or `strict: true` in `compilerOptions` of a JSONC config;
/// `None` when the config `extends` another or can't be parsed (the effective options
/// are unknown).
fn strict_function_types(src: &str) -> Option<bool> {
let json = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(src)).ok()?;
if json.get("extends").and_then(|e| e.as_str()).is_some_and(|e| !e.trim().is_empty()) {
return None;
}
Some(
["strictFunctionTypes", "strict"]
.iter()
.any(|key| json.get("compilerOptions").and_then(|o| o.get(key)).and_then(|v| v.as_bool()) == Some(true)),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vue_2_version_ranges() {
for spec in ["^2.7.16", "~2.7.0", "2.7", "2.x", "2.*", "2", "v2.7.16", ">=2.6.0 <3"] {
assert!(is_vue_2(spec), "{spec}");
}
for spec in ["^3.5.13", "3", "~3.0.0", "latest", "workspace:*", "*"] {
assert!(!is_vue_2(spec), "{spec}");
}
}
#[test]
fn vue_2_dependency_in_either_section() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("package.json"),
r#"{"dependencies": {"vue": "^2.7.16", "vue-template-compiler": "^2.7.16"}}"#,
)
.unwrap();
assert!(vue2_project(root));
std::fs::write(root.join("package.json"), r#"{"devDependencies": {"vue": "~2.7"}}"#).unwrap();
assert!(vue2_project(root));
std::fs::write(root.join("package.json"), r#"{"dependencies": {"vue": "^3.5.13"}}"#).unwrap();
assert!(!vue2_project(root));
std::fs::write(root.join("package.json"), r#"{"dependencies": {}}"#).unwrap();
assert!(!vue2_project(root));
}
#[test]
fn strict_function_types_in_jsonc() {
// Comments and trailing commas survive a real jsconfig.json.
let src = r#"{
// Generated by @vue/cli.
"compilerOptions": {
"target": "ES6",
"module": "commonjs", /* kept */
"allowJs": true,
},
"include": ["src/**/*"],
}"#;
assert_eq!(strict_function_types(src), Some(false));
assert_eq!(
strict_function_types(&src.replace("\"allowJs\": true", "\"strictFunctionTypes\": true")),
Some(true)
);
assert_eq!(strict_function_types(&src.replace("\"allowJs\": true", "\"strict\": true")), Some(true));
assert_eq!(strict_function_types(&src.replace("\"allowJs\": true", "\"strict\": false")), Some(false));
assert_eq!(
strict_function_types(&src.replace(
"\"include\": [\"src/**/*\"],",
"\"extends\": \"@vue/tsconfig\", \"include\": [\"src/**/*\"],"
)),
None
);
assert_eq!(strict_function_types("no json here"), None);
}
#[test]
fn missing_option_needs_a_quiet_config() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
// No config at all: the option defaults to off.
assert!(missing_strict_function_types(root));
let jsconfig = root.join("jsconfig.json");
std::fs::write(&jsconfig, r#"{"compilerOptions": {"module": "commonjs"}}"#).unwrap();
assert!(missing_strict_function_types(root));
// The option on in either config: navigation works there.
std::fs::write(&jsconfig, r#"{"compilerOptions": {"strictFunctionTypes": true}}"#).unwrap();
assert!(!missing_strict_function_types(root));
std::fs::write(&jsconfig, r#"{"compilerOptions": {"strict": true}}"#).unwrap();
assert!(!missing_strict_function_types(root));
// A base config could set it: stay quiet.
std::fs::write(&jsconfig, r#"{"extends": "./tsconfig.base.json", "compilerOptions": {}}"#).unwrap();
assert!(!missing_strict_function_types(root));
// An unparsable config: stay quiet.
std::fs::write(&jsconfig, "not json").unwrap();
assert!(!missing_strict_function_types(root));
// tsconfig.json carries the option for a jsconfig-less project.
std::fs::remove_file(&jsconfig).unwrap();
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions": {"strict": true}}"#).unwrap();
assert!(!missing_strict_function_types(root));
}
}
+2 -2
Переглянути файл
@@ -21,8 +21,8 @@ pub use runtime::{
component_api, host_api,
};
pub use sandbox::{
MAX_READ_BYTES, inside_root, read_text, resolve_in_root, resolve_new_in_root, resolve_real,
resolve_writable_in_root,
MAX_READ_BYTES, inside_root, inside_roots, read_text, resolve_in_root, resolve_in_roots, resolve_new_in_root,
resolve_real, resolve_writable_in_root, resolve_writable_in_roots,
};
pub use types::*;
pub use wasmtime::component::Component;
+7
Переглянути файл
@@ -356,6 +356,13 @@ pub trait HostApi: Send + Sync {
}
/// Roots of the open projects.
fn projects(&self) -> Vec<std::path::PathBuf>;
/// Roots of the workspace members attached to the project at `root` (a
/// project window group's folders, as the editor and LSP resolve them).
/// Empty for a plain project.
fn member_roots(&self, root: &Path) -> Vec<std::path::PathBuf> {
let _ = root;
Vec::new()
}
/// The most specific open project containing a document (including a new file).
fn project_of(&self, path: &Path) -> Option<std::path::PathBuf> {
if !path.is_absolute() {
+133
Переглянути файл
@@ -65,6 +65,29 @@ pub fn resolve_in_root(root: &Path, path: &str) -> Result<PathBuf, String> {
Ok(real)
}
/// [`resolve_in_root`] over several roots: the project root and, for a project
/// window group, its member roots. `roots` is tried in order (the project root
/// first), and the first root that contains `path` wins; a relative path may
/// name a file of any member. When no root contains it, the project root's
/// refusal is the error, as if there had been no members at all.
pub fn resolve_in_roots(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {
let (project_root, members) = match roots.split_first() {
Some((project_root, members)) => (project_root, members),
None => return Err(format!("{path}: no such file")),
};
match resolve_in_root(project_root, path) {
Ok(real) => Ok(real),
Err(project_root_error) => {
for root in members {
if let Ok(real) = resolve_in_root(root, path) {
return Ok(real);
}
}
Err(project_root_error)
}
}
}
/// Whether `path` (absolute, or relative to `root`) lands inside `root`,
/// without requiring it to exist: `Ok(true)` also for a missing path, so
/// callers distinguish "outside" from "absent". Existing symlinks are
@@ -74,6 +97,23 @@ pub fn inside_root(root: &Path, path: &str) -> Result<bool, String> {
Ok(resolve_real(&joined).starts_with(&root))
}
/// [`inside_root`] over several roots, as [`resolve_in_roots`] does: a path is
/// inside when any of them contains it.
pub fn inside_roots(roots: &[PathBuf], path: &str) -> Result<bool, String> {
let Some((project_root, members)) = roots.split_first() else {
return Ok(false);
};
if inside_root(project_root, path)? {
return Ok(true);
}
for root in members {
if inside_root(root, path)? {
return Ok(true);
}
}
Ok(false)
}
/// Like [`resolve_in_root`] for a path that may not exist yet (a file about to
/// be created) or that names a symlink itself (to delete or rename it): the
/// directory part is resolved through symlinks, the final name is kept as is,
@@ -128,6 +168,25 @@ pub fn resolve_writable_in_root(root: &Path, path: &str) -> Result<PathBuf, Stri
Ok(real)
}
/// [`resolve_writable_in_root`] over several roots, as [`resolve_in_roots`] does.
pub fn resolve_writable_in_roots(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {
let (project_root, members) = match roots.split_first() {
Some((project_root, members)) => (project_root, members),
None => return Err(format!("{path}: access outside the project root is not allowed")),
};
match resolve_writable_in_root(project_root, path) {
Ok(real) => Ok(real),
Err(project_root_error) => {
for root in members {
if let Ok(real) = resolve_writable_in_root(root, path) {
return Ok(real);
}
}
Err(project_root_error)
}
}
}
fn resolve_write_target(path: &Path, links_left: usize) -> Result<PathBuf, std::io::Error> {
match dunce::canonicalize(path) {
Ok(real) => return Ok(real),
@@ -411,6 +470,80 @@ mod tests {
assert!(inside_root(&root, "").is_err());
}
/// A project window group: the container root and its member roots.
fn group(tmp: &tempfile::TempDir) -> (PathBuf, PathBuf, Vec<PathBuf>) {
let container = tmp.path().join("workspace");
let alpha = tmp.path().join("alpha");
let beta = tmp.path().join("beta");
for dir in [&container, &alpha, &beta] {
std::fs::create_dir_all(dir).unwrap();
}
let container = dunce::canonicalize(container).unwrap();
let alpha = dunce::canonicalize(alpha).unwrap();
let beta = dunce::canonicalize(beta).unwrap();
(container, alpha.clone(), vec![alpha, beta])
}
#[test]
fn member_roots_accept_their_files_and_the_container_still_confines() {
let tmp = tempfile::tempdir().unwrap();
let (container, alpha, members) = group(&tmp);
std::fs::create_dir_all(container.join("src")).unwrap();
std::fs::write(container.join("src/notes.txt"), "hi").unwrap();
std::fs::create_dir_all(alpha.join("src")).unwrap();
let member_file = alpha.join("src/mapper.xml");
std::fs::write(&member_file, "hi").unwrap();
std::fs::write(tmp.path().join("secret.txt"), "s").unwrap();
let roots = [container.clone()].iter().cloned().chain(members.clone()).collect::<Vec<_>>();
// A member's absolute file resolves through its member root.
assert_eq!(resolve_in_roots(&roots, member_file.to_str().unwrap()).unwrap(), member_file);
// The container's own files still resolve as before.
let container_file = container.join("src/notes.txt");
assert_eq!(resolve_in_roots(&roots, "src/notes.txt").unwrap(), container_file);
// A missing path is `no such file`, wherever it would land.
let gone = container_file.with_file_name("gone.txt");
assert_eq!(
resolve_in_roots(&roots, gone.to_str().unwrap()).unwrap_err(),
format!("{}: no such file", gone.display())
);
// Outside every root is refused with the container's refusal.
let outside = tmp.path().join("secret.txt");
let err = resolve_in_roots(&roots, outside.to_str().unwrap()).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
let err = resolve_in_roots(&roots, "../secret.txt").unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
// `inside_roots` accepts member paths, including missing ones, and
// refuses what no root contains.
assert!(inside_roots(&roots, member_file.to_str().unwrap()).unwrap());
assert!(inside_roots(&roots, "missing/one.txt").unwrap());
assert!(inside_roots(&roots, alpha.join("src/new.xml").to_str().unwrap()).unwrap());
assert!(!inside_roots(&roots, outside.to_str().unwrap()).unwrap());
// No members: exactly the single-root behaviour.
let single = [container.clone()];
assert_eq!(resolve_in_roots(&single, "src/notes.txt").unwrap(), container_file);
assert!(!inside_roots(&single, member_file.to_str().unwrap()).unwrap());
}
#[test]
fn new_and_writable_paths_accept_members() {
let tmp = tempfile::tempdir().unwrap();
let (container, alpha, members) = group(&tmp);
std::fs::create_dir_all(container.join("src")).unwrap();
std::fs::create_dir_all(alpha.join("src")).unwrap();
let roots = [container.clone()].iter().cloned().chain(members.iter().cloned()).collect::<Vec<_>>();
let member_new = alpha.join("src/new.xml");
assert_eq!(resolve_writable_in_roots(&roots, member_new.to_str().unwrap()).unwrap(), member_new);
let container_new = container.join("src/new.txt");
assert_eq!(resolve_writable_in_roots(&roots, "src/new.txt").unwrap(), container_new);
let outside = tmp.path().join("escape.txt");
let err = resolve_writable_in_roots(&roots, outside.to_str().unwrap()).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
let err = resolve_writable_in_roots(&roots, "../../escape.txt").unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
}
#[test]
fn new_paths_are_confined_to_root() {
let tmp = tempfile::tempdir().unwrap();
+33 -7
Переглянути файл
@@ -686,7 +686,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
let real = match sandbox::resolve_in_root(&root, &path) {
let real = match self.resolve_in_project(&root, &path) {
Ok(real) => real,
Err(e) => {
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
@@ -704,7 +704,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
let real = match sandbox::resolve_in_root(&root, &path) {
let real = match self.resolve_in_project(&root, &path) {
Ok(real) => real,
Err(e) => {
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
@@ -720,15 +720,20 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
match sandbox::inside_root(&root, &path) {
match self.inside_project(&root, &path) {
Err(e) => Ok(Err(wit::Error::Invalid(e))),
Ok(false) => {
Ok(Err(wit::Error::Invalid(format!("{path}: access outside the project root is not allowed"))))
}
Ok(true) => {
let requested = Path::new(&path);
let joined = if requested.is_absolute() { requested.to_path_buf() } else { root.join(requested) };
Ok(Ok(joined.exists()))
let joined =
|root: &Path| if requested.is_absolute() { requested.to_path_buf() } else { root.join(requested) };
let mut exists = joined(&root).exists();
if !exists && !requested.is_absolute() {
exists = self.host.member_roots(&root).iter().any(|root| joined(root).exists());
}
Ok(Ok(exists))
}
}
}
@@ -738,7 +743,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
let real = match sandbox::resolve_in_root(&root, &path) {
let real = match self.resolve_in_project(&root, &path) {
Ok(real) => real,
Err(e) => {
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
@@ -797,7 +802,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(too_much_to_write(&path)));
}
let root = self.table.get(&this)?.root.clone();
let real = match sandbox::resolve_writable_in_root(&root, &path) {
let real = match self.resolve_writable_in_project(&root, &path) {
Ok(real) => real,
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
};
@@ -853,6 +858,27 @@ fn core_range(r: wit::Range) -> ide_core::Range {
ide_core::Range::new(pos(r.start), pos(r.end))
}
impl StoreData {
/// A `project` resource's path: inside the resource's root, or — for a
/// project window group — inside any of its member roots (as the editor and
/// LSP resolve them). When no root accepts the path, the resource root's own
/// refusal is the error, as if there were no members.
fn resolve_in_project(&self, root: &Path, path: &str) -> Result<PathBuf, String> {
sandbox::resolve_in_root(root, path).or_else(|root_error| {
sandbox::resolve_in_roots(&self.host.member_roots(root), path).map_err(|_| root_error)
})
}
/// [`Self::resolve_in_project`] for a content write's destination.
fn resolve_writable_in_project(&self, root: &Path, path: &str) -> Result<PathBuf, String> {
sandbox::resolve_writable_in_root(root, path).or_else(|root_error| {
sandbox::resolve_writable_in_roots(&self.host.member_roots(root), path).map_err(|_| root_error)
})
}
/// Whether a `project` resource's path lands inside the resource's root or
/// any member of its workspace group, without requiring it to exist.
fn inside_project(&self, root: &Path, path: &str) -> Result<bool, String> {
sandbox::inside_root(root, path)
.or_else(|root_error| sandbox::inside_roots(&self.host.member_roots(root), path).map_err(|_| root_error))
}
fn decoration_path(&self, path: &str) -> Result<PathBuf, wit::Error> {
if Path::new(path).is_absolute() {
return Ok(PathBuf::from(path));
+184 -18
Переглянути файл
@@ -439,29 +439,39 @@ pub fn gradle_env(
env
}
/// Settings › Build Tools › Gradle → jdtls `java.import.gradle.*`: the Java import runs the
/// same Gradle installation, user home and JVM as the IDE's own builds (paths resolved like
/// [`gradle_env`]). Without it a project that ships no wrapper is never imported, and one whose
/// caches live in a configured user home resolves no dependencies. The wrapper stays jdtls's
/// default unless a local distribution is chosen.
pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, s: &Settings) {
/// Settings › Build Tools › Gradle → jdtls `java.import.gradle.*`: the Java import of the Gradle
/// build in `build_dir` runs the same Gradle installation, user home and JVM as the IDE's own
/// Gradle runs ([`gradle_build_env`]: Gradle JVM, else the Project JDK, else an installed JDK
/// this Gradle version runs on). Without it a project that ships no wrapper is never imported,
/// one whose caches live in a configured user home resolves no dependencies, and an older Gradle
/// fails on the JDK jdtls itself runs on. The wrapper stays jdtls's default unless a local
/// distribution is chosen.
pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, build_dir: &Path, s: &Settings) {
if cfg.name != "jdtls" {
return;
}
let g = &s.languages.java.gradle;
let path = |p: PathBuf| Value::String(p.to_string_lossy().into_owned());
let mut gradle = serde_json::Map::new();
if g.distribution == ide_core::settings::GradleDistribution::Local
&& let Some(home) = setting_path(root, &g.home)
{
gradle.insert("home".into(), path(home));
gradle.insert("home".into(), json!(home.to_string_lossy()));
gradle.insert("wrapper".into(), json!({"enabled": false}));
}
if let Some(home) = setting_path(root, &g.user_home) {
gradle.insert("user".into(), json!({"home": path(home)}));
let gradle_build = ["settings.gradle", "settings.gradle.kts", "build.gradle", "build.gradle.kts"]
.iter()
.any(|f| build_dir.join(f).is_file());
let env = if gradle_build {
let command = gradle_command(root, build_dir, s);
gradle_build_env(root, build_dir, &command.to_string_lossy(), s, None)
} else {
gradle_env(root, s, Default::default())
};
if let Some(home) = env.get("GRADLE_USER_HOME") {
gradle.insert("user".into(), json!({"home": home}));
}
if let Some(home) = setting_path(root, &g.jvm) {
gradle.insert("java".into(), json!({"home": path(home)}));
if let Some(home) = env.get("JAVA_HOME") {
gradle.insert("java".into(), json!({"home": home}));
}
if gradle.is_empty() {
return;
@@ -1715,12 +1725,15 @@ pub fn terminal_activation(root: &Path, s: &Settings, shell: &str) -> Option<Str
if !s.languages.python.activate_virtualenv {
return None;
}
let venv = python_interpreter(root, s).as_deref().and_then(venv_of)?;
let python = python_interpreter(root, s)?;
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
let name = Path::new(name).file_stem().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
let Some(venv) = venv_of(&python) else {
return conda_activation(&python, &name, std::env::var_os("CONDA_EXE").map(PathBuf::from), which("conda"));
};
if std::env::var_os("VIRTUAL_ENV").is_some_and(|v| Path::new(&v) == venv) {
return None;
}
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
let name = Path::new(name).file_stem().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
let script = |file: &str| venv.join(bin_dir()).join(file);
let line = match name.as_str() {
"fish" => format!("source {}", sh_quote(&script("activate.fish").to_string_lossy())),
@@ -1745,6 +1758,64 @@ pub fn terminal_activation(root: &Path, s: &Settings, shell: &str) -> Option<Str
script(target).is_file().then_some(line)
}
/// `conda activate <prefix>` for a conda interpreter, as PyCharm does for a Conda project
/// interpreter: conda envs have no activate script of their own, and the shells' conda hook
/// comes from the installation (the env itself for `base`, the parent of `envs/`, else
/// `CONDA_EXE` or the `conda` on PATH). `name` is the shell's lowercased file stem.
fn conda_activation(python: &Path, name: &str, conda_exe: Option<PathBuf>, on_path: Option<PathBuf>) -> Option<String> {
let env = crate::discover::conda_env_home(python).filter(|env| env.join("conda-meta").is_dir())?;
if std::env::var_os("CONDA_PREFIX").is_some_and(|p| Path::new(&p) == env) {
return None;
}
let is_base = |dir: &Path| dir.join("condabin").is_dir();
// `<base>/bin/conda`, `<base>/condabin/conda[.bat]`, `<base>\Scripts\conda.exe`.
let base_of = |exe: PathBuf| exe.parent()?.parent().map(Path::to_path_buf).filter(|b| is_base(b));
let base = Some(env.clone())
.filter(|e| is_base(e))
.or_else(|| {
env.parent()
.filter(|p| p.file_name().is_some_and(|n| n == "envs"))?
.parent()
.map(Path::to_path_buf)
.filter(|b| is_base(b))
})
.or_else(|| conda_exe.and_then(base_of))
.or_else(|| on_path.and_then(base_of))?;
let prefix = env.to_string_lossy();
let conda = if cfg!(windows) { base.join("Scripts").join("conda.exe") } else { base.join("bin").join("conda") };
let posix = |hook: &str| {
conda.is_file().then(|| {
format!(
"eval \"$({} shell.{hook} hook)\" && conda activate {}",
sh_quote(&conda.to_string_lossy()),
sh_quote(&prefix)
)
})
};
match name {
"cmd" => {
let bat = base.join("condabin").join("conda.bat");
bat.is_file().then(|| format!("call \"{}\" activate \"{prefix}\"", bat.display()))
}
"pwsh" | "powershell" => {
let hook = base.join("shell").join("condabin").join("conda-hook.ps1");
let quote = |s: &str| format!("'{}'", s.replace('\'', "''"));
hook.is_file().then(|| format!("& {}; conda activate {}", quote(&hook.to_string_lossy()), quote(&prefix)))
}
"bash" => posix("bash"),
"zsh" => posix("zsh"),
"sh" | "dash" | "ksh" | "mksh" | "ash" => posix("posix"),
"fish" => conda.is_file().then(|| {
format!(
"{} shell.fish hook | source; and conda activate {}",
sh_quote(&conda.to_string_lossy()),
sh_quote(&prefix)
)
}),
_ => None,
}
}
#[cfg(test)]
mod java_compiler_tests {
use super::*;
@@ -1940,7 +2011,7 @@ mod maven_linkage_tests {
cfg.settings = Some(json!({"java": {"import": {"gradle": {"enabled": true}}}}));
let initial = cfg.clone();
let mut settings = Settings::default();
configure_gradle_runtime(&mut cfg, root, &settings);
configure_gradle_runtime(&mut cfg, root, root, &settings);
assert_eq!(cfg, initial, "no Gradle settings: jdtls keeps its own defaults and the wrapper");
let g = &mut settings.languages.java.gradle;
@@ -1948,7 +2019,7 @@ mod maven_linkage_tests {
g.home = "tools/gradle-5.2.1".into();
g.user_home = "/caches/gradle".into();
g.jvm = "/jdk/8".into();
configure_gradle_runtime(&mut cfg, root, &settings);
configure_gradle_runtime(&mut cfg, root, root, &settings);
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
assert_eq!(gradle["enabled"], json!(true), "merged, not replaced");
let resolved = |s: &str| json!(setting_path(root, s).unwrap().to_string_lossy());
@@ -1960,12 +2031,40 @@ mod maven_linkage_tests {
// The wrapper distribution keeps the wrapper even with a home left over.
let mut cfg = initial.clone();
settings.languages.java.gradle.distribution = ide_core::settings::GradleDistribution::Wrapper;
configure_gradle_runtime(&mut cfg, root, &settings);
configure_gradle_runtime(&mut cfg, root, root, &settings);
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
assert!(gradle.get("home").is_none() && gradle.get("wrapper").is_none());
assert_eq!(gradle["user"]["home"], resolved("/caches/gradle"));
}
#[test]
fn gradle_import_of_a_gradle_build_runs_on_the_project_jdk_like_the_ides_builds() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::write(root.join("build.gradle"), "plugins { id 'java' }").unwrap();
let jdk = root.join("jdk11");
std::fs::create_dir_all(jdk.join("bin")).unwrap();
std::fs::write(jdk.join("bin").join(crate::exe("java")), "").unwrap();
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"11.0.2\"\n").unwrap();
let mut settings = Settings::default();
settings.languages.java.jdk = jdk.to_string_lossy().into_owned();
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
configure_gradle_runtime(&mut cfg, root, root, &settings);
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
let expected =
gradle_build_env(root, root, &gradle_command(root, root, &settings).to_string_lossy(), &settings, None);
assert_eq!(gradle["java"]["home"], json!(expected["JAVA_HOME"]));
assert!(expected["JAVA_HOME"].ends_with("jdk11"));
assert!(gradle.get("wrapper").is_none(), "the wrapper stays on");
// An explicit Gradle JVM wins over the Project JDK.
settings.languages.java.gradle.jvm = "/gradle-jdk".into();
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
configure_gradle_runtime(&mut cfg, root, root, &settings);
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
assert_eq!(gradle["java"]["home"], json!(setting_path(root, "/gradle-jdk").unwrap().to_string_lossy()));
}
#[test]
fn explicit_gradle_links_scope_jdt_import_and_unlink_all_disables_gradle() {
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
@@ -2093,3 +2192,70 @@ mod java_compliance_tests {
assert_eq!(c("latest"), None);
}
}
#[cfg(test)]
mod conda_activation_tests {
use super::*;
fn touch(path: &Path) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
/// A conda prefix with its interpreter where conda puts it on this OS.
fn prefix(dir: &Path) -> PathBuf {
std::fs::create_dir_all(dir.join("conda-meta")).unwrap();
let python = if cfg!(windows) { dir.join("python.exe") } else { dir.join("bin").join("python") };
touch(&python);
python
}
#[test]
fn conda_envs_activate_through_the_installations_shell_hooks() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path().join("miniconda3");
let base_python = prefix(&base);
std::fs::create_dir_all(base.join("condabin")).unwrap();
let conda = if cfg!(windows) { base.join("Scripts").join("conda.exe") } else { base.join("bin").join("conda") };
touch(&conda);
let bat = base.join("condabin").join("conda.bat");
touch(&bat);
let hook = base.join("shell").join("condabin").join("conda-hook.ps1");
touch(&hook);
let env = base.join("envs").join("agent-gateway");
let python = prefix(&env);
let q = |p: &Path| sh_quote(&p.to_string_lossy());
assert_eq!(
conda_activation(&python, "zsh", None, None).unwrap(),
format!("eval \"$({} shell.zsh hook)\" && conda activate {}", q(&conda), q(&env))
);
assert_eq!(
conda_activation(&python, "cmd", None, None).unwrap(),
format!("call \"{}\" activate \"{}\"", bat.display(), env.display())
);
assert_eq!(
conda_activation(&python, "powershell", None, None).unwrap(),
format!("& '{}'; conda activate '{}'", hook.display(), env.display())
);
assert_eq!(
conda_activation(&python, "fish", None, None).unwrap(),
format!("{} shell.fish hook | source; and conda activate {}", q(&conda), q(&env))
);
assert_eq!(conda_activation(&python, "nu", None, None), None, "no conda hook for this shell");
assert!(conda_activation(&base_python, "bash", None, None).unwrap().ends_with(&q(&base)), "base itself");
// A `--prefix` env elsewhere finds the installation through CONDA_EXE or PATH.
let elsewhere = tmp.path().join("project").join(".conda");
let python = prefix(&elsewhere);
assert_eq!(conda_activation(&python, "bash", None, None), None);
let line = conda_activation(&python, "bash", Some(conda.clone()), None).unwrap();
assert!(line.ends_with(&format!("conda activate {}", q(&elsewhere))), "{line}");
assert!(conda_activation(&python, "cmd", None, Some(bat.clone())).is_some());
// Not a conda prefix.
let plain = tmp.path().join("python");
touch(&plain.join("bin").join("python"));
assert_eq!(conda_activation(&plain.join("bin").join("python"), "bash", Some(conda), None), None);
}
}
+1 -1
Переглянути файл
@@ -321,7 +321,7 @@ fn python_sdk_with_version(path: &Path, source: &str, root: Option<&Path>, versi
}
/// The prefix of a conda interpreter: `<env>/bin/python` on Unix, `<env>/python.exe` on Windows.
fn conda_env_home(python: &Path) -> Option<PathBuf> {
pub(crate) fn conda_env_home(python: &Path) -> Option<PathBuf> {
let dir = python.parent()?;
let bin = dir.file_name().is_some_and(|n| n == "bin" || n.eq_ignore_ascii_case("Scripts"));
Some(if bin { dir.parent()? } else { dir }.to_path_buf())
+30 -3
Переглянути файл
@@ -21,6 +21,7 @@ pub struct DocumentInfo {
pub version: u32,
pub language: LanguageId,
pub encoding: String,
pub has_bom: bool,
pub line_ending: LineEnding,
pub read_only: bool,
pub dirty: bool,
@@ -41,6 +42,14 @@ pub struct DocumentInfo {
pub ui_mode: Option<String>,
}
/// Encoding and BOM currently applied to an open document.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentEncoding {
pub encoding: String,
pub has_bom: bool,
}
/// Current text and identity of a document, for analyses (outline, folding).
#[derive(Clone, Debug)]
pub struct TextSnapshot {
@@ -326,6 +335,7 @@ impl Documents {
version: st.doc.version(),
language: st.language.clone(),
encoding: st.encoding.clone(),
has_bom: st.has_bom,
line_ending: st.doc.line_ending(),
read_only: st.read_only,
dirty: st.dirty,
@@ -822,7 +832,7 @@ impl Documents {
/// Changes the document's encoding. `reload`: re-decode the file on disk with
/// it (refused while there are unsaved changes); otherwise convert: the text
/// is kept and the next save writes it in the new encoding.
pub fn set_encoding(&self, doc: DocId, encoding: &str, reload: bool) -> IdeResult<String> {
pub fn set_encoding(&self, doc: DocId, encoding: &str, reload: bool) -> IdeResult<DocumentEncoding> {
self.with_doc(doc, |st| {
if st.uri.is_some() {
return Err(read_only_error(&st.path));
@@ -842,7 +852,7 @@ impl Documents {
self.replace_locked(doc, st, &loaded.text)?;
// Reloading is not an edit: the buffer matches the file again.
self.set_dirty(doc, st, false);
return Ok(loaded.encoding);
return Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom });
}
if st.read_only {
return Err(read_only_error(&st.path));
@@ -856,7 +866,24 @@ impl Documents {
st.encoding = encoding.to_owned();
st.has_bom = has_bom;
self.set_dirty(doc, st, true);
Ok(st.encoding.clone())
Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom })
})
}
/// Adds or removes the BOM on a UTF-8 document; the change is written on save.
pub fn set_bom(&self, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
self.with_doc(doc, |st| {
if st.uri.is_some() || st.read_only {
return Err(read_only_error(&st.path));
}
if st.encoding != "utf-8" || st.native_to_ascii {
return Err(IdeError::invalid("the BOM can only be changed for UTF-8 documents"));
}
if st.has_bom != has_bom {
st.has_bom = has_bom;
self.set_dirty(doc, st, true);
}
Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom })
})
}
+1 -1
Переглянути файл
@@ -21,7 +21,7 @@ pub mod unity;
pub mod window_groups;
pub mod workspace;
pub use documents::{DetectLanguage, DocumentInfo, Documents, TextSnapshot};
pub use documents::{DetectLanguage, DocumentEncoding, DocumentInfo, Documents, TextSnapshot};
pub use editorconfig::{EditorConfig, EditorConfigProps};
pub use file_defaults::FileDefaults;
pub use file_moves::{FileMove, FileMoves, UndoOutcome};
+29 -2
Переглянути файл
@@ -486,11 +486,15 @@ fn reload_and_convert_encoding() {
let (bytes, _, _) = encoding_rs::GBK.encode("中文内容");
fs::write(&path, &bytes).unwrap();
let info = f.docs.open(&path).unwrap();
assert_eq!(f.docs.set_encoding(info.id, "gbk", true).unwrap(), "gbk");
let encoding = f.docs.set_encoding(info.id, "gbk", true).unwrap();
assert_eq!(encoding.encoding, "gbk");
assert!(!encoding.has_bom);
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "中文内容");
// Convert: same text, written in the new encoding on save.
assert_eq!(f.docs.set_encoding(info.id, "utf-8", false).unwrap(), "utf-8");
let encoding = f.docs.set_encoding(info.id, "utf-8", false).unwrap();
assert_eq!(encoding.encoding, "utf-8");
assert!(!encoding.has_bom);
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "中文内容");
@@ -501,6 +505,29 @@ fn reload_and_convert_encoding() {
assert!(f.docs.set_encoding(info.id, "gbk", true).is_err());
}
#[test]
fn utf8_bom_is_added_and_removed_on_save() {
let f = fixture();
let path = f.root.join("bom.txt");
fs::write(&path, "text").unwrap();
let info = f.docs.open(&path).unwrap();
assert!(!info.has_bom);
assert!(f.docs.set_bom(info.id, true).unwrap().has_bom);
assert_eq!(fs::read(&path).unwrap(), b"text", "written on save only");
f.docs.save(info.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"\xEF\xBB\xBFtext");
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "text");
assert!(!f.docs.set_bom(info.id, false).unwrap().has_bom);
f.docs.save(info.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"text");
// Other encodings have no BOM to toggle.
f.docs.set_encoding(info.id, "gbk", false).unwrap();
assert!(f.docs.set_bom(info.id, true).is_err());
}
#[cfg(unix)]
#[test]
fn symlinked_path_maps_to_same_document() {
+2 -2
Переглянути файл
@@ -17,7 +17,7 @@ The left side is a tree; the right side shows details of the selected item (a co
### Run configurations
Spring Boot configurations appear by default. Other types appear when you add them with **Add Service › Run Configuration Type**, or once a configuration of that type has run. Each type is a group.
Only types you add appear here: choose **Add Service › Run Configuration Type**; each type is a group, kept until you remove it with **Remove from Services**. Removing a type or a single configuration takes effect at once, even while it runs: the run moves to the Run tool window, so its console stays reachable. Running a configuration of a type you have not added keeps its output in the Run or Debug tool window too.
- Group actions: **Run All**, **Restart All**, **Stop All**, **Open in Browser**.
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
@@ -31,7 +31,7 @@ OpenIDEA drives Docker through the `docker` CLI, so anything that provides a wor
### Connections
With nothing configured, Services shows one connection named **Docker** that uses the Docker CLI default (`DOCKER_HOST` or the current context). To add another, choose **Add Service › Docker Connection…**:
With nothing configured, Services lists no Docker connection. To add one (the first one usually connects to the Docker CLI default: `DOCKER_HOST` or the current context), choose **Add Service › Docker Connection…**:
| Field | Options |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+2 -2
Переглянути файл
@@ -17,7 +17,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
### 运行配置
Spring Boot 配置默认就会显示。其他类型在通过 **添加服务 › 运行配置类型** 添加后,或者该类型的配置运行过一次后出现。每种类型一个分组。
只有你添加的类型才会出现:选择 **添加服务 › 运行配置类型**(类型会一直保留,直到用 **从服务中移除** 删掉;每种类型一个分组)。移除类型或单个配置立即生效——即使它正在运行,运行也会转到运行工具窗口,控制台始终可达。运行未添加类型的配置时,输出同样留在运行或调试工具窗口。
- 分组操作:**全部运行**、**全部重启**、**全部停止**、**在浏览器中打开**。
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
@@ -31,7 +31,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
### 连接
什么都不配置时,服务中会有一个名为 **Docker** 的连接,使用 Docker CLI 默认设置(`DOCKER_HOST` 或当前上下文)。要添加其他连接,选择 **添加服务 › Docker 连接…**:
什么都不配置时,服务中不列出任何 Docker 连接。要添加一个连接(第一个通常连接 Docker CLI 默认设置:`DOCKER_HOST` 或当前上下文),选择 **添加服务 › Docker 连接…**:
| 字段 | 说明 |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+43
Переглянути файл
@@ -153,3 +153,46 @@ test("Docker Compose editor completes service references and navigates to declar
await page.keyboard.press("Meta+b");
await expect(editor.locator(".cm-activeLine")).toHaveText(" backend:");
});
test("the Services detail pane adds no second scrollbar over a console", async ({ workbench: page }) => {
// A short window: the run toolbar is taller than the detail pane, which used to make
// the split panel scroll too (the console had its own scrollbar right beside it).
await page.setViewportSize({ width: 1200, height: 640 });
await page.evaluate(async () => {
const store = await import(/* @vite-ignore */ "/src/features/run/store.ts" as string);
await store.startSampleOutput(200, 50);
const id = store.useRun.getState().activeSession as string;
store.useRun.setState((s: { sessions: { id: string }[]; versions: Record<string, number> }) => ({
sessions: s.sessions.map((x) => (x.id === id ? { ...x, status: "running" } : x)),
versions: { ...s.versions, [id]: (s.versions[id] ?? 0) + 1 },
}));
const svc = await import(/* @vite-ignore */ "/src/features/run/services.tsx" as string);
const tree = await import(/* @vite-ignore */ "/src/features/services/tree.ts" as string);
const session = store.useRun.getState().sessions.find((s: { id: string }) => s.id === id);
svc.addType(session.config.kind);
tree.useServicesTree.setState({
selectedKey: `run:config:${session.config.id}`,
selectedKeys: new Set([`run:config:${session.config.id}`]),
});
});
await page.keyboard.press("Meta+8");
await expect(page.getByRole("log").first()).toBeVisible();
const result = await page.evaluate(() => {
const log = document.querySelector('[data-toolwindow="services"] [role="log"]');
let panel: Element | null = log;
while (panel && !panel.hasAttribute("data-panel")) panel = panel.parentElement;
const inner = panel?.firstElementChild as HTMLElement | null;
const scrollers: string[] = [];
for (const el of document.querySelectorAll<HTMLElement>('[data-toolwindow="services"] *')) {
const cs = getComputedStyle(el);
if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && el.scrollHeight - el.clientHeight > 2)
scrollers.push(String(el.className));
}
return { overflowY: inner ? getComputedStyle(inner).overflowY : "missing", scrollers };
});
// The panel's inner div carries the library's inline `overflow: auto`; the detail pane
// overrides it, so the console is the only scroller.
expect(result.overflowY).toBe("hidden");
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
expect(result.scrollers.length).toBeGreaterThan(0);
});
+65
Переглянути файл
@@ -134,3 +134,68 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
]);
await expect(tree.getByRole("treeitem", { selected: true })).toContainText("z-web");
});
test("keeps surviving workspace icons and type order during removal", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const current = useProject.getState().project;
const projects = ["/work/a-go", "/work/b-web", "/work/z-rust"];
const project = {
...current,
root: "/workspace",
name: "Workspace",
workspace: { version: 1, name: "Workspace", projects },
};
const markers: Record<string, string> = {
"/work/a-go": "go.mod",
"/work/b-web": "package.json",
"/work/z-rust": "Cargo.toml",
};
const rescan = new Promise<void>((resolve) => {
window.__ipc.handlers.finish_workspace_rescan = () => resolve();
});
let removed = false;
window.__ipc.handlers.fs_read_dir = async ({ path }) => {
if (removed) await rescan;
const name = markers[String(path)];
return name
? [{ path: `${path}/${name}`, name, kind: "file", size: 0, mtimeMs: 0, ignored: false, excluded: false }]
: [];
};
window.__ipc.handlers.project_roots = () => ({ folders: [] });
window.__ipc.handlers.workspace_update = ({ projects }) => {
removed = true;
return { ...project, workspace: { ...project.workspace, projects } };
};
useProject.setState({ project });
});
const tree = page.getByRole("tree", { name: "Project" });
const rust = tree.locator('[data-project-path="/work/z-rust"]');
const go = tree.locator('[data-project-path="/work/a-go"]');
const web = tree.locator('[data-project-path="/work/b-web"]');
const icons = () =>
Promise.all(
[rust, go].map((row) =>
row.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))),
),
);
const panel = page.getByRole("region", { name: "Project", exact: true });
await panel.getByRole("button", { name: "Collapse All", exact: true }).click();
await panel.getByRole("button", { name: "Options", exact: true }).click();
await page.getByRole("menuitemcheckbox", { name: "Sort by Type", exact: true }).click();
const rows = tree.locator('[data-project-path^="/work/"]');
await expect(rows).toHaveText(["z-rust/work/z-rust", "a-go/work/a-go", "b-web/work/b-web"]);
const before = await icons();
await web.click({ button: "right" });
await page.getByRole("menuitem", { name: "Remove from Workspace", exact: true }).click();
await expect(web).toHaveCount(0);
await page.screenshot({ path: test.info().outputPath("workspace-removal.png"), animations: "disabled" });
expect(await icons()).toEqual(before);
await expect(rows).toHaveText(["z-rust/work/z-rust", "a-go/work/a-go"]);
await page.evaluate(() => window.__ipc.handlers.finish_workspace_rescan!({}));
});
+14 -3
Переглянути файл
@@ -6,7 +6,7 @@ use ide_core::{ChangeSet, DocId, IdeResult, OutlineItem, Range};
pub use ide_host::ops::doc::*;
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentInfo, HistoryEntry};
use ide_workspace::{DocumentEncoding, DocumentInfo, HistoryEntry};
use std::path::PathBuf;
use tauri::{Manager, State, Window};
@@ -87,7 +87,7 @@ pub async fn doc_ui_mode(window: Window, state: State<'_, AppState>, path: PathB
ide_host::ops::doc::doc_ui_mode(&state.host, window.label(), path).await
}
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state.
#[tauri::command]
#[specta::specta]
pub async fn doc_set_encoding(
@@ -96,10 +96,21 @@ pub async fn doc_set_encoding(
doc: DocId,
encoding: String,
reload: bool,
) -> IdeResult<String> {
) -> IdeResult<DocumentEncoding> {
ide_host::ops::doc::doc_set_encoding(&state.host, window.label(), doc, encoding, reload).await
}
#[tauri::command]
#[specta::specta]
pub async fn doc_set_bom(
window: Window,
state: State<'_, AppState>,
doc: DocId,
has_bom: bool,
) -> IdeResult<DocumentEncoding> {
ide_host::ops::doc::doc_set_bom(&state.host, window.label(), doc, has_bom).await
}
#[tauri::command]
#[specta::specta]
pub async fn doc_set_line_ending(
+1
Переглянути файл
@@ -194,6 +194,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
doc::doc_snapshot,
doc::doc_ui_mode,
doc::doc_set_encoding,
doc::doc_set_bom,
doc::doc_set_line_ending,
doc::doc_outline,
doc::doc_folding,
+25 -2
Переглянути файл
@@ -83,7 +83,6 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
m.index_files += status.files;
m.index_symbols += status.symbols;
m.indexing |= status.indexing;
let project = project_name(&p.root);
for s in p.lsp.servers() {
if matches!(s.status, ServerStatus::Starting | ServerStatus::Ready | ServerStatus::Busy) {
m.language_servers += 1;
@@ -93,7 +92,10 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
pid,
category: MemoryCategory::LanguageServer,
label: s.name,
detail: Some(project.clone()),
// A project can attach several roots (additional content
// roots); name the server's own workspace root, not the
// project folder, so rows of one name don't collide.
detail: Some(project_name(s.root.as_ref())),
with_children: true,
});
}
@@ -233,3 +235,24 @@ pub async fn clear_caches(window: Window, state: State<'_, AppState>) -> IdeResu
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
/// Language server rows are named by the server's own workspace root, not
/// the project folder: one project window can attach additional content
/// roots, and a server per root would otherwise show up as rows with the
/// same label and detail (e.g. "pyrefly MindSpeed" twice for MindSpeed +
/// Megatron-LM).
#[test]
fn server_row_detail_is_the_server_root_folder() {
let project = std::path::Path::new("B:/Program/Project/Ascend/MindSpeed");
let megatron = std::path::PathBuf::from("B:/Program/Project/Source/Megatron-LM");
assert_eq!(project_name(project), "MindSpeed");
assert_ne!(project_name(&megatron), project_name(project));
// IPC paths are `/`-separated on every OS, so `file_name` sees the
// folder without a Windows special case.
assert_eq!(project_name(&megatron), "Megatron-LM");
}
}
+28 -2
Переглянути файл
@@ -298,8 +298,9 @@ export const commands = {
* without opening it: previews of closed files.
*/
docUiMode: (path: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("doc_ui_mode", { path })),
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label. */
docSetEncoding: (doc: DocId, encoding: string, reload: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("doc_set_encoding", { doc, encoding, reload })),
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state. */
docSetEncoding: (doc: DocId, encoding: string, reload: boolean) => typedError<DocumentEncoding, IdeError>(__TAURI_INVOKE("doc_set_encoding", { doc, encoding, reload })),
docSetBom: (doc: DocId, hasBom: boolean) => typedError<DocumentEncoding, IdeError>(__TAURI_INVOKE("doc_set_bom", { doc, hasBom })),
docSetLineEnding: (doc: DocId, lineEnding: LineEnding) => typedError<null, IdeError>(__TAURI_INVOKE("doc_set_line_ending", { doc, lineEnding })),
/**
* Structure view: LSP document symbols when available (with tree-sitter
@@ -2714,6 +2715,13 @@ export type CodeStyleSettings_Serialize = {
formatterTagsRegexp: boolean,
};
/** Editor › Inlay Hints › Code Vision position (IDEA's "Default position for metrics"). */
export type CodeVisionPosition =
/** A row of its own above the declaration. */
"top" |
/** After the end of the declaration's first line. */
"right";
/** ColorInfo data. */
export type ColorInfo = {
range: Range,
@@ -4009,6 +4017,12 @@ export type DockerVolume = {
labels?: { [key in string]: string },
};
/** Encoding and BOM currently applied to an open document. */
export type DocumentEncoding = {
encoding: string,
hasBom: boolean,
};
/** What the UI needs to show an opened document. */
export type DocumentInfo = {
id: DocId,
@@ -4017,6 +4031,7 @@ export type DocumentInfo = {
version: number,
language: LanguageId,
encoding: string,
hasBom: boolean,
lineEnding: LineEnding,
readOnly: boolean,
dirty: boolean,
@@ -5575,6 +5590,12 @@ export type InlayHintsSettings = {
codeVisionUsages?: boolean,
/** Code vision: last author of a declaration (VCS blame) beside its usages. */
codeVisionAuthor?: boolean,
/** Code vision: "no usages" on declarations nothing uses (IDEA shows it; clicking searches everywhere). */
codeVisionNoUsages?: boolean,
/** Code vision: where the usages go, above the declaration or at the end of its line. */
codeVisionUsagesPosition?: CodeVisionPosition,
/** Code vision: where the author goes, above the declaration or at the end of its line. */
codeVisionAuthorPosition?: CodeVisionPosition,
};
export type InlayKind = "type" | "parameter" | "other";
@@ -6644,6 +6665,11 @@ export type McpServerInput = {
export type McpServerSettings = {
/** Serve the tools on 127.0.0.1 while the IDE runs. */
enabled?: boolean,
/**
* Run the tools that change the project or start processes without asking first
* (IDEA's brave mode). Read from the IDE's own settings only, never a project's.
*/
runWithoutConfirmation?: boolean,
};
/** What Settings › Agents › MCP Server shows. */
+2
Переглянути файл
@@ -595,6 +595,8 @@ export interface CodeLens {
run?: (view: EditorView, event: MouseEvent) => void;
/** Lower first within a line. Default 100. */
order?: number;
/** The Code Vision setting that places it ("usages", "author"); a lens without one goes above the line. */
kind?: string;
}
export const codeLenses = Facet.define<readonly CodeLens[], readonly CodeLens[]>({
+31 -8
Переглянути файл
@@ -12,6 +12,7 @@ import {
isTauri,
onIdeEvent,
type DocId,
type DocumentEncoding,
type DocumentInfo,
type FoldRange,
type LanguageInfo_Serialize,
@@ -47,8 +48,10 @@ export interface DocBackend {
syncFromDisk?(): Promise<void>;
snapshot(doc: DocId): Promise<DocumentInfo>;
setLineEnding(doc: DocId, lineEnding: LineEnding): Promise<void>;
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding. */
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<string>;
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding and BOM state. */
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<DocumentEncoding>;
/** Adds or removes the BOM on a UTF-8 document; the change is written on save. */
setBom(doc: DocId, hasBom: boolean): Promise<DocumentEncoding>;
outline(doc: DocId): Promise<OutlineItem[]>;
folding(doc: DocId): Promise<FoldRange[]>;
/** Tree-sitter highlighting, for languages without a CodeMirror mode. */
@@ -83,6 +86,7 @@ export const ipcBackend: DocBackend = {
snapshot: (doc) => call(commands.docSnapshot(doc)),
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
setBom: (doc, hasBom) => call(commands.docSetBom(doc, hasBom)),
outline: (doc) => call(commands.docOutline(doc)),
folding: (doc) => call(commands.docFolding(doc)),
highlights: (doc) => call(commands.docHighlights(doc)),
@@ -108,9 +112,11 @@ interface MemDoc {
path: string;
text: string;
saved: string;
savedBom: boolean;
version: number;
refs: number;
lineEnding: LineEnding;
hasBom: boolean;
readOnly: boolean;
language: string;
uiMode?: string;
@@ -377,6 +383,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
const dirtyHandlers = new Set<(e: { doc: DocId; dirty: boolean }) => void>();
let nextId = 1;
const store = new Map(Object.entries(files));
const savedBoms = new Map<string, boolean>();
const info = (d: MemDoc): DocumentInfo => ({
id: d.id,
@@ -385,9 +392,10 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
version: d.version,
language: d.language,
encoding: "UTF-8",
hasBom: d.hasBom,
lineEnding: d.lineEnding,
readOnly: d.readOnly,
dirty: d.text !== d.saved,
dirty: d.text !== d.saved || d.hasBom !== d.savedBom,
...(d.uri ? { uri: d.uri } : {}),
...(d.uiMode ? { uiMode: d.uiMode } : {}),
});
@@ -411,7 +419,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
return d;
};
const setDirty = (d: MemDoc, before: boolean) => {
const now = d.text !== d.saved;
const now = d.text !== d.saved || d.hasBom !== d.savedBom;
if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now }));
};
const delay = <T>(v: () => T): Promise<T> =>
@@ -439,15 +447,18 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
return info(d);
}
const text = store.get(path) ?? sampleFor(path);
const hasBom = savedBoms.get(path) ?? false;
const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
const d: MemDoc = {
id: nextId++,
path,
text,
saved: text,
savedBom: hasBom,
version: 0,
refs: 1,
lineEnding: "lf",
hasBom,
readOnly: false,
language: EXT_LANG[ext] ?? "plaintext",
};
@@ -473,9 +484,11 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
path: uri,
text,
saved: text,
savedBom: false,
version: 0,
refs: 1,
lineEnding: "lf",
hasBom: false,
readOnly: true,
language: ext === "class" ? "java" : (EXT_LANG[ext] ?? "plaintext"),
uri,
@@ -496,7 +509,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
if (d.readOnly) throw new IpcError({ kind: "permissionDenied", message: "read-only" });
if (baseVersion !== d.version)
throw new IpcError({ kind: "outOfSync", message: `base ${baseVersion}, document at ${d.version}` });
const before = d.text !== d.saved;
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
d.text = applyChanges(d.text, changes);
d.version++;
setDirty(d, before);
@@ -505,9 +518,11 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
},
async save(doc) {
const d = get(doc);
const before = d.text !== d.saved;
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
d.saved = d.text;
d.savedBom = d.hasBom;
store.set(d.path, d.text);
savedBoms.set(d.path, d.hasBom);
setDirty(d, before);
},
async snapshot(doc) {
@@ -516,8 +531,16 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
async setLineEnding(doc, le) {
get(doc).lineEnding = le;
},
async setEncoding(_doc, encoding) {
return encoding;
async setEncoding(doc, encoding) {
return { encoding, hasBom: get(doc).hasBom };
},
async setBom(doc, hasBom) {
const d = get(doc);
if (d.readOnly) throw new IpcError({ kind: "permissionDenied", message: "read-only" });
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
d.hasBom = hasBom;
setDirty(d, before);
return { encoding: "utf-8", hasBom: d.hasBom };
},
async outline(doc) {
// Brace-based outline good enough for the dev shell.
+44 -1
Переглянути файл
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { declarationStart, groupLenses, indentColumns } from "./codeLens";
import { EditorView } from "@codemirror/view";
import { codeLenses } from "@/editor/api";
import { codeLensExtension, codeLensPositions, declarationStart, groupLenses, indentColumns } from "./codeLens";
const doc = (text: string) => EditorState.create({ doc: text });
@@ -34,3 +36,44 @@ describe("code lens layout", () => {
expect(indentColumns(" x", 4)).toBe(4);
});
});
describe("code lens position", () => {
const doc = "@contextmanager\ndef lifespan(app):\n pass\n";
const lenses = [
{ pos: 16, title: "1 usage", kind: "usages", order: 10 },
{ pos: 16, title: "Denis", kind: "author", order: 20 },
];
const view = (positions: Record<string, "top" | "right">) =>
new EditorView({
state: EditorState.create({
doc,
extensions: [codeLensExtension, codeLenses.of(lenses), codeLensPositions.of(positions)],
}),
parent: document.body,
});
const texts = (els: NodeListOf<Element>) => [...els].map((e) => e.textContent);
it("puts every lens on a row above the declaration by default, with no separators", () => {
const v = view({});
expect(texts(v.dom.querySelectorAll(".cm-openidea-lens"))).toEqual(["1 usageDenis"]);
expect(v.dom.querySelector(".cm-openidea-lens")?.closest(".cm-line")).toBeNull();
expect(v.dom.querySelector(".cm-openidea-lensInline")).toBeNull();
v.destroy();
});
it("puts each kind where its setting says: usages at the line end, the author above", () => {
const v = view({ usages: "right" });
expect(texts(v.dom.querySelectorAll(".cm-openidea-lens"))).toEqual(["Denis"]);
const inline = v.dom.querySelector(".cm-openidea-lensInline");
expect(inline?.textContent).toBe("1 usage");
expect(inline?.closest(".cm-line")?.textContent).toBe("@contextmanager1 usage");
v.destroy();
});
it("puts both at the line end", () => {
const v = view({ usages: "right", author: "right" });
expect(v.dom.querySelector(".cm-openidea-lens")).toBeNull();
expect(texts(v.dom.querySelectorAll(".cm-openidea-lensInline"))).toEqual(["1 usageDenis"]);
v.destroy();
});
});
+59 -30
Переглянути файл
@@ -1,14 +1,24 @@
/**
* Renders `codeLenses` (editor/api) as one small hint row above the target
* line, indented like the line (IDEA "3 usages | Run test" inlays).
* line, indented like the line (IDEA "3 usages Run test" inlays), and those
* whose kind is set to "right" (`codeLensPositions`) after the end of that line.
*/
import { EditorState, RangeSetBuilder, type Extension } from "@codemirror/state";
import { EditorState, Facet, RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { getIndentUnit } from "@codemirror/language";
import { codeLenses, type CodeLens } from "@/editor/api";
import { guideVars, rainbowGuides } from "./indentGuides";
import { LINE_INSET } from "./lineInset";
/**
* Where code lenses of each kind (`CodeLens.kind`) go: a row above the declaration (IDEA's default, also for
* kinds not listed) or after the end of its line.
*/
export const codeLensPositions = Facet.define<
Readonly<Record<string, "top" | "right">>,
Readonly<Record<string, "top" | "right">>
>({ combine: (v) => Object.assign({}, ...v) });
/** Groups lenses by line start, ordered by line then `order`. Exported for tests. */
export function groupLenses(
state: EditorState,
@@ -71,12 +81,15 @@ class LensWidget extends WidgetType {
readonly indent: number,
readonly indentUnit: number,
readonly rainbow: boolean,
/** After the end of the line instead of a row above it. */
readonly inline = false,
) {
super();
}
private get key(): string {
return (
(this.inline ? "inline\u0000" : "") +
this.indent +
"\u0000" +
this.indentUnit +
@@ -92,8 +105,9 @@ class LensWidget extends WidgetType {
}
override toDOM(view: EditorView): HTMLElement {
const dom = document.createElement("div");
dom.className = "cm-openidea-lens";
// The inline one shares no class with the row, so none of the row's block styles reach into the line.
const dom = document.createElement(this.inline ? "span" : "div");
dom.className = this.inline ? "cm-openidea-lensInline" : "cm-openidea-lens";
this.fill(dom, view);
return dom;
}
@@ -105,9 +119,11 @@ class LensWidget extends WidgetType {
private fill(dom: HTMLElement, view: EditorView) {
dom.textContent = "";
dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`;
// The guides of the annotated line continue through this row while indent guides are on.
const guides = guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow);
const guides = this.inline
? null
: guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow);
if (!this.inline) dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`;
if (guides) {
dom.style.setProperty("--openidea-guide-images", guides.images);
dom.style.setProperty("--openidea-guide-positions", guides.positions);
@@ -117,14 +133,7 @@ class LensWidget extends WidgetType {
}
dom.setAttribute("role", "group");
dom.setAttribute("aria-label", "Code lens");
this.lenses.forEach((lens, i) => {
if (i > 0) {
const sep = document.createElement("span");
sep.className = "cm-openidea-lensSep";
sep.textContent = "|";
sep.setAttribute("aria-hidden", "true");
dom.appendChild(sep);
}
for (const lens of this.lenses) {
const el = document.createElement(lens.run ? "button" : "span");
el.className = lens.run ? "cm-openidea-lensItem cm-openidea-lensAction" : "cm-openidea-lensItem";
if (lens.tooltip) el.title = lens.tooltip;
@@ -154,11 +163,11 @@ class LensWidget extends WidgetType {
});
}
dom.appendChild(el);
});
}
}
override get estimatedHeight(): number {
return 16;
return this.inline ? -1 : 16;
}
override ignoreEvent(): boolean {
@@ -169,16 +178,28 @@ class LensWidget extends WidgetType {
function buildDecorations(state: EditorState): DecorationSet {
const lenses = state.facet(codeLenses);
if (!lenses.length) return Decoration.none;
const positions = state.facet(codeLensPositions);
const right = (l: CodeLens) => !!l.kind && positions[l.kind] === "right";
const builder = new RangeSetBuilder<Decoration>();
for (const group of groupLenses(state, lenses)) {
const line = state.doc.lineAt(group.lineFrom);
const widget = new LensWidget(
group.lenses,
indentColumns(line.text, state.tabSize),
Math.max(1, getIndentUnit(state)),
state.facet(rainbowGuides),
);
builder.add(line.from, line.from, Decoration.widget({ widget, block: true, side: -1 }));
const indent = indentColumns(line.text, state.tabSize);
const unit = Math.max(1, getIndentUnit(state));
const rainbow = state.facet(rainbowGuides);
const above = group.lenses.filter((l) => !right(l));
const after = group.lenses.filter(right);
if (above.length)
builder.add(
line.from,
line.from,
Decoration.widget({ widget: new LensWidget(above, indent, unit, rainbow), block: true, side: -1 }),
);
if (after.length)
builder.add(
line.to,
line.to,
Decoration.widget({ widget: new LensWidget(after, indent, unit, rainbow, true), side: 1 }),
);
}
return builder.finish();
}
@@ -187,7 +208,7 @@ const lensTheme = EditorView.theme({
".cm-openidea-lens": {
display: "flex",
alignItems: "center",
gap: "6px",
gap: "12px",
height: "16px",
color: "var(--fg-muted)",
WebkitUserSelect: "none",
@@ -195,29 +216,37 @@ const lensTheme = EditorView.theme({
whiteSpace: "nowrap",
overflow: "hidden",
},
// "right": after the line's text, on its baseline, with IDEA's spacing.
".cm-openidea-lensInline": {
display: "inline-flex",
alignItems: "baseline",
gap: "12px",
marginLeft: "12px",
color: "var(--fg-muted)",
WebkitUserSelect: "none",
userSelect: "none",
whiteSpace: "nowrap",
},
".cm-openidea-lensItem": {
display: "inline-flex",
alignItems: "center",
gap: "3px",
gap: "4px",
padding: "0",
border: "none",
background: "none",
font: "inherit",
color: "inherit",
},
// The row keeps the editor font so its `ch`-based indent guides line up with the code.
".cm-openidea-lensItem, .cm-openidea-lensSep": {
// The items take the UI font; the row keeps the editor's, so its `ch`-based indent guides line up with the code.
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-tiny)",
},
".cm-openidea-lensAction": { cursor: "pointer" },
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
".cm-openidea-lensSep": { color: "var(--fg-faint)" },
".cm-openidea-lensIcon-run": { color: "var(--success)" },
});
/** Base extension (always installed): no cost until a provider contributes lenses. */
export const codeLensExtension: Extension = [
EditorView.decorations.compute([codeLenses, rainbowGuides], buildDecorations),
EditorView.decorations.compute([codeLenses, rainbowGuides, codeLensPositions], buildDecorations),
lensTheme,
];
+21 -1
Переглянути файл
@@ -355,7 +355,27 @@ export const commentBlock: Command = (view) => {
/** ⌘/ in a language without line comments (CSS, HTML…): the block comment of the lines. */
function blockCommentLines(view: EditorView): boolean {
return uncommentBlock(view, selectedLines(view.state)) || toggleComment(view);
const ranges = selectedLines(view.state);
if (uncommentBlock(view, ranges)) return true;
const { state } = view;
if (
ranges.every(
(r) =>
state.sliceDoc(r.from, r.from + 1) === "{" &&
commentPairs(state, state.doc.lineAt(r.from).from)[0]?.open === "{/*",
)
) {
view.dispatch({
changes: ranges.flatMap((r) => [
{ from: r.from, insert: "{/* " },
{ from: r.to, insert: " */}" },
]),
scrollIntoView: true,
userEvent: "input.comment",
});
return true;
}
return toggleComment(view);
}
// --- Enter in a line comment ------------------------------------------------------
+21
Переглянути файл
@@ -419,6 +419,27 @@ describe("toggle comment where the tokens depend on the syntax context", () => {
// JavaScript, where the tokens are `/* … */`.
const wrap = (body: string) => `const a = (\n <div>\n ${body}\n </div>\n);`;
it.each(["JSX", "TSX"])("comments a JSX expression child with Ctrl+/ in %s", async (name) => {
const mode = await languages.find((l) => l.name === name)!.load();
const v = make("const view = <section>\n |{label}\n</section>;", mode);
commentLine(v);
expect(v.state.doc.line(2).text).toBe(" {/* {label} */}");
commentLine(v);
expect(v.state.doc.toString()).toBe("const view = <section>\n {label}\n</section>;");
});
it.each(["JSX", "TSX"])("comments a selected JSX child subtree with Ctrl+/ in %s", async (name) => {
const mode = await languages.find((l) => l.name === name)!.load();
const original = "const view = <main>\n <aside>\n <strong>ready</strong>\n </aside>\n</main>;";
const v = make(original.replace("<aside>", "[<aside>").replace("</aside>", "</aside>]"), mode);
commentLine(v);
expect(v.state.doc.toString()).toBe(
"const view = <main>\n {/* <aside>\n <strong>ready</strong>\n </aside> */}\n</main>;",
);
commentLine(v);
expect(v.state.doc.toString()).toBe(original);
});
it("takes a JSX line comment back out, with the caret", async () => {
const tsx = await languages.find((l) => l.name === "TSX")!.load();
const v = make(wrap("|</div>"), tsx);
+7 -1
Переглянути файл
@@ -54,6 +54,7 @@ import { skipClosingQuote, smartBackspace, smartBackspaceApplies, tabOut } from
import { stringClipboard } from "./stringClipboard";
import { filterCopiedText } from "./clipboard";
import { LINE_INSET } from "./lineInset";
import { codeLensPositions } from "./codeLens";
// --- soft wraps ---------------------------------------------------------------
@@ -557,7 +558,12 @@ export function prefsExtension(o: PrefsOptions): Extension {
const { prefs } = o;
const g = prefs.general;
const k = prefs.smartKeys;
const out: Extension[] = [];
const out: Extension[] = [
codeLensPositions.of({
usages: prefs.inlay.codeVisionUsagesPosition,
author: prefs.inlay.codeVisionAuthorPosition,
}),
];
if (!o.readOnly)
out.push(markdownImages({ path: o.path, folder: g.markdownImageFolder, pattern: g.markdownImageNamePattern }));
if (g.scrollPastEnd) out.push(scrollPastEnd());
+54
Переглянути файл
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { BlockType, RectangleMarker, type BlockInfo } from "@codemirror/view";
import {
alignLeftEdges,
dropInsetSlivers,
cutOutGaps,
fillGaps,
fillRowEnds,
@@ -249,3 +251,55 @@ describe("fillGaps", () => {
expect(fillGaps(rows, C, [], 0, 300)).toEqual(rows);
});
});
describe("alignLeftEdges", () => {
const C = "sel";
it("moves rectangles at the real line start to the rounded one and keeps their right edges", () => {
const out = alignLeftEdges(
[new RectangleMarker(C, 40.5, 0, 100, 20), new RectangleMarker(C, 40, 20, 300, 20)],
C,
40.5,
40,
);
expect(out.map((m) => [m.left, m.left + m.width!])).toEqual([
[40, 140.5],
[40, 340],
]);
});
it("leaves rectangles that start elsewhere, and everything when the inset is whole", () => {
const m = new RectangleMarker(C, 80, 0, 50, 20);
expect(alignLeftEdges([m], C, 40.5, 40)).toEqual([m]);
const at = new RectangleMarker(C, 40, 0, 50, 20);
expect(alignLeftEdges([at], C, 40, 40)).toEqual([at]);
});
});
describe("dropInsetSlivers", () => {
const C = "sel";
it("drops rectangles covering only the inset before the text", () => {
const row = new RectangleMarker(C, 40, 0, 300, 20);
expect(dropInsetSlivers([row, new RectangleMarker(C, 40, 20, 0.5, 20)], 40, 40.5)).toEqual([row]);
});
it("leaves the middle rows whole when dropped after growing the rows", () => {
// Rows of 20px; the selection runs from row 0 to the start of row 3, where CodeMirror draws a sliver.
const rowAt = (y: number) => ({ top: Math.floor(y / 20) * 20, bottom: Math.floor(y / 20) * 20 + 20 });
const drawn = [
new RectangleMarker(C, 60, 2, 280, 16),
new RectangleMarker(C, 40, 18, 300, 44),
new RectangleMarker(C, 40, 62, 0.5, 16),
];
const out = dropInsetSlivers(growToLineBoxes(drawn, C, rowAt), 40, 40.5);
expect(out.map((m) => [m.top, m.top + m.height])).toEqual([
[0, 20],
[20, 60],
]);
});
it("keeps rectangles that reach into the text or start elsewhere", () => {
const into = new RectangleMarker(C, 40, 0, 8, 20);
const mid = new RectangleMarker(C, 80, 0, 0.5, 20);
expect(dropInsetSlivers([into, mid], 40, 40.5)).toEqual([into, mid]);
});
});
+54 -3
Переглянути файл
@@ -157,6 +157,35 @@ export function cutOutGaps(
return out;
}
/**
* Moves the rectangles that start at `from` to `to`, keeping their right edges. CodeMirror starts the rows a selection
* runs through from the line start at the lines' left padding rounded down to whole pixels (`parseInt`), and a row
* that starts at a line's first character at the real padding, so with a fractional inset one row of a selection
* started a device pixel to the right of the others.
*/
export function alignLeftEdges(
markers: readonly RectangleMarker[],
className: string,
from: number,
to: number,
): RectangleMarker[] {
if (Math.abs(to - from) < 0.01) return [...markers];
return markers.map((m) =>
m.width !== null && Math.abs(m.left - from) < 0.01
? new RectangleMarker(className, to, m.top, m.width - (to - from), m.height)
: m,
);
}
/**
* Drops the rectangles that start at `from` and end by `to`, covering only the inset before a line's text. A selection
* that ends at the start of a line made CodeMirror paint that line from its rounded edge (`from`) to the first
* character (`to`): a sliver left of the text, a device pixel wide with a fractional inset. IDEA paints nothing there.
*/
export function dropInsetSlivers(markers: readonly RectangleMarker[], from: number, to: number): RectangleMarker[] {
return markers.filter((m) => m.width === null || Math.abs(m.left - from) >= 0.01 || m.left + m.width > to + 0.01);
}
/** Adds one rectangle from `left` to `right` over each of `gaps` (layer coordinates). */
export function fillGaps(
markers: readonly RectangleMarker[],
@@ -206,6 +235,21 @@ function lineRightEdge(view: EditorView): { rightSide: number; pad: number } {
return { rightSide: view.contentDOM.getBoundingClientRect().right - pad - base, pad };
}
/**
* Where CodeMirror starts a selection running through a line start (`rounded`: the left padding cut to whole pixels)
* and where it starts one beginning at a line's first character (`real`: the padding as it is), in layer coordinates.
*/
function lineLeftEdge(view: EditorView): { rounded: number; real: number } | null {
const line = view.contentDOM.querySelector(".cm-line");
if (!line) return null;
const style = getComputedStyle(line);
const scroller = view.scrollDOM.getBoundingClientRect();
const left = view.contentDOM.getBoundingClientRect().left - (scroller.left - view.scrollDOM.scrollLeft * view.scaleX);
const rounded = left + parseInt(style.paddingLeft) + Math.min(0, parseInt(style.textIndent));
const real = left + parseFloat(style.paddingLeft) + Math.min(0, parseFloat(style.textIndent));
return Number.isFinite(rounded) && Number.isFinite(real) ? { rounded, real } : null;
}
/** Layer y = document y + this offset. */
function layerOffset(view: EditorView): number {
const scroller = view.scrollDOM.getBoundingClientRect();
@@ -275,6 +319,7 @@ const snappedSelectionLayer = layer({
if (!ranges.length) return [];
const dpr = window.devicePixelRatio || 1;
const edge = view.textDirection === Direction.LTR ? lineRightEdge(view) : null;
const start = view.textDirection === Direction.LTR ? lineLeftEdge(view) : null;
const offset = layerOffset(view);
const out: RectangleMarker[] = [];
for (const r of ranges) {
@@ -285,15 +330,21 @@ const snappedSelectionLayer = layer({
first: hasTextBlockAt(view, from, 1),
last: hasTextBlockAt(view, to, -1),
});
if (!lines.length) continue;
// The sliver CodeMirror draws on a line the selection ends at the start of marks that line as the last row for
// growToLineBoxes, so it goes only after the rows are grown. Then every row starts at the rounded edge: a pixel
// left of the text, as IDEA leaves a gap between them.
const aligned = start
? alignLeftEdges(dropInsetSlivers(lines, start.rounded, start.real), CLASS, start.real, start.rounded)
: lines;
if (!aligned.length) continue;
const full = edge
? fillRowEnds(
widenToRightEdge(lines, CLASS, edge.rightSide, edge.pad),
widenToRightEdge(aligned, CLASS, edge.rightSide, edge.pad),
CLASS,
rowsPastEnd(view, offset, r),
edge.rightSide + edge.pad,
)
: lines;
: aligned;
// Block widgets: cut them all out of CodeMirror's rectangles, then paint the ones the selection runs through
// with one rectangle each, so a translucent selection colour never doubles up over them.
const widgets = lineWidgets(view, offset, r);
+1 -1
Переглянути файл
@@ -1463,7 +1463,7 @@ export class EditorController implements SlotHost {
}
try {
const encoding = await this.manager.backend.setEncoding(meta.doc, meta.encoding, true);
model.setMeta({ encoding });
model.setMeta({ encoding: encoding.encoding, hasBom: encoding.hasBom });
} catch (e) {
notifications().notify({
level: "error",
+2
Переглянути файл
@@ -82,6 +82,7 @@ export interface DocMeta {
language: string;
uiMode: string | null;
encoding: string;
hasBom: boolean;
lineEnding: LineEnding;
readOnly: boolean;
dirty: boolean;
@@ -248,6 +249,7 @@ export class DocModel {
language: info.language,
uiMode: uiMode ?? this.desc?.name ?? null,
encoding: info.encoding,
hasBom: info.hasBom,
lineEnding: info.lineEnding,
// Library sources (External Libraries) open read-only, like IDEA's.
readOnly: info.readOnly || (!this.virtual && isLibraryPath(info.path)),
+35 -2
Переглянути файл
@@ -352,6 +352,7 @@ const ENCODINGS = ENCODING_CHOICES;
/** File encoding widget (IDEA: click → choose an encoding, then Reload or Convert). */
export function EncodingStatus() {
const meta = useActiveMeta();
const prefs = useEditorPrefs();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
if (!meta) return null;
@@ -360,7 +361,7 @@ export function EncodingStatus() {
if (!model) return;
void editorController()
.manager.backend.setEncoding(meta.doc, encoding, reload)
.then((enc) => model.setMeta({ encoding: enc, ...(reload ? {} : { dirty: true }) }))
.then((enc) => model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, ...(reload ? {} : { dirty: true }) }))
.catch((e: unknown) =>
notifications().notify({
level: "error",
@@ -370,6 +371,27 @@ export function EncodingStatus() {
);
};
const current = meta.encoding.toLowerCase();
const nativeToAsciiProperties = prefs.encodings.nativeToAscii && meta.path.endsWith(".properties");
const canToggleBom = current === "utf-8" && !nativeToAsciiProperties;
const label = ENCODINGS.find(([id]) => id === current)?.[1] ?? meta.encoding;
const applyBom = (hasBom: boolean) => {
const controller = editorController();
const model = controller.manager.get(meta.path);
if (!model) return;
void controller.manager.backend
.setBom(meta.doc, hasBom)
.then(async (enc) => {
model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, dirty: true });
if (controller.autoSave()) await model.save("auto");
})
.catch((e: unknown) =>
notifications().notify({
level: "error",
title: tx("Cannot change the UTF-8 BOM"),
body: e instanceof Error ? e.message : String(e),
}),
);
};
const group = (reload: boolean) =>
ENCODINGS.filter(([id]) => id !== current).map(([id, label]) => ({
id: `${reload ? "reload" : "convert"}.${id}`,
@@ -385,7 +407,7 @@ export function EncodingStatus() {
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
>
{ENCODINGS.find(([id]) => id === current)?.[1] ?? meta.encoding}
{meta.hasBom ? `${label} BOM` : label}
</BarButton>
<Menu
open={open}
@@ -396,6 +418,17 @@ export function EncodingStatus() {
items={[
{ id: "reload", label: "Reload with Encoding", disabled: meta.dirty, submenu: group(true) },
{ id: "convert", label: "Convert to Encoding", disabled: meta.readOnly, submenu: group(false) },
...(canToggleBom
? [
{ kind: "separator" as const },
{
id: "toggle-bom",
label: meta.hasBom ? "Remove UTF-8 BOM" : "Add UTF-8 BOM",
disabled: meta.readOnly,
run: () => applyBom(!meta.hasBom),
},
]
: []),
{ kind: "separator" },
{
id: "configure",
+12
Переглянути файл
@@ -118,6 +118,18 @@ describe("background usage counts", () => {
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it('leaves out "no usages" when Show “no usages” is off', async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
useProject.setState({
settings: {
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false, codeVisionNoUsages: false } },
} as never,
});
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
});
it("does not cache an incomplete count while indexing, and retries on server refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
+10 -2
Переглянути файл
@@ -233,14 +233,22 @@ class UsagesLensPlugin {
const offset = posToOffset(text, { line: t.line, col: t.col });
const who = lines && authorSummary(lines, t.startLine, t.endLine);
if (who)
lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 });
lenses.push({
pos: offset,
title: authorLabel(who),
tooltip: authorTooltip(who),
icon: "user",
order: 20,
kind: "author",
});
const n = usages ? this.cache.get(key(t)) : undefined;
if (n === undefined) continue;
if (n === undefined || (n === 0 && !editorPrefs().inlay.codeVisionNoUsages)) continue;
lenses.push({
pos: offset,
title: usagesLabel(n),
tooltip: tx`Show usages of ${t.name}`,
order: 10,
kind: "usages",
run: (v) => openUsages(v, Math.min(offset, v.state.doc.length)),
});
}
+18 -18
Переглянути файл
@@ -32,6 +32,7 @@ import {
nodeLabel,
profileChecked,
withGradleOptions,
gradleHasTestTask,
type BuildNode,
} from "./model";
import {
@@ -64,7 +65,9 @@ export function nodeConfig(
const first = nodes[0];
if (!first) return null;
if (first.kind === "runConfig")
return first.config.kind === "gradle" ? withGradleOptions(first.config, settings.gradle) : first.config;
return first.config.kind === "gradle"
? withGradleOptions(first.config, settings.gradle, gradleHasTestTask(model.gradle ?? []))
: first.config;
if ((first.kind === "phase" || first.kind === "goal") && model.maven) {
const same = nodes.filter(
(n): n is Extract<BuildNode, { kind: "phase" | "goal" }> =>
@@ -168,15 +171,13 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
iconSize={16}
action={maven ? "maven.analyzeDependencies" : "gradle.analyzeDependencies"}
/>
{maven && (
<IconButton
icon="skip-tests"
size="small"
iconSize={16}
action="maven.toggleSkipTests"
pressed={settings.maven.skipTests}
/>
)}
<IconButton
icon="skip-tests"
size="small"
iconSize={16}
action={`${tool}.toggleSkipTests`}
pressed={maven ? settings.maven.skipTests : settings.gradle.skipTests}
/>
<span className={styles.sep} />
<IconButton icon="expand-all" size="small" iconSize={16} action={`${tool}.expandAll`} />
<IconButton icon="collapse-all" size="small" iconSize={16} action={`${tool}.collapseAll`} />
@@ -234,7 +235,9 @@ function BuildBanner({ info, tool }: { info: MavenModel | GradleModel; tool: Bui
function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
const choices = useBuild((s) => s.settings.maven.profiles);
const skipTests = useBuild((s) => s.settings.maven.skipTests);
// Each toggle strikes through only its own tool's tree: the Maven `test` phase, or the Gradle `test` task.
const mavenSkipTests = useBuild((s) => s.settings.maven.skipTests);
const gradleSkipTests = useBuild((s) => s.settings.gradle.skipTests);
if (node.kind === "profile") {
return (
<span className={styles.row} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
@@ -257,16 +260,13 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
: node.kind === "task"
? node.task.description
: null;
const skipped =
(mavenSkipTests && node.kind === "phase" && node.phase === "test") ||
(gradleSkipTests && node.kind === "task" && node.task.name === "test");
return (
<span className={styles.row} title={node.kind === "task" ? (node.task.description ?? undefined) : undefined}>
<Icon name={nodeIcon(node)} size={16} className={styles.icon} />
<span
className={clsx(
styles.label,
state.selected && styles.selectedLabel,
skipTests && node.kind === "phase" && node.phase === "test" && styles.skippedGoal,
)}
>
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
{nodeLabel(node)}
</span>
{detail && <span className={styles.detail}>{detail}</span>}
+60
Переглянути файл
@@ -174,4 +174,64 @@ describe("build tools feature", () => {
render(<GradleView />);
expect(screen.getByText("test")).not.toHaveClass(styles.skippedGoal!);
});
it("toggles Gradle Skip Tests and runs tasks with -x test", async () => {
const started: unknown[] = [];
const off = registerAction({
id: "run.runConfig",
title: "Run",
hidden: true,
run: ({ arg }) => void started.push(arg),
});
const build = {
dir: "",
projects: [
{
path: ":",
name: "demo",
dir: "",
buildFile: "build.gradle.kts",
tasks: [{ name: "test", group: "verification", description: null }],
},
],
command: "/p/gradlew",
env: {},
javaVersion: null,
syncedAt: null,
stale: false,
syncError: null,
};
const key = gradleProjectKey(build, build.projects[0]!);
act(() =>
useBuild.setState({
root: "/p",
model: { maven: mavenModel.maven, gradle: [build] },
expanded: { maven: new Set(), gradle: new Set([key, `${key}:tasks`, `${key}:tasks:verification`]) },
}),
);
await executeAction("gradle.toggleSkipTests");
expect(useBuild.getState().settings.gradle).toMatchObject({ skipTests: true });
expect(JSON.parse(localStorage.getItem("openidea.buildTools:/p")!).gradle.skipTests).toBe(true);
expect(
allActions()
.find((a) => a.id === "gradle.toggleSkipTests")!
.toggled?.(),
).toBe(true);
render(<GradleView />);
const task = screen.getByText("test");
expect(task).toHaveClass(styles.skippedGoal!);
await act(async () => {
task.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
});
off();
expect(started).toHaveLength(1);
const { config } = started[0] as { config: RunConfig };
expect(config).toMatchObject({
name: "demo [test]",
command: "/p/gradlew",
args: ["test", "-x", "test"],
kind: "gradle",
isTest: false,
});
});
});
+12
Переглянути файл
@@ -51,6 +51,7 @@ import {
generateSources,
syncTool,
toggleGradleOffline,
toggleGradleSkipTests,
toggleMavenOffline,
toggleSkipTests,
useBuild,
@@ -451,6 +452,17 @@ export function activate(): () => void {
toggled: () => useBuild.getState().settings.gradle.offline,
run: () => toggleGradleOffline(),
},
{
id: "gradle.toggleSkipTests",
title: "Toggle 'Skip Tests' Mode",
description: "Runs Gradle with -x test",
category: "Gradle",
icon: "skip-tests",
when: GRADLE_WHEN,
keywords: ["gradle", "skip tests"],
toggled: () => useBuild.getState().settings.gradle.skipTests,
run: () => toggleGradleSkipTests(),
},
{
id: "gradle.expandAll",
title: "Expand All",
+1 -1
Переглянути файл
@@ -378,7 +378,7 @@ it("runs duplicate task paths with the selected build's wrapper, cwd and offline
model,
expanded: { maven: new Set(), gradle: expanded },
current: { gradle: gradleProjectKey(builds[1]!, builds[1]!.projects[1]!) },
settings: { ...useBuild.getState().settings, gradle: { offline: true } },
settings: { ...useBuild.getState().settings, gradle: { offline: true, skipTests: false } },
}),
);
const started: RunConfig[] = [];
+54 -4
Переглянути файл
@@ -20,6 +20,8 @@ import {
profilesArg,
splitArgs,
taskCompletions,
withGradleOptions,
gradleHasTestTask,
type BuildNode,
} from "./model";
@@ -324,7 +326,7 @@ describe("Gradle tree and runs", () => {
it("runs tasks by path from the build directory", () => {
const app = gradle.projects[1]!;
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true });
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true, skipTests: false });
expect(config).toMatchObject({
name: "app [test]",
kind: "gradle",
@@ -335,13 +337,61 @@ describe("Gradle tree and runs", () => {
env: {},
isTest: true,
});
expect(gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false }).args).toEqual(["wrapper"]);
expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false }).args).toEqual([
expect(
gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false, skipTests: false }).args,
).toEqual(["wrapper"]);
expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false, skipTests: false }).args).toEqual([
":lib:jar",
"--info",
]);
});
it("appends -x test to task runs when Skip Tests is on", () => {
const app = gradle.projects[1]!;
const skipped = gradleTaskConfig(gradle, app, ["build"], { offline: false, skipTests: true });
expect(skipped.args).toEqual([":app:build", "-x", "test"]);
// Running `test` with Skip Tests on is not a test run for the Run window.
const test = gradleTaskConfig(gradle, app, ["test"], { offline: false, skipTests: true });
expect(test.args).toEqual([":app:test", "-x", "test"]);
expect(test.isTest).toBe(false);
// A command line that already excludes tests is not changed again (typed task names keep
// the pre-existing project-path prefix).
const explicit = gradleTaskConfig(gradle, app, ["build", "-x", "test"], { offline: false, skipTests: true });
expect(explicit.args).toEqual([":app:build", "-x", ":app:test"]);
const verbose = gradleTaskConfig(gradle, app, ["build", "--exclude-task", "test"], {
offline: false,
skipTests: true,
});
expect(verbose.args).toEqual([":app:build", "--exclude-task", ":app:test"]);
// A build without a `test` task would fail on `-x test`.
const noTests = {
...gradle,
projects: gradle.projects.map((p) => ({ ...p, tasks: p.tasks.filter((t) => t.name !== "test") })),
};
expect(gradleHasTestTask([noTests])).toBe(false);
expect(
gradleTaskConfig(noTests, noTests.projects[1]!, ["build"], { offline: false, skipTests: true }).args,
).toEqual([":app:build"]);
});
it("applies the toolbar toggles to saved configurations started from the tree", () => {
const saved = runConfig({ id: "g", name: "app [build]", kind: "gradle", args: ["build"] });
expect(withGradleOptions(saved, { offline: false, skipTests: false }).args).toEqual(["build"]);
expect(withGradleOptions(saved, { offline: true, skipTests: false }).args).toEqual(["build", "--offline"]);
expect(withGradleOptions(saved, { offline: true, skipTests: true }).args).toEqual([
"build",
"--offline",
"-x",
"test",
]);
const excluding = withGradleOptions(runConfig({ ...saved, args: ["build", "-x", "test"] }), {
offline: false,
skipTests: true,
});
expect(excluding.args).toEqual(["build", "-x", "test"]);
expect(withGradleOptions(saved, { offline: false, skipTests: true }, false).args).toEqual(["build"]);
});
it("keeps identical project paths and tasks of independent builds distinct", () => {
const builds = ["first", "second"].map((dir) => ({
...gradle,
@@ -361,7 +411,7 @@ describe("Gradle tree and runs", () => {
return gradleChildren(group, builds, [])![0]!;
});
expect(tasks[0]!.key).not.toBe(tasks[1]!.key);
const runs = builds.map((b) => gradleTaskConfig(b, b.projects[1]!, ["test"], { offline: true }));
const runs = builds.map((b) => gradleTaskConfig(b, b.projects[1]!, ["test"], { offline: true, skipTests: false }));
expect(runs[0]!.id).not.toBe(runs[1]!.id);
expect(runs[1]).toMatchObject({
command: "/p/second/gradlew",
+34 -5
Переглянути файл
@@ -83,6 +83,8 @@ export interface MavenRunOptions {
export interface GradleRunOptions {
offline: boolean;
/** Skip Tests toolbar toggle: task runs get `-x test` (no Maven-style toggle exists in IDEA's Gradle window). */
skipTests: boolean;
}
// ---------------------------------------------------------------------------
@@ -514,6 +516,29 @@ export function gradleTaskPath(project: GradleProject, task: string): string {
return project.path === ":" ? task : `${project.path}:${task}`;
}
/**
* Whether one of the builds has a task named `test`: `-x test` fails the whole run with
* "Task 'test' not found" in a build without one (Kotlin Multiplatform, non-JVM builds).
*/
export function gradleHasTestTask(models: readonly GradleModel[]): boolean {
return models.some((m) => m.projects.some((p) => p.tasks.some((t) => t.name === "test")));
}
/** Whether the command line already excludes the `test` task (`-x test`, `-xtest`, `--exclude-task test`). */
function excludesTest(args: readonly string[]): boolean {
return args.some((a, i) => {
const value =
a === "-x" || a === "--exclude-task"
? args[i + 1]
: a.startsWith("--exclude-task=")
? a.slice("--exclude-task=".length)
: a.startsWith("-x")
? a.slice(2)
: undefined;
return value === "test";
});
}
export function gradleTaskConfig(
model: GradleModel,
project: GradleProject,
@@ -522,6 +547,8 @@ export function gradleTaskConfig(
): RunConfig {
const args = tasks.map((t) => (t.startsWith("-") || t.startsWith(":") ? t : gradleTaskPath(project, t)));
if (options.offline && !args.includes("--offline")) args.push("--offline");
// Typed task names are project-path prefixed above, so the typed line is the one to inspect.
if (options.skipTests && gradleHasTestTask([model]) && !excludesTest(tasks)) args.push("-x", "test");
const names = tasks.filter((t) => !t.startsWith("-"));
return {
id: `gradle:task:${JSON.stringify([model.dir, project.path])}:${tasks.join(" ")}`,
@@ -533,15 +560,17 @@ export function gradleTaskConfig(
// As for Maven: the Gradle JVM / `JAVA_HOME` is derived from Settings at launch, not frozen here.
env: {},
detected: false,
isTest: names.some((t) => /(^|:)(test|check|build|integrationTest)$/.test(t)),
isTest: !options.skipTests && names.some((t) => /(^|:)(test|check|build|integrationTest)$/.test(t)),
debugAdapter: null,
};
}
/** Applies the current toggles to a saved configuration started from the tree. */
export function withGradleOptions(config: RunConfig, options: GradleRunOptions): RunConfig {
if (!options.offline || config.args.includes("--offline")) return config;
return { ...config, args: [...config.args, "--offline"] };
/** Applies the current toggles to a saved configuration started from the tree (`hasTestTask`: see {@link gradleHasTestTask}). */
export function withGradleOptions(config: RunConfig, options: GradleRunOptions, hasTestTask = true): RunConfig {
let args = config.args;
if (options.offline && !args.includes("--offline")) args = [...args, "--offline"];
if (options.skipTests && hasTestTask && !excludesTest(args)) args = [...args, "-x", "test"];
return args === config.args ? config : { ...config, args };
}
// ---------------------------------------------------------------------------
+3 -1
Переглянути файл
@@ -45,7 +45,7 @@ export interface BuildSettings {
export const DEFAULT_SETTINGS: BuildSettings = {
maven: { offline: false, skipTests: false, profiles: {} },
gradle: { offline: false },
gradle: { offline: false, skipTests: false },
};
interface SyncState {
@@ -131,6 +131,8 @@ export const toggleSkipTests = () =>
updateSettings((s) => ({ ...s, maven: { ...s.maven, skipTests: !s.maven.skipTests } }));
export const toggleGradleOffline = () =>
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, offline: !s.gradle.offline } }));
export const toggleGradleSkipTests = () =>
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, skipTests: !s.gradle.skipTests } }));
/** Delay before reloading Maven after a profile toggle, so a few toggles in a row reload once. */
export const PROFILE_RELOAD_DELAY_MS = 800;
+28
Переглянути файл
@@ -3,6 +3,7 @@ import { IpcError } from "@/platform/ipc";
import { missingAdapter } from "../missingAdapter";
const unavailable = (message: string) => new IpcError({ kind: "unavailable", message });
const invalid = (message: string) => new IpcError({ kind: "invalidInput", message });
describe("missing debug adapters", () => {
it("offers OpenIDEA's debugpy when the interpreter has none", () => {
@@ -41,6 +42,33 @@ describe("missing debug adapters", () => {
});
});
it("offers to reinstall Delve when it is too old for the Go toolchain", () => {
const message =
"launch failed: Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 " +
"(maximum supported version 1.26, suppress this error with --check-go-version=false)";
// The failed `launch` response arrives as `invalidInput` (a DAP error, not a missing binary).
expect(missingAdapter("delve", invalid(message))).toMatchObject({
tool: "delve",
title: "Delve is too old for Go 1.27.0",
action: "Reinstall and Debug",
body: `${message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
});
});
it("offers the reinstall even when delve exited during startup", () => {
const e = unavailable(
"debug adapter `delve` exited during startup:\nVersion of Delve is too old for Go version go1.27.0",
);
expect(missingAdapter("delve", e)).toMatchObject({ tool: "delve", action: "Reinstall and Debug" });
});
it("keeps a Go launch that failed for another reason as a plain error", () => {
expect(missingAdapter("delve", invalid("launch failed: could not find project directory"))).toBeNull();
expect(
missingAdapter("delve", unavailable("debug adapter `delve` exited during startup:\nexit status 1")),
).toBeNull();
});
it("leaves other failures and adapters without an installer alone", () => {
expect(missingAdapter("js-debug", unavailable("connection refused"))).toBeNull();
expect(missingAdapter("js-debug", new Error("debug adapter `js-debug` not found"))).toBeNull();
+28
Переглянути файл
@@ -65,4 +65,32 @@ describe("debug start failures", () => {
expect.objectContaining({ title: "Cannot start debugger for Listen for Xdebug", body: PORT_IN_USE }),
);
});
it("offers to reinstall a Delve that is too old for the Go toolchain", async () => {
const notify = vi.fn();
provideNotificationService({ notify });
useDebug.setState({ sessions: {}, active: null, console: {} });
const message =
"launch failed: Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 " +
"(maximum supported version 1.26, suppress this error with --check-go-version=false)";
ipc.debugStart.mockResolvedValueOnce({ status: "error", error: { kind: "invalidInput", message, data: null } });
const go: LaunchConfig = {
name: "api: go run .",
adapter: "delve",
request: "launch",
program: "/p/api",
args: [],
cwd: "/p/api",
env: {},
extraJson: JSON.stringify({ mode: "debug" }),
};
expect(await startSession(go)).toBeNull();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
title: "Delve is too old for Go 1.27.0",
body: `${message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
actions: [expect.objectContaining({ label: "Reinstall and Debug" })],
}),
);
});
});
+26 -3
Переглянути файл
@@ -1,8 +1,10 @@
/**
* A debug adapter that is not installed: name it and offer the one-click install
* (ide-tools) followed by the same launch again, instead of a bare error.
* A debug adapter that is not installed, or an installed one that refuses the Go
* toolchain: name it and offer the one-click install / reinstall (ide-tools) followed
* by the same launch again, instead of a bare error.
*/
import { IpcError } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
/** Adapters the tools installer can provide (adapter id → tool name). */
const INSTALLABLE: Record<string, { tool: string; title: string }> = {
@@ -16,16 +18,37 @@ const INSTALLABLE: Record<string, { tool: string; title: string }> = {
"bash-debug": { tool: "bash-debug", title: "Bash Debug is not installed" },
};
/**
* Delve refuses a Go toolchain newer than it supports: the adapter starts, but its
* `launch` request fails with "Version of Delve is too old for Go version go1.27.0
* (maximum supported version 1.26, …)". The managed install is
* `go install github.com/go-delve/delve/cmd/dlv@latest`, so reinstalling updates it.
*/
const DELVE_TOO_OLD = /Version of Delve is too old for Go version go([\d.]+)/;
export interface MissingAdapter {
tool: string;
title: string;
body: string;
/** The action's label when "Install and Debug" doesn't fit (a stale adapter's reinstall). */
action?: string;
}
/** The install offer for a failed start, or null when the failure is something else. */
export function missingAdapter(adapter: string, e: unknown): MissingAdapter | null {
if (!(e instanceof IpcError)) return null;
if (adapter === "delve") {
const go = DELVE_TOO_OLD.exec(e.message)?.[1];
if (go)
return {
tool: "delve",
title: tx`Delve is too old for Go ${go}`,
body: `${e.message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
action: "Reinstall and Debug",
};
}
const entry = INSTALLABLE[adapter];
if (!entry || !(e instanceof IpcError) || e.kind !== "unavailable") return null;
if (!entry || e.kind !== "unavailable") return null;
if (adapter === "debugpy" && e.message.startsWith("debugpy is not installed")) {
return {
tool: entry.tool,
+1 -1
Переглянути файл
@@ -677,7 +677,7 @@ export async function startSession(
sticky: true,
actions: [
{
label: "Install and Debug",
label: missing.action ?? "Install and Debug",
run: () => void executeAction("tools.install", missing.tool).then(() => startSession(launch, options)),
},
],
+4 -1
Переглянути файл
@@ -34,6 +34,9 @@ const GROUP_ICONS: Record<string, string> = {
gems: "file-ruby",
};
/** SDK groups, which IDEA writes in angle brackets (`< 21 >`); library groups (`Maven: g:a:v`) go without. */
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust"]);
/** An archive's root (`/jdk/lib/src.zip!`): its entries live below `<archive>!/`. */
const isArchiveRoot = (path: string) => path.endsWith("!");
@@ -91,7 +94,7 @@ export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootC
order: 5,
readOnly: true,
children: groups.map((g) => ({
label: `< ${g.name} >`,
label: SDK_KINDS.has(g.kind) ? `< ${g.name} >` : g.name,
icon: GROUP_ICONS[g.kind] ?? "library",
children: g.roots.map((r) => ({
label: r.name,
+3 -1
Переглянути файл
@@ -64,7 +64,9 @@ describe("External Libraries", () => {
{ name: "Maven: g:a:1", kind: "maven", roots: [{ name: "a-1-sources.jar", path: "/m2/g/a/1/a-1-sources.jar!" }] },
])!;
expect(root.children?.[0]?.children?.map((c) => c.icon)).toEqual(["folder-library", "file-archive"]);
expect(root.children?.[1]).toMatchObject({ label: "< Maven: g:a:1 >", icon: "maven-project" });
// As in IDEA: SDKs in angle brackets, dependencies without.
expect(root.children?.[0]).toMatchObject({ label: "< temurin-21 >" });
expect(root.children?.[1]).toMatchObject({ label: "Maven: g:a:1", icon: "maven-project" });
dispose = setLibraryRoots("test", ["/jdk/lib/src.zip!"]);
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
});
+16
Переглянути файл
@@ -43,6 +43,22 @@ afterEach(() => {
const childLabels = (key: string) => (currentModel().children.get(key) ?? []).map((n) => n.label);
it("retains cached types only for members that remain in the same workspace", () => {
initProjectTree("/workspace", "Workspace", ["/go", "/web"]);
useProjectTree.setState({
projectTypes: new Map([
["/go", "go"],
["/web", "node"],
]),
});
initProjectTree("/workspace", "Workspace", ["/go", "/new"]);
expect([...useProjectTree.getState().projectTypes]).toEqual([["/go", "go"]]);
initProjectTree("/other-workspace", "Other workspace", ["/go"]);
expect(useProjectTree.getState().projectTypes.size).toBe(0);
});
describe("lazy loading", () => {
it("loads folders on demand and shares concurrent requests", async () => {
const spy = vi.spyOn(fs, "readDir");
+11 -2
Переглянути файл
@@ -321,16 +321,25 @@ export function initProjectTree(
clearTimeout(persistTimer);
modeExpanded.clear();
autoExpanded.clear();
const previousMode = get().mode;
const previous = get();
const previousMode = previous.mode;
const mode =
unity && previousMode === "project" ? "unity" : !unity && previousMode === "unity" ? "project" : previousMode;
// Keep the remaining members' types visible while the workspace is rescanned.
const projectTypes = new Map<string, ProjectType>();
if (root === previous.root && members) {
for (const member of members) {
const type = previous.projectTypes.get(member);
if (type) projectTypes.set(member, type);
}
}
set({
unity,
mode,
root,
name,
members,
projectTypes: new Map(),
projectTypes,
listings: new Map(),
expanded: initialExpanded(root, mode, members),
selected: new Set(),
+8
Переглянути файл
@@ -34,6 +34,14 @@
gap: 2px;
padding: 4px 0;
border-right: 1px solid var(--border);
min-height: 0;
/* A pane shorter than the buttons (the Services detail) scrolls them with the wheel
instead of growing the pane and adding a second scrollbar. */
overflow-y: auto;
scrollbar-width: none;
}
.toolbar::-webkit-scrollbar {
display: none;
}
.toolbarSep {
width: 16px;
+46 -48
Переглянути файл
@@ -59,15 +59,11 @@ export function sessionIcon(s: RunSession): string {
export function SessionPanel({
session,
onRerun,
onDebug,
onStop,
showLifecycle = true,
}: {
session: RunSession;
onRerun?: (() => void) | null;
/** Override the Debug button (Services: rerun the attached debugger's launch); null disables it. */
onDebug?: (() => void) | null;
onStop?: () => void;
/** False in the Services detail: the window's own toolbar already offers Run/Debug/Stop for the selection. */
showLifecycle?: boolean;
}) {
const updating = useApplicationUpdates((s) => s.ids.has(session.id));
const version = useRun((s) => s.versions[session.id] ?? 0);
@@ -169,48 +165,50 @@ export function SessionPanel({
return (
<div className={styles.session}>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Run actions")}>
<IconButton
icon="rerun"
title="Rerun"
shortcut={shortcutLabel("run.rerun")}
disabled={onRerun === null}
onClick={onRerun ?? (() => rerunSession(session.id))}
/>
{/* Switch the launch mode: the same configuration started under the debugger. */}
<IconButton
icon="debug"
title="Debug"
shortcut={shortcutLabel("run.debug")}
disabled={onDebug === null}
onClick={onDebug ?? (() => void debugSession(session.id))}
/>
{rt.tests && (
<IconButton
icon="rerun"
tone="danger"
title="Rerun Failed Tests"
shortcut={shortcutLabel("run.rerunFailed")}
disabled={!canRerunFailed}
onClick={() => void rerunFailed(session.id)}
/>
{showLifecycle && (
<>
<IconButton
icon="rerun"
title="Rerun"
shortcut={shortcutLabel("run.rerun")}
onClick={() => rerunSession(session.id)}
/>
{/* Switch the launch mode: the same configuration started under the debugger. */}
<IconButton
icon="debug"
title="Debug"
shortcut={shortcutLabel("run.debug")}
onClick={() => void debugSession(session.id)}
/>
{rt.tests && (
<IconButton
icon="rerun"
tone="danger"
title="Rerun Failed Tests"
shortcut={shortcutLabel("run.rerunFailed")}
disabled={!canRerunFailed}
onClick={() => void rerunFailed(session.id)}
/>
)}
<IconButton
icon="stop"
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
tone={running ? "danger" : "default"}
disabled={!running}
onClick={() => void stopSession(session.id)}
/>
{isUpdatable(session.config) && (
<IconButton
icon="refresh"
title="Update Application"
shortcut={shortcutLabel("run.updateApplication")}
disabled={session.status !== "running" || updating}
onClick={() => showApplicationUpdate(session.id)}
/>
)}
<div className={styles.toolbarSep} />
</>
)}
<IconButton
icon="stop"
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
tone={running || onStop ? "danger" : "default"}
disabled={!running && !onStop}
onClick={onStop ?? (() => void stopSession(session.id))}
/>
{isUpdatable(session.config) && (
<IconButton
icon="refresh"
title="Update Application"
shortcut={shortcutLabel("run.updateApplication")}
disabled={session.status !== "running" || updating}
onClick={() => showApplicationUpdate(session.id)}
/>
)}
<div className={styles.toolbarSep} />
{!rt.terminal && (
<>
<IconButton
+1 -2
Переглянути файл
@@ -44,7 +44,7 @@ import { invalidateGoModules } from "./goModules";
import { invalidatePythonPackages } from "./pythonPackages";
import { RunWidget } from "./RunWidget";
import { runConfigsRunAnything } from "./runAnything";
import { cleanupRemovedProject, recordRun, registerRunServiceActions, runServiceProvider } from "./services";
import { cleanupRemovedProject, registerRunServiceActions, runServiceProvider } from "./services";
import { liveServiceSession, serviceSessions } from "./serviceSessions";
import { ServiceImportHost } from "./serviceImport";
import { cmakeBuildId } from "./cmake";
@@ -158,7 +158,6 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
}
if (remoteDebugBlocked(config)) return;
if (!(await prepareLaunch(config, chain, show))) return;
recordRun(config.id);
// Python on a Docker / Compose target: debugpy in the container, the debugger attaches.
if (containerDebuggable(config) && getAction("debug.attach")) {
await debugInContainer(config);
-9
Переглянути файл
@@ -63,7 +63,6 @@ import {
} from "./remote";
import { onRunExited, resetRuns, saveUserConfigs, startRun, useRun } from "./store";
import { newConfigOfType } from "./types";
import { readRan } from "./services";
const cfg = (id: string, extra: Partial<RunConfig> = {}): RunConfig => ({
id,
@@ -357,14 +356,6 @@ describe("remote debugging", () => {
await executeAction("run.debugConfig", local.id);
expect(startConfig).toHaveBeenCalledWith(local);
});
it("remembers a non-Spring-Boot configuration accepted for debugging", async () => {
useProject.setState({ project: { root: "/remember-debug" } as never });
const local = cfg("python:debug", { debugAdapter: "debugpy" });
useRun.setState({ configs: [local], loaded: true });
await executeAction("run.debugConfig", local.id);
expect(readRan("/remember-debug")).toContain(local.id);
});
});
describe("coverage and profiling", () => {
+39 -77
Переглянути файл
@@ -18,9 +18,7 @@ import {
categorizedTypes,
runServiceProvider,
registerRunServiceActions,
DEFAULT_TYPES,
readHidden,
readRan,
readTypes,
runServiceItems,
sessionDetail,
@@ -107,7 +105,7 @@ describe("run configurations in Services", () => {
rerun: null,
show: () => {},
};
const build = (status: DebugServiceSession["status"]) => runServiceItems([c], [], [], [], {}, [{ ...d, status }]);
const build = (status: DebugServiceSession["status"]) => runServiceItems([c], [], [kind], {}, [{ ...d, status }]);
expect(build("running")[0]?.children?.[0]).toMatchObject({
key: "run:config:debug-app",
detail: "Debugging",
@@ -132,12 +130,10 @@ describe("run configurations in Services", () => {
rerun: null,
show: () => {},
};
const direct = runServiceItems([c], [r], DEFAULT_TYPES, [], {}, [d]);
const direct = runServiceItems([c], [r], ["spring-boot"], {}, [d]);
expect(direct[0]?.detail).toBe("1 running");
expect(direct[0]?.children?.[0]?.detail).toBe("Debugging");
const attached = runServiceItems([c], [{ ...r, status: "running" }], DEFAULT_TYPES, [], {}, [
{ ...d, processId: 7 },
]);
const attached = runServiceItems([c], [{ ...r, status: "running" }], ["spring-boot"], {}, [{ ...d, processId: 7 }]);
expect(attached[0]?.detail).toBe("1 running");
expect(attached[0]?.children).toHaveLength(1);
expect(attached[0]?.children?.[0]?.detail).toBe(":8080");
@@ -156,15 +152,15 @@ describe("run configurations in Services", () => {
rerun: null,
show: () => {},
};
expect(runServiceItems([c], [], DEFAULT_TYPES, [], {}, [d])[0]?.children?.[0]).toMatchObject({
expect(runServiceItems([c], [], ["spring-boot"], {}, [d])[0]?.children?.[0]).toMatchObject({
detail: ":8080",
icon: "debug",
dim: false,
});
// A paused debugger still wins over the announced port.
expect(
runServiceItems([c], [], DEFAULT_TYPES, [], {}, [{ ...d, status: "paused" }])[0]?.children?.[0]?.detail,
).toBe("Suspended");
expect(runServiceItems([c], [], ["spring-boot"], {}, [{ ...d, status: "paused" }])[0]?.children?.[0]?.detail).toBe(
"Suspended",
);
});
it("applies display order to detected and saved configurations of every language", () => {
@@ -176,7 +172,7 @@ describe("run configurations in Services", () => {
config("py-a", "python"),
config("py-b", "python"),
];
const items = runServiceItems(configs, [], ["spring-boot", "npm", "python"], [], {
const items = runServiceItems(configs, [], ["spring-boot", "npm", "python"], {
"spring-boot": ["java-b", "java-a"],
npm: ["node-b", "node-a"],
python: ["py-b", "py-a"],
@@ -194,23 +190,17 @@ describe("run configurations in Services", () => {
const second = { ...config("workspace:two:app", kind), cwd: "/workspace/two", module: "two" };
const fresh = config("workspace:two:new", kind);
const configs = [first, second, fresh];
const items = runServiceItems(configs, [], [kind], [], { [kind]: [second.id, first.id] });
const items = runServiceItems(configs, [], [kind], { [kind]: [second.id, first.id] });
expect(items[0]!.children!.map((c) => c.key)).toEqual([second, first, fresh].map((c) => `run:config:${c.id}`));
expect(configs).toEqual([first, second, fresh]);
});
it("orders remembered configurations when their type was not explicitly added", () => {
const items = runServiceItems([build, test], [], [], ["build", "test"], { cargo: ["test", "build"] });
expect(items[0]!.children!.map((c) => c.key)).toEqual(["run:config:test", "run:config:build"]);
});
it("keeps stable service identity and session details after refresh and rename", () => {
const renamed = { ...build, name: "Renamed build" };
const items = runServiceItems(
[renamed, test],
[session("s1", renamed, "running", 1, { httpPort: 8080 })],
["cargo"],
[],
{ cargo: ["test", "build"] },
);
expect(items[0]!.children!.map((c) => [c.key, c.label, c.detail])).toEqual([
@@ -219,27 +209,23 @@ describe("run configurations in Services", () => {
]);
});
it("lists added types fully and other types only with their runs", () => {
it("lists added types fully and keeps other types out", () => {
const sessions = [
session("s1", dev, "finished", 1),
session("s2", dev, "running", 2),
session("s3", scratch, "failed", 3, { exitCode: 2 }),
];
const items = runServiceItems([build, test, dev], sessions, ["cargo"]);
expect(items.map((i) => [i.key, i.label, i.detail])).toEqual([
["run:type:cargo", "Cargo", undefined],
["run:type:npm", "npm", "1 running"],
["run:type:python", "Python", undefined],
]);
expect(items.map((i) => [i.key, i.label, i.detail])).toEqual([["run:type:cargo", "Cargo", undefined]]);
expect(items[0]!.children!.map((c) => [c.key, c.detail, c.dim])).toEqual([
["run:config:build", undefined, true],
["run:config:test", undefined, true],
]);
// The newest session of a configuration decides its state.
expect(items[1]!.children!.map((c) => [c.label, c.detail, c.dim, c.icon])).toEqual([
// The newest session of a configuration decides its state once its type is added.
const npm = runServiceItems([dev], sessions, ["npm"]);
expect(npm[0]!.children!.map((c) => [c.label, c.detail, c.dim, c.icon])).toEqual([
["dev", "Running", false, "run"],
]);
expect(items[2]!.children!.map((c) => [c.key, c.detail])).toEqual([["run:config:context:file", "Failed (exit 2)"]]);
});
it("has no groups without added types or sessions", () => {
@@ -253,12 +239,14 @@ describe("run configurations in Services", () => {
expect(sessionStatus(session("a", build, "finished", 0))).toBe("Finished");
});
it("shows Spring Boot by default, hidden while the project has none", () => {
it("shows nothing for a type that was never added", () => {
const app = config("spring:app", "spring-boot");
expect(runServiceItems([build], [], DEFAULT_TYPES)).toEqual([]);
const items = runServiceItems([build, app], [], DEFAULT_TYPES);
expect(runServiceItems([build, app], [], [])).toEqual([]);
const items = runServiceItems([build, app], [], ["spring-boot"]);
expect(items.map((i) => [i.key, i.label, i.expanded])).toEqual([["run:type:spring-boot", "Spring Boot", true]]);
expect(items[0]!.children!.map((c) => [c.label, c.detail, c.dim])).toEqual([["spring:app", undefined, true]]);
// An added type stays listed without configurations until it is removed again.
expect(runServiceItems([build], [], ["spring-boot"])[0]!.children).toEqual([]);
});
it("shows the HTTP port of a running application instead of its state", () => {
@@ -267,62 +255,39 @@ describe("run configurations in Services", () => {
expect(sessionDetail(running)).toBe(":8080");
expect(sessionDetail(session("s1", app, "running", 1))).toBe("Running");
expect(sessionDetail(session("s1", app, "finished", 1, { httpPort: 8080, stopped: true }))).toBe("Stopped");
expect(runServiceItems([app], [running], DEFAULT_TYPES)[0]!.children![0]!.detail).toBe(":8080");
expect(runServiceItems([app], [running], ["spring-boot"])[0]!.children![0]!.detail).toBe(":8080");
});
});
describe("types added to Services", () => {
beforeEach(() => localStorage.clear());
it("defaults to Spring Boot and persists the user's list per project", () => {
expect(readTypes("/p")).toEqual(["spring-boot"]);
it("starts empty and persists the user's list per project", () => {
expect(readTypes("/p")).toEqual([]);
localStorage.setItem("openidea.services.runTypes:/p", JSON.stringify(["npm"]));
expect(readTypes("/p")).toEqual(["npm"]);
localStorage.setItem("openidea.services.runTypes:/p", "[]");
expect(readTypes("/p")).toEqual([]);
expect(readTypes("/q")).toEqual(["spring-boot"]);
expect(readTypes("/q")).toEqual([]);
});
});
describe("configurations that ran", () => {
describe("sessions of types not added", () => {
const dev = config("dev", "npm");
const scratch = config("context:file", "python");
beforeEach(() => localStorage.clear());
it("persists the ran configuration ids per project", () => {
expect(readRan("/p")).toEqual([]);
localStorage.setItem("openidea.services.ran:/p", JSON.stringify(["dev"]));
expect(readRan("/p")).toEqual(["dev"]);
expect(readRan("/q")).toEqual([]);
});
it("lists previously run configurations without a session", () => {
const items = runServiceItems([dev, scratch], [], [], ["dev", "context:file"]);
expect(items.map((i) => [i.key, i.label])).toEqual([
["run:type:npm", "npm"],
["run:type:python", "Python"],
]);
expect(items[0]!.children!.map((c) => [c.label, c.dim])).toEqual([["dev", true]]);
expect(items[1]!.children!.map((c) => c.key)).toEqual(["run:config:context:file"]);
});
it("ignores ran ids whose configuration is gone and merges sessions", () => {
const gone = runServiceItems([dev], [], [], ["missing"]);
expect(gone).toEqual([]);
const running = session("s1", dev, "running", 1);
const items = runServiceItems([dev], [running], [], ["dev"]);
expect(items).toHaveLength(1);
expect(items[0]!.children!.map((c) => [c.label, c.detail])).toEqual([["dev", "Running"]]);
it("keeps the type out of Services", () => {
expect(runServiceItems([dev], [session("s1", dev, "running", 1)], [])).toEqual([]);
});
it("drops a deleted configuration once its run has ended (#1497)", () => {
const removed = (id: string) => id === "dev";
const ended = runServiceItems([], [session("s1", dev, "finished", 1)], [], ["dev"], {}, [], removed);
expect(ended).toEqual([]);
const live = runServiceItems([], [session("s1", dev, "running", 1)], [], ["dev"], {}, [], removed);
const ended = runServiceItems([], [session("s1", dev, "finished", 1)], ["npm"], {}, [], removed);
expect(ended[0]!.children).toEqual([]);
const live = runServiceItems([], [session("s1", dev, "running", 1)], ["npm"], {}, [], removed);
expect(live[0]!.children!.map((c) => [c.label, c.detail])).toEqual([["dev", "Running"]]);
// Never a saved configuration (a build task, an external tool): its finished run stays.
const adHoc = runServiceItems([], [session("s2", scratch, "finished", 1)], [], [], {}, [], removed);
const adHoc = runServiceItems([], [session("s2", scratch, "finished", 1)], ["python"], {}, [], removed);
expect(adHoc[0]!.children!.map((c) => c.key)).toEqual(["run:config:context:file"]);
});
});
@@ -345,25 +310,24 @@ describe("hidden configurations", () => {
const a = config("a", "spring-boot");
const b = config("b", "spring-boot");
it("hides a configuration unless it runs", () => {
it("hides a configuration even while it runs", () => {
const hidden = { "spring-boot": ["a"] };
const stopped = runServiceItems([a, b], [], DEFAULT_TYPES, [], {}, [], () => false, hidden);
const stopped = runServiceItems([a, b], [], ["spring-boot"], {}, [], () => false, hidden);
expect(stopped[0]!.children!.map((c) => c.key)).toEqual(["run:config:b"]);
const running = runServiceItems(
[a, b],
[session("s1", a, "running", 1)],
DEFAULT_TYPES,
[],
["spring-boot"],
{},
[],
() => false,
hidden,
);
expect(running[0]!.children!.map((c) => c.key)).toEqual(["run:config:a", "run:config:b"]);
expect(running[0]!.children!.map((c) => c.key)).toEqual(["run:config:b"]);
});
it("keeps an empty default group whose configurations are all hidden", () => {
const items = runServiceItems([a], [], DEFAULT_TYPES, [], {}, [], () => false, { "spring-boot": ["a"] });
it("keeps an added type's group whose configurations are all hidden", () => {
const items = runServiceItems([a], [], ["spring-boot"], {}, [], () => false, { "spring-boot": ["a"] });
expect(items).toHaveLength(1);
expect(items[0]!.children).toEqual([]);
});
@@ -384,8 +348,7 @@ describe("hidden configurations", () => {
const items = runServiceItems(
[compose, dockerfile, image],
[session("s1", compose, "running", 1), session("s2", dockerfile, "finished", 2)],
[...DEFAULT_TYPES, "docker-compose", "docker-dockerfile", "docker-image"],
[compose.id, dockerfile.id, image.id],
["docker-compose", "docker-dockerfile", "docker-image"],
);
expect(items).toEqual([]);
});
@@ -584,6 +547,7 @@ describe("group batch actions", () => {
it("uses the saved display order and leaves other types alone", async () => {
useProject.setState({ project: { root: "/group-order" } as never });
localStorage.setItem("openidea.services.runTypes:/group-order", JSON.stringify(["spring-boot"]));
localStorage.setItem("openidea.services.runOrder:/group-order", JSON.stringify({ "spring-boot": ["c", "a", "b"] }));
const configs = [
config("a", "spring-boot"),
@@ -671,7 +635,6 @@ describe("removing a workspace member from Services", () => {
sessions: [session("s1", main, "finished", 1), session("s2", vue, "running", 2, { runId: 7 })],
});
localStorage.setItem("openidea.services.runTypes:/w/main", JSON.stringify(["spring-boot", "npm"]));
localStorage.setItem("openidea.services.ran:/w/main", JSON.stringify(["app", "dev"]));
await cleanupRemovedProject("/w/vue");
@@ -680,7 +643,6 @@ describe("removing a workspace member from Services", () => {
expect(s.configs.map((c) => c.id)).toEqual(["app"]);
expect(s.temporary).toEqual([]);
expect(readTypes("/w/main")).toEqual(["spring-boot"]);
expect(readRan("/w/main")).toEqual(["app"]);
expect(ipc.runConfigs).toHaveBeenCalled();
});
@@ -758,6 +720,6 @@ describe("service selection", () => {
await pending;
await Promise.resolve();
expect(readHidden("/other-selection")).toEqual({});
expect(readTypes("/other-selection")).toEqual(DEFAULT_TYPES);
expect(readTypes("/other-selection")).toEqual([]);
});
});
+22 -106
Переглянути файл
@@ -1,10 +1,10 @@
/**
* Run configurations in the Services tool window (IDEA's Run Dashboard): Spring
* Boot by default, the configuration types added there ("Add Service › Run
* Configuration Type"), the types of this window's run sessions and the
* configurations that ran before (kept per project across restarts), one group
* each, with run / debug / stop / rerun per configuration. A configuration that
* ran shows its console in the detail pane, a running web application its HTTP port.
* Run configurations in the Services tool window (IDEA's Run Dashboard): the
* configuration types added there ("Add Service › Run Configuration Type"), one
* group each, with run / debug / stop / rerun per configuration. Nothing else is
* listed, and what is removed leaves at once; a run it started keeps its console
* in the Run tool window. A configuration that ran shows its console in the
* detail pane, a running web application its HTTP port.
*/
import { useEffect, useMemo } from "react";
import { create } from "zustand";
@@ -33,7 +33,6 @@ import { showApplicationUpdate } from "./applicationUpdate";
import { isUpdatable } from "./updatePolicies";
import {
configRemoved,
debugSession,
loadConfigs,
persistTemporary,
rerunConfig,
@@ -68,9 +67,6 @@ export const RUN_PROVIDER = "runConfigurations";
const TYPE_PREFIX = "run:type:";
const CONFIG_PREFIX = "run:config:";
const STORAGE_KEY = "openidea.services.runTypes:";
const RAN_KEY = "openidea.services.ran:";
/** Types shown in Services until the user changes the list. */
export const DEFAULT_TYPES: readonly string[] = ["spring-boot"];
/** Docker run kinds whose containers/deployments are already shown under the Docker provider in Services. */
const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "docker-dockerfile", "docker-image"]);
@@ -79,15 +75,15 @@ const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "d
const useAddedTypes = create<{ root: string | null; types: string[] }>(() => ({ root: null, types: [] }));
/** The project's types; Spring Boot until the user changes the list. */
/** The project's types; empty until the user adds one with "Add Service". */
export function readTypes(root: string): string[] {
try {
const raw = localStorage.getItem(STORAGE_KEY + root);
if (raw === null) return [...DEFAULT_TYPES];
if (raw === null) return [];
const v: unknown = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
return [...DEFAULT_TYPES];
return [];
}
}
@@ -118,41 +114,6 @@ export function removeType(kind: string) {
setAddedTypes(currentTypes().filter((t) => t !== kind));
}
// ---------------------------------------------------------------------------
// Configurations that ran, per project (shown again after a restart)
const useRanConfigs = create<{ root: string | null; ids: string[] }>(() => ({ root: null, ids: [] }));
/** The project's previously run configuration ids, most recent last. */
export function readRan(root: string): string[] {
try {
const raw = localStorage.getItem(RAN_KEY + root);
if (raw === null) return [];
const v: unknown = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
return [];
}
}
function ranIds(root: string | null): string[] {
const s = useRanConfigs.getState();
return s.root === root ? s.ids : root ? readRan(root) : [];
}
/** Records a run, so its configuration is back in Services after a restart. */
export function recordRun(configId: string) {
const root = useProject.getState().project?.root ?? null;
const ids = [...ranIds(root).filter((id) => id !== configId), configId];
useRanConfigs.setState({ root, ids });
if (!root) return;
try {
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
// ---------------------------------------------------------------------------
// Project removal: a workspace member's data leaves with it
@@ -165,7 +126,7 @@ function insideRoot(path: string, root: string): boolean {
* Drops a removed workspace member's data from Services: stops and forgets its
* sessions (a finished one still groups the tree), removes its temporary
* configurations, reloads (the backend no longer lists the member) and clears
* the added types and remembered runs that would otherwise render empty groups.
* the added types that would otherwise render empty groups.
*/
export async function cleanupRemovedProject(removedRoot: string): Promise<void> {
const { configs, sessions, temporary } = useRun.getState();
@@ -196,20 +157,6 @@ export async function cleanupRemovedProject(removedRoot: string): Promise<void>
const { configs: fresh, sessions: liveSessions } = useRun.getState();
const liveKinds = new Set([...fresh.map((c) => c.kind), ...liveSessions.map((s) => s.config.kind)]);
for (const kind of kinds) if (!liveKinds.has(kind)) removeType(kind);
const root = useProject.getState().project?.root ?? null;
if (root) {
const freshIds = new Set(fresh.map((c) => c.id));
const ids = ranIds(root).filter((id) => freshIds.has(id));
if (ids.length !== ranIds(root).length) {
useRanConfigs.setState({ root, ids });
try {
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
}
}
// Configurations hidden from Services, per project (removed one by one; "Add Service" restores)
@@ -253,7 +200,7 @@ function saveHidden(hidden: Record<string, string[]>) {
}
}
/** Removes one configuration from Services; it reappears while it runs (its console stays reachable). */
/** Removes one configuration from Services at once, even while it runs (its console is in the Run window). */
function hideConfig(kind: string, id: string) {
const hidden = currentHidden();
if ((hidden[kind] ?? []).includes(id)) return;
@@ -311,15 +258,15 @@ function executionDetail(s: ServiceSession | undefined): string | undefined {
}
/**
* Groups by configuration type: added types list all their configurations, other
* types only those that ran. A default type (Spring Boot) without configurations is hidden.
* A configuration deleted since it ran (`removed`) stays only while its run is live.
* Groups by configuration type: only the types added in this window list their
* configurations, and a configuration removed from the window stays out even
* while it runs (its console is in the Run tool window). A configuration deleted
* since it ran (`removed`) stays only while its run is live.
*/
export function runServiceItems(
configs: readonly RunConfig[],
sessions: readonly RunSession[],
added: readonly string[],
ran: readonly string[] = [],
order: ServiceOrder = {},
debug: readonly DebugServiceSession[] = [],
removed: (id: string) => boolean = () => false,
@@ -329,28 +276,12 @@ export function runServiceItems(
const latest = currentServiceSessions(executions);
const kinds = added.filter((kind) => !DOCKER_PROVIDER_KINDS.has(kind));
const shown = (s: ServiceSession) => liveServiceSession(s) || !removed(s.config.id);
for (const s of executions)
if (shown(s) && !DOCKER_PROVIDER_KINDS.has(s.config.kind) && !kinds.includes(s.config.kind))
kinds.push(s.config.kind);
for (const id of ran) {
const kind = configs.find((c) => c.id === id)?.kind;
if (kind && !DOCKER_PROVIDER_KINDS.has(kind) && !kinds.includes(kind)) kinds.push(kind);
}
return kinds.flatMap((kind) => {
const entries: RunConfig[] = added.includes(kind)
? configs.filter((c) => c.kind === kind)
: ran.map((id) => configs.find((c) => c.id === id)).filter((c): c is RunConfig => !!c && c.kind === kind);
const entries: RunConfig[] = configs.filter((c) => c.kind === kind);
for (const s of latest.values())
if (s.config.kind === kind && shown(s) && !entries.some((c) => c.id === s.config.id)) entries.push(s.config);
// Hidden configurations reappear only while they run (their console stays reachable).
const hiddenIds = new Set(hidden[kind] ?? []);
const visible = entries.filter((c) => {
if (!hiddenIds.has(c.id)) return true;
const s = latest.get(c.id);
return !!s && liveServiceSession(s);
});
// Keep an empty group only when its existing configurations can be restored.
if (!visible.length && DEFAULT_TYPES.includes(kind) && !configs.some((c) => c.kind === kind)) return [];
const visible = entries.filter((c) => !hiddenIds.has(c.id));
const children = orderServices(visible, order[kind]).map((c): ServiceTreeItem => {
const s = latest.get(c.id);
return {
@@ -388,28 +319,24 @@ function useRoots(): ServiceTreeItem[] {
const debug = useDebugRunSessions((s) => s.serviceSessions);
const types = useAddedTypes((s) => s.types);
const typesRoot = useAddedTypes((s) => s.root);
const ran = useRanConfigs((s) => s.ids);
const ranRoot = useRanConfigs((s) => s.root);
const hidden = useHiddenConfigs((s) => s.hidden);
const hiddenLocation = useHiddenConfigs((s) => s.location);
useEffect(() => {
if (typesRoot !== root) useAddedTypes.setState({ root, types: root ? readTypes(root) : [] });
if (ranRoot !== root) useRanConfigs.setState({ root, ids: root ? readRan(root) : [] });
if (hiddenLocation !== location) useHiddenConfigs.setState({ location, hidden: readHidden(location) });
}, [root, typesRoot, ranRoot, hiddenLocation, location]);
}, [root, typesRoot, hiddenLocation, location]);
return useMemo(
() =>
runServiceItems(
configs,
sessions,
typesRoot === root ? types : [],
ranRoot === root ? ran : [],
order,
debug,
configRemoved,
hiddenLocation === location ? hidden : {},
),
[configs, sessions, types, typesRoot, ran, ranRoot, root, order, debug, hidden, hiddenLocation, location],
[configs, sessions, types, typesRoot, root, order, debug, hidden, hiddenLocation, location],
);
}
@@ -477,7 +404,6 @@ function groupConfigs(kind: string): RunConfig[] {
configs,
sessions,
currentTypes(),
ranIds(root),
location ? currentServiceOrder(location) : {},
debug,
configRemoved,
@@ -744,20 +670,11 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
</div>
</EmptyState>
);
// The configuration ran: its console, as in the Run tool window.
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
// come from this window's toolbar (the selection), so the console strip leaves them out.
if (r.session?.run) {
const execution = r.session;
const d = serviceDebugger(execution);
const rerun = d ? (d.rerunInPlace ?? d.rerun) : undefined;
return (
<SessionPanel
key={execution.run!.id}
session={execution.run!}
onRerun={d ? rerun : () => run(r)}
onDebug={d ? rerun : () => debugSession(execution.run!.id, { show: false })}
onStop={d ? () => void stopServiceSessions([execution]) : undefined}
/>
);
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
}
const d = r.session?.debug[0];
if (d && Console)
@@ -908,7 +825,6 @@ export const runServiceProvider: ServiceProviderContribution = {
configs,
sessions,
currentTypes(),
ranIds(useProject.getState().project?.root ?? null),
order,
useDebugRunSessions.getState().serviceSessions,
configRemoved,
-3
Переглянути файл
@@ -59,7 +59,6 @@ import { remoteLabel, startWithRemedies } from "./remote";
import { TerminalOutput } from "./terminalOutput";
import { typeFor } from "./types";
import { loadRunTemplates } from "./runTemplates";
import { recordRun } from "./services";
import { startedPort } from "@/platform/serverPort";
import { tomcatBrowserUrl } from "./tomcat";
import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun";
@@ -832,8 +831,6 @@ export async function startRun(
useRun.setState((s) => ({ sessions: [...s.sessions, created], activeSession: created.id }));
}
bump(session.id);
// The Services tool window lists the configuration again after a restart.
recordRun(config.id);
const sessionId = session.id;
const rt = runtimes.get(sessionId)!;
const generation = rt.generation;
+18 -11
Переглянути файл
@@ -56,6 +56,8 @@ let dispose: () => void;
let disposeActions: () => void;
beforeEach(() => {
localStorage.clear();
// The types are added by hand, as in the real window (nothing shows by default).
localStorage.setItem("openidea.services.runTypes:/services-debug", JSON.stringify(["spring-boot", "shell"]));
useProject.setState({
project: { root: "/services-debug", name: "app", isGit: false, settings: validateSettings({}) } as never,
});
@@ -144,7 +146,7 @@ it("reruns a debug service in place from the Services panel", () => {
expect(d.rerun).not.toHaveBeenCalled();
});
it("starts a debug session in place from a run service's detail toolbar", async () => {
it("starts a debug session in place from the Services toolbar", async () => {
const start = vi.fn();
const disposeAction = registerActions([
{ id: "run.debugConfig", title: "Debug Configuration", run: ({ arg }) => start(arg) },
@@ -153,18 +155,18 @@ it("starts a debug session in place from a run service's detail toolbar", async
const s = await startRun(c);
expect(s).not.toBeNull();
useRun.setState({ configs: [c], sessions: [{ ...s!, config: c, status: "running" as const }] });
useServicesTree.setState({ expanded: new Set(["run:type:shell"]) });
try {
render(<ServicesTreeView />);
select();
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
fireEvent.click(actions.getByRole("button", { name: "Debug" }));
fireEvent.click(toolbar().getByRole("button", { name: "Debug" }));
await vi.waitFor(() => expect(start).toHaveBeenCalledWith({ config: c, show: false }));
} finally {
disposeAction();
}
});
it("reruns a plain run service in place from its detail toolbar", async () => {
it("reruns a plain run service in place from the Services toolbar", async () => {
const c = { ...config, kind: "shell", command: "echo", debugAdapter: null };
const s = await startRun(c);
expect(s).not.toBeNull();
@@ -175,12 +177,12 @@ it("reruns a plain run service in place from its detail toolbar", async () => {
const previousRuntime = runtime(s!.id);
render(<ServicesTreeView />);
select();
fireEvent.click(within(screen.getByRole("toolbar", { name: "Run actions" })).getByRole("button", { name: "Rerun" }));
fireEvent.click(toolbar().getByRole("button", { name: /^(Run|Rerun)$/ }));
await vi.waitFor(() => expect(runtime(s!.id)).not.toBe(previousRuntime));
expect(show).not.toHaveBeenCalled();
});
it("reruns an attached debugger in place from a run service's detail toolbar", async () => {
it("reruns an attached debugger in place from the Services toolbar", async () => {
const c = { ...config, kind: "shell", command: "echo", debugAdapter: null };
const s = await startRun(c);
expect(s).not.toBeNull();
@@ -191,8 +193,7 @@ it("reruns an attached debugger in place from a run service's detail toolbar", a
useDebugRunSessions.setState({ serviceSessions: [d] });
render(<ServicesTreeView />);
select();
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
fireEvent.click(actions.getByRole("button", { name: "Debug" }));
fireEvent.click(toolbar().getByRole("button", { name: "Debug" }));
expect(d.rerunInPlace).toHaveBeenCalledOnce();
expect(d.rerun).not.toHaveBeenCalled();
});
@@ -215,7 +216,7 @@ it("keeps the other parallel instance alive and then displays it", async () => {
expect(screen.getByRole("log")).toHaveTextContent("first instance");
});
it("shows the owning Run output for attached debugging and overrides both sets of controls", async () => {
it("shows the owning Run output for attached debugging and routes the controls through the Services toolbar", async () => {
const stopRun = vi.spyOn(commands, "runStop").mockImplementation(async (id) => {
queueMicrotask(() => onRunExited(id, 130));
return { status: "ok", data: null };
@@ -231,8 +232,14 @@ it("shows the owning Run output for attached debugging and overrides both sets o
render(<ServicesTreeView />);
select();
expect(screen.getByRole("log")).toHaveTextContent("Maven application log");
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
fireEvent.click(actions.getByRole("button", { name: "Rerun" }));
// The console strip keeps only console controls: the window toolbar owns Run / Debug / Stop.
const strip = within(screen.getByRole("toolbar", { name: "Run actions" }));
expect(strip.queryByRole("button", { name: "Rerun" })).toBeNull();
expect(strip.queryByRole("button", { name: "Debug" })).toBeNull();
expect(strip.queryByRole("button", { name: "Stop" })).toBeNull();
expect(strip.getByRole("button", { name: "Clear All" })).toBeTruthy();
const actions = toolbar();
fireEvent.click(actions.getByRole("button", { name: /^(Run|Rerun)$/ }));
expect(d.rerun).toHaveBeenCalledOnce();
await act(async () => fireEvent.click(actions.getByRole("button", { name: "Stop" })));
expect(stopRun).toHaveBeenCalledExactlyOnceWith(7);
+8 -1
Переглянути файл
@@ -272,7 +272,14 @@ export function ServicesTreeView() {
</div>
</SplitPanel>
<SplitHandle />
<SplitPanel id="services-detail" minSize="200px">
<SplitPanel
id="services-detail"
minSize="200px"
// The panel library puts `overflow: auto` inline; the detail content
// (a console, a log) owns its scrolling, so the pane must not add a second
// bar. A column flex box lets that content fill the pane.
style={{ overflow: "hidden", height: "100%", display: "flex", flexDirection: "column" }}
>
{selected && Detail && shown ? (
<Detail key={selected.item.key} item={selected.item} />
) : (
+2
Переглянути файл
@@ -140,6 +140,8 @@ export function dockerItems(
icon: snap?.availability.kind === "ready" ? "docker-connected" : "file-docker",
detail: connectionDetail(state),
dim: snap?.availability.kind !== "ready",
// A connection the user just added opens once, so its groups are in sight.
expanded: true,
children: children(root)?.map(convert) ?? [],
};
});
+1 -1
Переглянути файл
@@ -21,7 +21,7 @@ export const useServicesTree = create<TreeState>(() => ({
roots: {},
selectedKey: null,
selectedKeys: new Set(),
expanded: new Set(["docker:default", "docker:default:group:containers"]),
expanded: new Set(),
}));
/** Keys of nodes asking to start expanded that were shown once (collapsing them then sticks). */
+47 -2
Переглянути файл
@@ -116,12 +116,55 @@ describe("scheme actions", () => {
it("shows a malformed-file error without staging any changes", async () => {
mocks.read.mockResolvedValueOnce({ status: "ok", data: '<scheme name="bad">' });
await run("import");
await waitFor(() => expect(mocks.error).toHaveBeenCalledWith("Color Scheme", "Invalid .icls color scheme"));
await waitFor(() =>
expect(mocks.error).toHaveBeenCalledWith("Import Scheme", expect.stringContaining("Invalid .icls color scheme")),
);
expect(useSettingsDialog.getState().staged).toEqual({});
});
it("offers .xml scheme files in the chooser and imports one (#2714)", async () => {
mocks.open.mockResolvedValueOnce("/downloads/Material Darker.xml");
mocks.read.mockResolvedValueOnce({
status: "ok",
data: readFileSync("src/platform/__fixtures__/colorSchemes/material-darker.xml", "utf8"),
});
await run("import");
expect(mocks.open).toHaveBeenCalledWith({
multiple: false,
filters: [{ name: "IntelliJ Color Scheme", extensions: ["icls", "xml"] }],
});
expect(value("colorScheme")).toMatch(/^custom-/);
expect(screen.getByRole("status")).toHaveTextContent("Applied 12 values; skipped 3");
const schemes = value("customSchemes") as Record<string, { name: string }>;
expect(Object.values(schemes).some((s) => s.name === "Material Darker")).toBe(true);
});
it("names a scheme without a name attribute after its file (#2714)", async () => {
mocks.open.mockResolvedValueOnce("/downloads/one-dark-wrapped.xml");
mocks.read.mockResolvedValueOnce({
status: "ok",
data: readFileSync("src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml", "utf8"),
});
await run("import");
const schemes = value("customSchemes") as Record<string, { name: string }>;
expect(Object.values(schemes).some((s) => s.name === "one-dark-wrapped")).toBe(true);
});
});
describe("doc comment scheme attributes", () => {
describe("python scheme attributes", () => {
it("groups Python attributes as PyCharm does", () => {
schemePage("editor.colorScheme.python");
const tree = screen.getByRole("tree", { name: "Color scheme attributes" });
// The tree virtualizes; a collapsed group renders before its siblings, so a group near
// the top is enough to prove grouping, and expanding it shows its leaves.
expect(within(tree).getByRole("treeitem", { name: "Functions" })).toBeInTheDocument();
for (const flat of ["Byte string", "F-string", "Method call"])
expect(within(tree).queryByRole("treeitem", { name: flat })).toBeNull();
const functions = within(tree).getByRole("treeitem", { name: "Functions" });
act(() => fireEvent.mouseDown(within(functions).getByText("Functions").previousElementSibling!, { button: 0 }));
expect(within(tree).getByRole("treeitem", { name: "Method call" })).toBeInTheDocument();
});
it("selects Python docstring tags and keywords from their preview", () => {
schemePage("editor.colorScheme.python");
const preview = screen.getByLabelText("Color scheme preview");
@@ -134,7 +177,9 @@ describe("doc comment scheme attributes", () => {
act(() => fireEvent.click(keyword));
expect(screen.getByRole("treeitem", { name: "Keyword", selected: true })).toBeInTheDocument();
});
});
describe("doc comment scheme attributes", () => {
it.each([
["en", "Doc comment", "Tag", "Tag value", "Markup"],
["zh", "文档注释", "标签", "标签值", "标记"],
+6 -3
Переглянути файл
@@ -104,7 +104,7 @@ export interface ValidSettings extends WorkflowSettings {
/** Tools › Agents › Chat: the meters in an agent task's header. */
agents: Required<AgentSettings>;
/** Agents › IDE MCP Server (global). */
mcpServer: { enabled: boolean };
mcpServer: { enabled: boolean; runWithoutConfirmation: boolean };
}
/** One `languageServers.<name>` entry; every field optional, like in settings.toml. */
@@ -193,7 +193,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
defaults: {},
mcpServers: {},
},
mcpServer: { enabled: false },
mcpServer: { enabled: false, runWithoutConfirmation: false },
...DEFAULT_WORKFLOW,
};
@@ -359,7 +359,10 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
defaults: agentDefaults(agents.defaults),
mcpServers: agentMcpServers(agents.mcpServers),
},
mcpServer: { enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled) },
mcpServer: {
enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled),
runWithoutConfirmation: bool(obj(root.mcpServer).runWithoutConfirmation, d.mcpServer.runWithoutConfirmation),
},
...validateWorkflow(root),
};
}
+13 -6
Переглянути файл
@@ -28,7 +28,7 @@ import styles from "./Editor.module.css";
import { executeAction, registerActions } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { ask, confirm, showError } from "@/workbench/messages";
import { parseIcls, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
import { tx, useTx } from "@/platform/i18n";
import { selectPage } from "../../model/staging";
@@ -1158,10 +1158,17 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
file ??
(await open({
multiple: false,
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }],
// IDEA schemes ship as .icls, but the ones people download are frequently .xml.
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls", "xml"] }],
}));
if (!path) return;
const parsed = parseIcls(await call(commands.fsReadText(path)));
// A scheme element without a name is named after its file, as IntelliJ does.
const fallbackName =
path
.split(/[\\/]/)
.at(-1)
?.replace(/\.[^.]+$/, "") || "Imported scheme";
const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName);
let overwrite = false;
if (schemes.some((s) => s.name === parsed.scheme.name)) {
const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name);
@@ -1232,9 +1239,9 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
await handlers.current[name]!(typeof arg === "string" ? arg : undefined);
} catch (error) {
await showError(
tx("Color Scheme"),
error instanceof Error && error.message === "Invalid .icls color scheme"
? tx("Invalid .icls color scheme")
tx("Import Scheme"),
error instanceof SchemeParseError
? `${tx("Invalid .icls color scheme")}: ${error.message}`
: String(error),
);
} finally {
+32 -2
Переглянути файл
@@ -835,6 +835,11 @@ const INLAY: Item[] = [
},
];
const CODE_VISION_POSITIONS = [
{ value: "top", label: "Top" },
{ value: "right", label: "Right" },
];
const INLAY_HINTS = editorPage({
id: "editor.inlayHints",
title: "Inlay Hints",
@@ -845,8 +850,33 @@ const INLAY_HINTS = editorPage({
{
title: "Code Vision",
items: [
{ t: "check", key: `${P}.inlay.codeVisionUsages`, label: "Usages" },
{ t: "check", key: `${P}.inlay.codeVisionAuthor`, label: "Code author" },
{
t: "check",
key: `${P}.inlay.codeVisionUsages`,
label: "Usages",
children: [
{
t: "select",
key: `${P}.inlay.codeVisionUsagesPosition`,
label: "Position",
options: CODE_VISION_POSITIONS,
},
{ t: "check", key: `${P}.inlay.codeVisionNoUsages`, label: "Show “no usages”" },
],
},
{
t: "check",
key: `${P}.inlay.codeVisionAuthor`,
label: "Code author",
children: [
{
t: "select",
key: `${P}.inlay.codeVisionAuthorPosition`,
label: "Position",
options: CODE_VISION_POSITIONS,
},
],
},
],
},
{ title: "Languages", items: [{ t: "custom", label: "Show inlay hints for:", component: InlayLanguages }] },
+6
Переглянути файл
@@ -128,6 +128,12 @@ export const MCP_SERVER_PAGE: PageSpec = {
label: "Enable MCP server",
hint: "Agents can read, edit, and run projects open in OpenIDEA through its built-in tools. Run tools ask for confirmation. The server listens on 127.0.0.1 only and requires a token.",
},
{
kind: "toggle",
key: "mcpServer.runWithoutConfirmation",
label: "Run tools without confirmation (brave mode)",
hint: "Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.",
},
{
kind: "custom",
label: "Endpoint",
+7
Переглянути файл
@@ -0,0 +1,7 @@
<scheme name="Bom Light" version="142" parent_scheme="Default">
<colors><option name="CARET_COLOR" value="ff00ff" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="1122ff" /><option name="FONT_TYPE" value="1" /></value></option>
<option name="TEXT"><value><option name="FOREGROUND" value="334455" /><option name="BACKGROUND" value="f0f0f0" /></value></option>
</attributes>
</scheme>
+9
Переглянути файл
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="windows-1252"?>
<!-- Saved by a Windows editor: the declaration describes the file's bytes, while a
caller hands parseIcls already decoded text. The name must survive unchanged. -->
<scheme name="Café Solar" version="142" parent_scheme="Default">
<colors><option name="CARET_COLOR" value="ffcc00" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="cc7832" /></value></option>
</attributes>
</scheme>
+89
Переглянути файл
@@ -0,0 +1,89 @@
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2015-2021 Elior "Mallowigi" Boukhobza
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
~
~
-->
<scheme name="Material Darker" version="142" parent_scheme="Darcula">
<option name="FONT_SCALE" value="1.0" />
<metaInfo>
<property name="created">2017-04-10T18:10:53</property>
<property name="ide">idea</property>
<property name="ideVersion">2020.1.0.0</property>
<property name="modified">2020-04-18T11:14:57</property>
<property name="originalScheme">Material Darker</property>
</metaInfo>
<option name="LINE_SPACING" value="1.4" />
<option name="EDITOR_FONT_SIZE" value="12" />
<font>
<option name="EDITOR_FONT_NAME" value="Menlo" />
<option name="EDITOR_FONT_SIZE" value="12" />
</font>
<font>
<option name="EDITOR_FONT_NAME" value="Fira Code" />
<option name="EDITOR_FONT_SIZE" value="12" />
</font>
<console-font>
<option name="EDITOR_FONT_NAME" value="Menlo" />
<option name="EDITOR_FONT_SIZE" value="12" />
</console-font>
<console-font>
<option name="EDITOR_FONT_NAME" value="Fira Code" />
<option name="EDITOR_FONT_SIZE" value="12" />
</console-font>
<colors>
<option name="CARET_COLOR" value="ffcc00" />
<option name="CARET_ROW_COLOR" value="181818" />
<option name="CONSOLE_BACKGROUND_KEY" value="212121" />
<option name="DELETED_LINES_COLOR" value="f07178" />
<option name="GUTTER_BACKGROUND" value="212121" />
<option name="LINE_NUMBERS_COLOR" value="424242" />
<option name="SELECTION_BACKGROUND" value="353535" />
</colors>
<attributes>
<option name="DEFAULT_KEYWORD">
<value>
<option name="FOREGROUND" value="c792ea" />
<option name="FONT_TYPE" value="2" />
</value>
</option>
<option name="DEFAULT_STRING">
<value>
<option name="FOREGROUND" value="c3e88d" />
</value>
</option>
<option name="DEFAULT_LINE_COMMENT">
<value>
<option name="FOREGROUND" value="616161" />
<option name="FONT_TYPE" value="2" />
</value>
</option>
<option name="TEXT">
<value>
<option name="FOREGROUND" value="eeffff" />
<option name="BACKGROUND" value="212121" />
<option name="EFFECT_TYPE" value="5" />
</value>
</option>
</attributes>
</scheme>
+11
Переглянути файл
@@ -0,0 +1,11 @@
<application>
<component name="EditorColorsSchemeImpl">
<scheme version="142" parent_scheme="Darcula">
<colors><option name="SELECTION_BACKGROUND" value="3a3d41" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="c678dd" /><option name="FONT_TYPE" value="1" /></value></option>
<option name="TEXT"><value><option name="FOREGROUND" value="abb2bf" /><option name="BACKGROUND" value="282c34" /></value></option>
</attributes>
</scheme>
</component>
</application>
+15
Переглянути файл
@@ -58,6 +58,21 @@ describe("color schemes", () => {
expect(css).toContain("--syn-constant: #224466 !important");
});
it("groups Python attributes as PyCharm's color settings page does", () => {
const python = (name: string) => ATTRIBUTES.find((a) => a.id === `py${name}`)!;
expect(python("FString").name).toBe("String › f-string › Expression braces");
expect(python("Bytes").name).toBe("String › Binary (bytes)");
expect(python("Docstring").name).toBe("Docstring › Text");
expect(python("MethodCall").name).toBe("Functions › Method call");
expect(python("NestedFunction").name).toBe("Functions › Nested function definition");
expect(python("Self").name).toBe("Parameters › 'self' parameter");
expect(python("PredefinedDefinition").name).toBe("Special names › Definition");
expect(python("PredefinedUsage").name).toBe("Special names › Usage");
expect(python("Parentheses").name).toBe("Braces and Operators › Parentheses");
// Attribute ids (the override and .icls keys) keep their old, stable names.
for (const a of ATTRIBUTES.filter((a) => a.path[0] === "Python")) expect(a.id).toMatch(/^py[A-Z]/);
});
it("resolves scheme attribute state and editor defaults", () => {
expect(resolvedAttribute("light", "lineComment")).toMatchObject({
foreground: "#8c8c8c",
+25 -24
Переглянути файл
@@ -154,18 +154,32 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [
...[1, 2, 3, 4, 5].map((n) => syn(`semantic${n}`, `Semantic highlighting › Color ${n}`, [LD], `rainbow-${n}`)),
...[1, 2, 3].map((n) => syn(`bracket${n}`, `Rainbow brackets › Level ${n}`, [LD], `bracket-${n}`)),
syn("pyMethodCall", "Method call", ["Python"], "python-method-call"),
// Python's tree mirrors PyCharm's groups and their order (PySyntaxBundle.properties in python-syntax).
syn("pyBytes", "String › Binary (bytes)", ["Python"], "python-bytes"),
syn("pyFString", "String › f-string › Expression braces", ["Python"], "python-fstring"),
syn("pyFormat", "String › f-string › Format spec number", ["Python"], "python-format"),
syn("pyDocstring", "Docstring › Text", ["Python"], "docstring", { defaultItalic: true }),
syn("pyDocstringTag", "Docstring › Tag", ["Python"], "python-docstring-tag"),
syn("pyDocstringKeyword", "Docstring › Keyword", ["Python"], "python-docstring-keyword"),
syn("pyParentheses", "Braces and Operators › Parentheses", ["Python"], "python-parentheses"),
syn("pyBrackets", "Braces and Operators › Brackets", ["Python"], "python-brackets"),
syn("pyBraces", "Braces and Operators › Braces", ["Python"], "python-braces"),
syn("pyNestedFunction", "Functions › Nested function definition", ["Python"], "python-nested-function"),
syn("pyMethodCall", "Functions › Method call", ["Python"], "python-method-call"),
syn("pySelf", "Parameters › 'self' parameter", ["Python"], "self"),
syn("pyKeywordArg", "Keyword argument", ["Python"], "keyword-arg"),
syn("pyPredefinedDefinition", "Special names › Definition", ["Python"], "python-predefined-definition"),
syn("pyPredefinedUsage", "Special names › Usage", ["Python"], "python-predefined-usage"),
syn("pyBuiltin", "Built-in name", ["Python"], "python-builtin"),
syn("pyDecorator", "Decorator", ["Python"], "annotation"),
syn("pyAnnotation", "Type annotation", ["Python"], "python-annotation"),
syn("pyParentheses", "Parentheses", ["Python"], "python-parentheses"),
syn("pyBrackets", "Brackets", ["Python"], "python-brackets"),
syn("pyBraces", "Braces", ["Python"], "python-braces"),
syn("pyNestedFunction", "Nested function definition", ["Python"], "python-nested-function"),
syn("pyBytes", "Byte string", ["Python"], "python-bytes"),
syn("pyFString", "F-string", ["Python"], "python-fstring"),
syn("pyPredefinedDefinition", "Predefined function definition", ["Python"], "python-predefined-definition"),
syn("pyPredefinedUsage", "Predefined name usage", ["Python"], "python-predefined-usage"),
syn("pyFormat", "Format specifier", ["Python"], "python-format"),
syn("pySelf", "Self parameter", ["Python"], "self"),
syn("pyLocalVariable", "Local variables", ["Python"], "python-local-variable"),
syn("pyTypeParameter", "Type parameters", ["Python"], "python-type-parameter"),
syn("pyGlobalVariable", "Global variable", ["Python"], "python-global-variable"),
syn("pyInstanceAttribute", "Instance attribute", ["Python"], "python-instance-attribute"),
syn("pyClassAttribute", "Class attribute", ["Python"], "python-class-attribute"),
syn("pyConstant", "Constant", ["Python"], "python-constant"),
syn("pyProperty", "Property", ["Python"], "python-property"),
{
id: "pyStaticSymbol",
name: "Static symbol",
@@ -174,19 +188,6 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [
italicOnly: true,
defaultItalic: false,
},
syn("pyKeywordArg", "Keyword argument", ["Python"], "keyword-arg"),
syn("pyDocstring", "Docstring", ["Python"], "docstring", { defaultItalic: true }),
syn("pyDocstringTag", "Docstring › Tag", ["Python"], "python-docstring-tag"),
syn("pyDocstringKeyword", "Docstring › Keyword", ["Python"], "python-docstring-keyword"),
syn("pyBuiltin", "Built-in name", ["Python"], "python-builtin"),
syn("pyDecorator", "Decorator", ["Python"], "annotation"),
syn("pyLocalVariable", "Local variable", ["Python"], "python-local-variable"),
syn("pyGlobalVariable", "Global variable", ["Python"], "python-global-variable"),
syn("pyInstanceAttribute", "Instance attribute", ["Python"], "python-instance-attribute"),
syn("pyClassAttribute", "Class attribute", ["Python"], "python-class-attribute"),
syn("pyConstant", "Constant", ["Python"], "python-constant"),
syn("pyProperty", "Property", ["Python"], "python-property"),
syn("pyTypeParameter", "Type parameter", ["Python"], "python-type-parameter"),
syn("mdHeading", "Heading", ["Markdown"], "markup-heading", { defaultBold: true }),
syn("mdCode", "Code span", ["Markdown"], "markup-code"),
syn("mdLink", "Link", ["Markdown"], "link", { defaultEffect: "underline" }),
+5
Переглянути файл
@@ -179,6 +179,9 @@ export const EDITOR_EXTRA_DEFAULTS = {
disabledLanguages: [] as string[],
codeVisionUsages: true,
codeVisionAuthor: true,
codeVisionNoUsages: true,
codeVisionUsagesPosition: "top" as "top" | "right",
codeVisionAuthorPosition: "top" as "top" | "right",
},
inlineCompletion: { enabled: true, onlyOnPause: false, pauseMs: 500, disabledLanguages: [] as string[] },
gutterIconsDisabled: [] as string[],
@@ -260,6 +263,8 @@ export function validateEditorExtras(raw: unknown): EditorExtras {
const out = coerceLike(raw, EDITOR_EXTRA_DEFAULTS);
if (!["ask", "always", "never"].includes(out.autoImport.importsOnPaste)) out.autoImport.importsOnPaste = "ask";
if (!DOCSTRING_FORMATS.includes(out.docstringFormat)) out.docstringFormat = "rest";
for (const k of ["codeVisionUsagesPosition", "codeVisionAuthorPosition"] as const)
if (!["top", "right"].includes(out.inlay[k])) out.inlay[k] = "top";
out.fontWeight = fontWeightOf(out.fontWeight, EDITOR_EXTRA_DEFAULTS.fontWeight);
out.boldFontWeight = fontWeightOf(out.boldFontWeight, EDITOR_EXTRA_DEFAULTS.boldFontWeight);
return out;
+1
Переглянути файл
@@ -283,6 +283,7 @@ describe("catalogs", () => {
"Yarn",
"Cargo",
"CMake",
"f-string",
"Tailwind CSS",
]);
const translated = SUPPORTED_LOCALES.filter((locale) => locale !== "en").sort();
+61 -13
Переглянути файл
@@ -9,14 +9,15 @@ import {
SCHEMES,
schemeCss,
} from "./colorScheme";
import { deleteScheme, exportIcls, importScheme, parseIcls } from "./icls";
import { deleteScheme, exportIcls, importScheme, parseIcls, SchemeParseError } from "./icls";
import { validateSettings } from "@/features/settings/model/schema";
import { colorSchemeItems } from "@/workbench/quickSwitch";
import { useProject } from "./project";
import type { Settings } from "./ipc";
import { isClientSetting } from "./clientSettings";
const fixture = (name: string) => readFileSync(`src/platform/__fixtures__/colorSchemes/${name}.icls`, "utf8");
const fixture = (name: string, ext = "icls") =>
readFileSync(`src/platform/__fixtures__/colorSchemes/${name}.${ext}`, "utf8");
beforeAll(() => _setSchemeSource(readFileSync("src/styles/tokens.css", "utf8")));
describe(".icls schemes", () => {
@@ -177,18 +178,65 @@ describe(".icls schemes", () => {
expect([sign.applied, sign.skipped]).toEqual([1, 2]);
});
it.each(["", "<scheme", '<scheme name="A"><attributes></scheme>', "<nope>", '<html name="x"/>'])(
"rejects malformed or non-scheme XML without mutating schemes: %s",
(xml) => {
const customs = importScheme({}, parseIcls(fixture("forest")).scheme).customs;
const before = structuredClone(customs);
expect(() => parseIcls(xml)).toThrow(SchemeParseError);
expect(customs).toEqual(before);
},
);
it("names what is wrong with a rejected file", () => {
expect(() => parseIcls("<nope>")).toThrow(/not valid XML/);
try {
parseIcls('<html name="x"/>');
expect.unreachable();
} catch (error) {
expect(error).toBeInstanceOf(SchemeParseError);
expect((error as Error).message).toMatch(/<scheme> element/);
}
});
it("imports a real-world .xml scheme from Material Theme UI (#2714)", () => {
const { scheme, applied, skipped } = parseIcls(fixture("material-darker", "xml"));
expect(scheme.name).toBe("Material Darker");
expect(scheme.parent).toBe("dark");
expect(scheme.attributes.keyword).toEqual({ foreground: "#c792ea", bold: false, italic: true });
expect(scheme.attributes.string?.foreground).toBe("#c3e88d");
expect(scheme.attributes.lineComment).toEqual({ foreground: "#616161", bold: false, italic: true });
expect(scheme.attributes.text).toEqual({ foreground: "#eeffff", background: "#212121" });
expect(scheme.attributes.caret?.foreground).toBe("#ffcc00");
expect(scheme.attributes.gutter?.background).toBe("#212121");
expect(scheme.attributes.lineNumber?.foreground).toBe("#424242");
expect(scheme.attributes.selection?.background).toBe("#353535");
expect([applied, skipped]).toEqual([12, 3]);
});
it.each([
"",
"<scheme",
'<scheme name="A"><attributes></scheme>',
"<scheme/>",
'<html name="x"/>',
'<!DOCTYPE scheme [<!ENTITY a "red">]><scheme name="x"/>',
])("rejects malformed XML without mutating schemes: %s", (xml) => {
const customs = importScheme({}, parseIcls(fixture("forest")).scheme).customs;
const before = structuredClone(customs);
expect(() => parseIcls(xml)).toThrow("Invalid .icls color scheme");
expect(customs).toEqual(before);
["bom-utf8", "Bom Light"],
["declared-encoding", "Café Solar"],
] as const)("accepts the BOM and encoding-declaration variants of a scheme: %s", (name, schemeName) => {
const { scheme } = parseIcls(fixture(name));
expect(scheme.name).toBe(schemeName);
expect(scheme.attributes.keyword?.foreground).toBe(name === "bom-utf8" ? "#1122ff" : "#cc7832");
// Byte-order and encoding marks do not change what a scheme says.
expect(parseIcls(`\uFEFF${fixture(name)}`).scheme).toEqual(scheme);
});
it("unwraps a scheme element from its settings export and names a scheme after its file (#2714)", () => {
const { scheme } = parseIcls(fixture("one-dark-wrapped", "xml"));
expect(scheme.name).toBe("Imported scheme");
expect(scheme.attributes.keyword).toEqual({ foreground: "#c678dd", bold: true, italic: false });
expect(scheme.attributes.text).toEqual({ foreground: "#abb2bf", background: "#282c34" });
expect(parseIcls(fixture("one-dark-wrapped", "xml"), "One Dark").scheme.name).toBe("One Dark");
});
it("accepts a DOCTYPE prolog, which XML allows and old exporters emit (#2714)", () => {
const { scheme } = parseIcls('<!DOCTYPE scheme SYSTEM "scheme.dtd"><scheme name="D"><colors/></scheme>');
expect(scheme.name).toBe("D");
expect(() => parseIcls('<!DOCTYPE scheme [<!ENTITY a "red">]><scheme name="x"/>')).not.toThrow();
});
it.each([
+40 -11
Переглянути файл
@@ -274,16 +274,45 @@ function attributeEntries(section: Element): Element[] {
return entries.filter((e) => e.getAttribute("name") !== "DEFAULT_BLOCK_COMMENT");
}
export function parseIcls(xml: string): { scheme: CustomColorScheme; applied: number; skipped: number } {
const doc = new DOMParser().parseFromString(xml, "application/xml");
const root = doc.documentElement;
if (
doc.querySelector("parsererror") ||
doc.doctype ||
root.tagName !== "scheme" ||
!root.getAttribute("name")?.trim()
)
throw new Error("Invalid .icls color scheme");
/** A scheme file that is not an IntelliJ color scheme; `message` says what is wrong with it. */
export class SchemeParseError extends Error {
constructor(message: string) {
super(message);
this.name = "SchemeParseError";
}
}
/**
* The variants real IDEA scheme files come in: a BOM, an `encoding=` declaration
* (both describe the file's bytes, while this text has already been decoded), and
* a DOCTYPE prolog. None of them change the scheme, so drop the first two.
*/
const prepareIclsXml = (xml: string) =>
xml
.replace(/^\uFEFF+/, "")
.replace(/^\s*<\?xml\s[^>]*\?>(\r\n|\r|\n)?/i, "")
.replace(/^\s*(\r\n|\r|\n)?/, "");
const parserDetail = (doc: Document): string => {
const detail = (doc.querySelector("parsererror")?.textContent ?? "").replace(/\s+/g, " ").trim();
return detail.length ? detail.slice(0, 200) : "no scheme element found";
};
export function parseIcls(
xml: string,
fallbackName = "Imported scheme",
): { scheme: CustomColorScheme; applied: number; skipped: number } {
const doc = new DOMParser().parseFromString(prepareIclsXml(xml), "application/xml");
// Some distributors wrap the scheme element (an <application>/<component> export), or leave the name out.
const root =
doc.documentElement?.tagName === "scheme"
? doc.documentElement
: (doc.getElementsByTagName("scheme")[0] ?? undefined);
if (doc.querySelector("parsererror") || !root)
throw new SchemeParseError(
doc.querySelector("parsererror") ? `not valid XML (${parserDetail(doc)})` : "no IntelliJ <scheme> element found",
);
const name = root.getAttribute("name")?.trim() || fallbackName;
const attributes: Record<string, TextAttributesOverride> = {};
const entries = new Map(
children(root, "attributes").flatMap((section) =>
@@ -397,7 +426,7 @@ export function parseIcls(xml: string): { scheme: CustomColorScheme; applied: nu
: dark
? "dark"
: "light";
return { scheme: { name: root.getAttribute("name")!.trim(), parent, attributes }, applied, skipped };
return { scheme: { name, parent, attributes }, applied, skipped };
}
/** Name collisions include built-ins; imports never replace a built-in. */
+6
Переглянути файл
@@ -117,6 +117,9 @@
"Move the worktree at {path} to {to}?": "Move the worktree at {path} to {to}?",
"Cannot move a worktree containing the open project.": "Cannot move a worktree containing the open project.",
"Add Environment File": "Add Environment File",
"Add UTF-8 BOM": "Add UTF-8 BOM",
"Remove UTF-8 BOM": "Remove UTF-8 BOM",
"Cannot change the UTF-8 BOM": "Cannot change the UTF-8 BOM",
"Convert to cURL and Copy": "Convert to cURL and Copy",
"Add Environment to Public File": "Add Environment to Public File",
"Add Environment to Private File": "Add Environment to Private File",
@@ -591,6 +594,7 @@
"Invalid log stream configuration": "Invalid log stream configuration",
"Find in Logs": "Find in Logs",
"Waiting for output…": "Waiting for output…",
"Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.": "Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.",
"Soft-wrap": "Soft-wrap",
"Clear": "Clear",
"\n[Process finished]": "\n[Process finished]",
@@ -670,6 +674,8 @@
"Gradle Tasks": "Gradle Tasks",
"IDE MCP Server": "IDE MCP Server",
"Enable MCP server": "Enable MCP server",
"Run tools without confirmation (brave mode)": "Run tools without confirmation (brave mode)",
"Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.": "Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.",
"Status": "Status",
"Running on port {port}": "Running on port {port}",
"Failed to start: {error}": "Failed to start: {error}",
+5
Переглянути файл
@@ -1073,6 +1073,7 @@
"Install Plugin from Disk…": "Instalar complemento desde el disco…",
"Install a plugin folder with": "Instala una carpeta de complemento con",
"Install and Debug": "Instalar y depurar",
"Reinstall and Debug": "Reinstalar y depurar",
"Install gh…": "Instalar gh…",
"Installed": "Instalados",
"Installed packages": "Paquetes instalados",
@@ -1889,6 +1890,7 @@
"Running": "En ejecución",
"Running processes requires the desktop app.": "Ejecutar procesos requiere la aplicación de escritorio.",
"Runs Gradle with --offline": "Ejecuta Gradle con --offline",
"Runs Gradle with -x test": "Ejecuta Gradle con -x test",
"Runs Maven with -DskipTests": "Ejecuta Maven con -DskipTests",
"Runs Maven with -o": "Ejecuta Maven con -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Ejecuta Optimizar importaciones cuando el archivo no tiene errores, a menos que modifique la línea del cursor.",
@@ -2374,6 +2376,8 @@
"more": "más",
"Usages": "Usos",
"Code author": "Autor del código",
"Position": "Posición",
"Show “no usages”": "Mostrar «sin usos»",
"Usages Detected": "Usos detectados",
"Usages actions": "Acciones de usos",
"Usages of '{symbol}'": "Usos de '{symbol}'",
@@ -4041,6 +4045,7 @@
"{count} classes": "{count} clases",
"The JavaScript debugger (vscode-js-debug) is not installed": "El depurador de JavaScript (vscode-js-debug) no está instalado",
"Delve is not installed": "Delve no está instalado",
"Delve is too old for Go {go}": "Delve es demasiado antiguo para Go {go}",
"CodeLLDB is not installed": "CodeLLDB no está instalado",
"{name} (child)": "{name} (hijo)",
"Enable breakpoint at {path}:{line}": "Habilitar punto de interrupción en {path}:{line}",
+5
Переглянути файл
@@ -1010,6 +1010,7 @@
"Install Plugin from Disk…": "Installer un plugin depuis le disque…",
"Install a plugin folder with": "Installez un dossier de plugin avec",
"Install and Debug": "Installer et déboguer",
"Reinstall and Debug": "Réinstaller et déboguer",
"Install gh…": "Installer gh…",
"Installed": "Installés",
"Installed packages": "Paquets installés",
@@ -1805,6 +1806,7 @@
"Running": "En cours d'exécution",
"Running processes requires the desktop app.": "L'exécution de processus nécessite l'application de bureau.",
"Runs Gradle with --offline": "Exécute Gradle avec --offline",
"Runs Gradle with -x test": "Exécute Gradle avec -x test",
"Runs Maven with -DskipTests": "Exécute Maven avec -DskipTests",
"Runs Maven with -o": "Exécute Maven avec -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Exécute Optimiser les imports lorsque le fichier ne contient pas d'erreur, sauf si cela modifie la ligne du curseur.",
@@ -2278,6 +2280,8 @@
"more": "de plus",
"Usages": "Utilisations",
"Code author": "Auteur du code",
"Position": "Position",
"Show “no usages”": "Afficher « aucune utilisation »",
"Usages Detected": "Utilisations détectées",
"Usages actions": "Actions sur les utilisations",
"Usages of '{symbol}'": "Utilisations de '{symbol}'",
@@ -3905,6 +3909,7 @@
"{class} reloaded": "{class} rechargée",
"The JavaScript debugger (vscode-js-debug) is not installed": "Le débogueur JavaScript (vscode-js-debug) n'est pas installé",
"Delve is not installed": "Delve n'est pas installé",
"Delve is too old for Go {go}": "Delve est trop ancien pour Go {go}",
"CodeLLDB is not installed": "CodeLLDB n'est pas installé",
"{name} (child)": "{name} (enfant)",
"Enable breakpoint at {path}:{line}": "Activer le point d'arrêt à {path}:{line}",
+5 -5
Переглянути файл
@@ -26,11 +26,6 @@
"Braces": "중괄호",
"Parentheses": "소괄호",
"Type annotation": "타입 어노테이션",
"Format specifier": "형식 지정자",
"Predefined name usage": "사전 정의된 이름 사용",
"Predefined function definition": "사전 정의된 함수 정의",
"Byte string": "바이트 문자열",
"F-string": "F-문자열",
"Nested function definition": "중첩 함수 정의",
"Local variable": "지역 변수",
"Global variable": "전역 변수",
@@ -1114,6 +1109,7 @@
"Install Plugin from Disk…": "디스크에서 플러그인 설치…",
"Install a plugin folder with": "다음으로 플러그인 폴더 설치",
"Install and Debug": "설치 및 디버그",
"Reinstall and Debug": "다시 설치 및 디버그",
"Install gh…": "gh 설치…",
"Installed": "설치됨",
"Installed packages": "설치된 패키지",
@@ -1945,6 +1941,7 @@
"Running": "실행 중",
"Running processes requires the desktop app.": "프로세스를 실행하려면 데스크톱 앱이 필요합니다.",
"Runs Gradle with --offline": "--offline으로 Gradle을 실행합니다",
"Runs Gradle with -x test": "-x test로 Gradle을 실행합니다",
"Runs Maven with -DskipTests": "-DskipTests로 Maven을 실행합니다",
"Runs Maven with -o": "-o로 Maven을 실행합니다",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "파일에 오류가 없으면 import 최적화를 실행합니다. 단, 캐럿 줄이 변경되는 경우는 제외합니다.",
@@ -2430,6 +2427,8 @@
"more": "더보기",
"Usages": "사용 위치",
"Code author": "코드 작성자",
"Position": "위치",
"Show “no usages”": "‘사용 위치 없음’ 표시",
"Usages Detected": "사용 위치 감지됨",
"Usages actions": "사용 위치 액션",
"Usages of '{symbol}'": "'{symbol}'의 사용 위치",
@@ -4105,6 +4104,7 @@
"{count} classes": "클래스 {count}개",
"The JavaScript debugger (vscode-js-debug) is not installed": "JavaScript 디버거(vscode-js-debug)가 설치되어 있지 않습니다",
"Delve is not installed": "Delve가 설치되어 있지 않습니다",
"Delve is too old for Go {go}": "Delve가 Go {go}을(를) 지원할 수 없을 만큼 오래되었습니다",
"CodeLLDB is not installed": "CodeLLDB가 설치되어 있지 않습니다",
"PHP Debug (Xdebug) is not installed": "PHP Debug(Xdebug)가 설치되어 있지 않습니다",
"Bash Debug is not installed": "Bash Debug가 설치되어 있지 않습니다",
+5
Переглянути файл
@@ -1065,6 +1065,7 @@
"Install Plugin from Disk…": "Zainstaluj wtyczkę z dysku…",
"Install a plugin folder with": "Zainstaluj folder wtyczki za pomocą",
"Install and Debug": "Zainstaluj i debuguj",
"Reinstall and Debug": "Zainstaluj ponownie i debuguj",
"Install gh…": "Zainstaluj gh…",
"Installed": "Zainstalowane",
"Installed packages": "Zainstalowane pakiety",
@@ -1880,6 +1881,7 @@
"Running": "Uruchomiono",
"Running processes requires the desktop app.": "Uruchamianie procesów wymaga aplikacji stacjonarnej.",
"Runs Gradle with --offline": "Uruchamia Gradle z opcją --offline",
"Runs Gradle with -x test": "Uruchamia Gradle z opcją -x test",
"Runs Maven with -DskipTests": "Uruchamia Maven z opcją -DskipTests",
"Runs Maven with -o": "Uruchamia Maven z opcją -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Uruchamia Optymalizację importów, gdy plik nie zawiera błędów, chyba że zmieniłoby to wiersz kursora.",
@@ -2353,6 +2355,8 @@
"more": "więcej",
"Usages": "Użycia",
"Code author": "Autor kodu",
"Position": "Pozycja",
"Show “no usages”": "Pokazuj „brak użyć”",
"Usages Detected": "Wykryto użycia",
"Usages actions": "Akcje użyć",
"Usages of '{symbol}'": "Użycia symbolu '{symbol}'",
@@ -4000,6 +4004,7 @@
"{count} classes": "Liczba klas: {count}",
"The JavaScript debugger (vscode-js-debug) is not installed": "Debuger JavaScript (vscode-js-debug) nie jest zainstalowany",
"Delve is not installed": "Delve nie jest zainstalowane",
"Delve is too old for Go {go}": "Delve jest zbyt stary dla Go {go}",
"CodeLLDB is not installed": "CodeLLDB nie jest zainstalowane",
"{name} (child)": "{name} (potomny)",
"Enable breakpoint at {path}:{line}": "Włącz punkt przerwania w {path}:{line}",
+5
Переглянути файл
@@ -1065,6 +1065,7 @@
"Install Plugin from Disk…": "Instalar plugin do disco…",
"Install a plugin folder with": "Instalar uma pasta de plugin com",
"Install and Debug": "Instalar e depurar",
"Reinstall and Debug": "Reinstalar e depurar",
"Install gh…": "Instalar gh…",
"Installed": "Instalados",
"Installed packages": "Pacotes instalados",
@@ -1880,6 +1881,7 @@
"Running": "Em execução",
"Running processes requires the desktop app.": "A execução de processos requer o aplicativo desktop.",
"Runs Gradle with --offline": "Executa o Gradle com --offline",
"Runs Gradle with -x test": "Executa o Gradle com -x test",
"Runs Maven with -DskipTests": "Executa o Maven com -DskipTests",
"Runs Maven with -o": "Executa o Maven com -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Executa Otimizar importações quando o arquivo não tiver erros, a menos que isso altere a linha do cursor.",
@@ -2354,6 +2356,8 @@
"more": "mais",
"Usages": "Usos",
"Code author": "Autor do código",
"Position": "Posição",
"Show “no usages”": "Mostrar “sem usos”",
"Usages Detected": "Usos detectados",
"Usages actions": "Ações de usos",
"Usages of '{symbol}'": "Usos de '{symbol}'",
@@ -4006,6 +4010,7 @@
"{count} classes": "{count} classes",
"The JavaScript debugger (vscode-js-debug) is not installed": "O depurador JavaScript (vscode-js-debug) não está instalado",
"Delve is not installed": "O Delve não está instalado",
"Delve is too old for Go {go}": "O Delve é antigo demais para o Go {go}",
"CodeLLDB is not installed": "O CodeLLDB não está instalado",
"{name} (child)": "{name} (filho)",
"Enable breakpoint at {path}:{line}": "Ativar ponto de interrupção em {path}:{line}",
+23 -6
Переглянути файл
@@ -275,18 +275,24 @@
"Braces": "花括号",
"Parentheses": "圆括号",
"Type annotation": "类型注解",
"Format specifier": "格式说明符",
"Predefined name usage": "预定义名称引用",
"Predefined function definition": "预定义函数定义",
"Byte string": "字节字符串",
"F-string": "F 字符串",
"Binary (bytes)": "二进制(字节)",
"f-string": "f-string",
"Expression braces": "表达式花括号",
"Format spec number": "格式说明符编号",
"'self' parameter": "'self' 参数",
"Special names": "特殊名称",
"Usage": "引用",
"Built-in name": "内置名称",
"Decorator": "装饰器",
"Keyword argument": "关键字实参",
"Nested function definition": "嵌套函数定义",
"Local variable": "局部变量",
"Local variables": "局部变量",
"Global variable": "全局变量",
"Instance attribute": "实例属性",
"Class attribute": "类属性",
"Constant": "常量",
"Type parameter": "类型参数",
"Type parameters": "类型参数",
"Unity": "Unity 项目",
"Show Meta Files": "显示 Meta 文件",
"Show Generated Files": "显示生成的文件",
@@ -307,6 +313,7 @@
"Edited within moved code": "移动代码中的修改",
"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)以启用这些检查。",
"Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.": "Vue 2(Options API)的模板跳转需要在 jsconfig.json / tsconfig.json 的 compilerOptions 里设置 'strictFunctionTypes': true(或 'strict': true):缺少该选项时,Vue 2.7 的类型会把 this 上的 methods、computed 推断为 any,模板内跳转定义和悬停都无法解析。加上该选项(若项目还没有配置文件则新建 jsconfig.json),然后重新打开文件或重启语言服务即可。",
"Auto-detect ({defaultProgram})": "自动检测({defaultProgram})",
"Custom executable": "自定义可执行文件",
"Found on PATH": "已在 PATH 中找到",
@@ -844,6 +851,9 @@
"Continue Revert": "继续还原",
"Contributes": "贡献",
"Convert to Encoding": "转换为编码",
"Add UTF-8 BOM": "添加 UTF-8 BOM",
"Remove UTF-8 BOM": "移除 UTF-8 BOM",
"Cannot change the UTF-8 BOM": "无法更改 UTF-8 BOM",
"Copied code keeps the editor's syntax colors and font when pasted into documents and mail.": "复制的代码粘贴到文档和邮件中时会保留编辑器的语法颜色和字体。",
"Copy": "复制",
"Copy / Paste Special": "复制/选择性粘贴",
@@ -1386,6 +1396,7 @@
"Install Plugin from Disk…": "从磁盘安装插件…",
"Install a plugin folder with": "安装插件文件夹:",
"Install and Debug": "安装并调试",
"Reinstall and Debug": "重新安装并调试",
"Install gh…": "安装 gh…",
"Installed": "已安装",
"Installed packages": "已安装的软件包",
@@ -2335,6 +2346,7 @@
"Running": "正在运行",
"Running processes requires the desktop app.": "运行进程需要桌面应用。",
"Runs Gradle with --offline": "使用 --offline 运行 Gradle",
"Runs Gradle with -x test": "使用 -x test 运行 Gradle",
"Runs Maven with -DskipTests": "使用 -DskipTests 运行 Maven",
"Runs Maven with -o": "使用 -o 运行 Maven",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "文件没有错误时运行“优化导入”,除非这会更改光标所在行。",
@@ -2830,6 +2842,8 @@
"more": "更多",
"Usages": "用法",
"Code author": "代码作者",
"Position": "位置",
"Show “no usages”": "显示“无用法”",
"Usages Detected": "检测到用法",
"Usages actions": "用法操作",
"Usages of '{symbol}'": "'{symbol}' 的用法",
@@ -4538,6 +4552,7 @@
"{count} classes": "{count} 个类",
"The JavaScript debugger (vscode-js-debug) is not installed": "JavaScript 调试器 (vscode-js-debug) 未安装",
"Delve is not installed": "Delve 未安装",
"Delve is too old for Go {go}": "Delve 版本过旧,不支持 Go {go}",
"CodeLLDB is not installed": "CodeLLDB 未安装",
"PHP Debug (Xdebug) is not installed": "PHP Debug (Xdebug) 未安装",
"Bash Debug is not installed": "Bash Debug 未安装",
@@ -7010,6 +7025,8 @@
"Gradle Tasks": "Gradle 任务",
"IDE MCP Server": "IDE MCP 服务器",
"Enable MCP server": "启用 MCP 服务器",
"Run tools without confirmation (brave mode)": "运行工具时不再确认(勇敢模式)",
"Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.": "运行配置、终端命令以及其他会修改项目的工具直接执行、不再询问,适合无人值守的智能体。只能在 IDE 自身的设置里开启,项目设置无法开启。",
"Running on port {port}": "正在端口 {port} 上运行",
"Failed to start: {error}": "启动失败:{error}",
"Not running": "未运行",
+30
Переглянути файл
@@ -535,3 +535,33 @@ describe("Tree indents", () => {
expect(placeholder?.style.paddingLeft).toBe("calc(24px + 1 * var(--tree-indent, 20px))");
});
});
describe("Tree double-click", () => {
it("selects on the first press without cancelling its default", () => {
const { tree } = setup();
const row = within(tree).getByRole("treeitem", { name: "README.md" });
expect(fireEvent.mouseDown(row, { button: 0, detail: 1 })).toBe(true);
expect(row).toHaveAttribute("aria-selected", "true");
});
it("cancels the second press so double-clicking cannot select label text, and still activates", () => {
const { tree, onActivate } = setup();
const row = within(tree).getByRole("treeitem", { name: "README.md" });
fireEvent.mouseDown(row, { button: 0, detail: 1 });
// The browser starts its word selection on this press; cancelling it keeps
// the labels unselected (jsdom reports cancellation through dispatchEvent).
expect(fireEvent.mouseDown(row, { button: 0, detail: 2 })).toBe(false);
fireEvent.doubleClick(row);
expect(onActivate).toHaveBeenCalledWith(expect.objectContaining({ id: "README.md" }), expect.anything());
expect(row).toHaveAttribute("aria-selected", "true");
});
it("still expands a folder on double-click", () => {
const { tree } = setup();
const row = within(tree).getByRole("treeitem", { name: "src" });
fireEvent.mouseDown(row, { button: 0, detail: 1 });
fireEvent.mouseDown(row, { button: 0, detail: 2 });
fireEvent.doubleClick(row);
expect(labels(tree)).toEqual(["src", "main", "util.ts", "README.md"]);
});
});
+11
Переглянути файл
@@ -590,6 +590,17 @@ export function Tree<T>(props: TreeProps<T>) {
return;
}
if (e.button !== 0) return;
// The second press of a double-click starts the browser's word selection,
// which in a virtualized tree spills onto the rows an expanding folder just
// inserted and highlights neighbouring labels. Prevent it: rows are
// controls, not text (the shared List does the same via `user-select`), the
// first press already selected, and the dblclick below still fires, so
// activation keeps working. Rows can host editors (inline rename), so this
// is scoped to repeated clicks instead of unselecting all row content.
if (e.detail >= 2) {
e.preventDefault();
return;
}
setQuery("");
if (e.shiftKey) selectIndex(i, "range");
else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle");