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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 5bfd7c0a7a feat(http-client): Generate HTTP requests from Spring Web mappings
Java and Kotlin controllers (@RestController / @Controller) get a gutter
icon on every request mapping and on the class. Its menu, the editor
context menu and Show Context Actions offer "Generate Request in HTTP
Client" (http.generateSpringRequest) and "Generate Requests for
Controller" (http.generateSpringControllerRequests).

Requests are appended to the generated-requests.http scratch (created on
first use, ### separated), which opens with the caret on the new request:
- class + method paths (several paths: a choice in the gutter menu),
  @RequestMapping#method or the shortcut annotations, {var} -> {{var}};
- @RequestParam -> query, @RequestHeader / headers= -> headers, params=;
- consumes / produces -> Content-Type / Accept, @RequestBody -> JSON body
  with the fields of the body type (same file, or the imported / sibling
  source file, one nested level);
- server.port, context path and SSL from application.properties / .yml of
  the module, else http://localhost:8080;
- static final / const val constants of the same file, Kotlin templates.

Sources are read by a small declaration-level Java/Kotlin reader
(annotations, classes, methods, fields), no new dependencies. Features can
now contribute context actions to the intentions popup through the
intentionProviders facet.

Fixes #100

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 20:53:01 +08:00
l0ng-ai 8568ff001b fix(i18n): Translate interpolated UI text through a tx template tag (#98)
About 270 UI strings were JS template literals with interpolation passed to exact catalog lookup, so they could never be translated; about 25 more spliced lowercase English fragments into sentences.

`tx` now also works as a template tag (`` tx`Remove data source '${name}'?` ``): it looks up the entry by the literal parts (`{name}` placeholders), translates interpolated values that have entries, and remembers generated text so it re-translates after a language switch or when the catalog loads later. Call sites use the tag; spliced fragments are written as whole sentences per variant. Adds 280 Chinese translations and removes stale ones.

The catalog guard now also fails on untagged template literals reaching exact lookup (unless allowlisted with a reason), tagged text missing from the catalog, case-changed or ternary-suffix interpolations, and duplicate template patterns.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:56:54 +08:00
胡翀таzzxzz12345 2a8e5e791d fix(diff): Keep distant edits as separate chunks and render continuous change blocks (#95)
In long files several distant edits could collapse into one large replacement that highlighted unchanged lines, and multi-line changes showed per-line stripes.

Lines are now matched before character-level changes. The line diff is anchored on lines that occur once on both sides (patience-style), with a bounded diff only between anchors, so 50k-line files with distant edits keep separate chunks. Whole inserted or deleted lines render as continuous blocks; paired modified lines keep the line background plus word-level highlights, also inside multi-line chunks. Line decorations are built for the visible range only.

Co-authored-by: zzxzz12345 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:54:15 +08:00
Walter WangтаClaude 3b608355a3 feat(themes): Built-in Solarized and One light/dark themes (#85)
Adds Solarized Light, Solarized Dark, One Light and One Dark as built-in themes across the workbench, editor, terminal and Mermaid, keeping the original palettes (MIT notices in THIRD_PARTY_LICENSES.md, mapping in docs/themes.md).

- Native window colours are read from tokens.css at build time (`theme_frame.rs`) instead of a second colour table.
- Startup restores the built-in palette before first paint.
- Editor schemes, the terminal and Mermaid refresh on switches between themes of the same kind.
- The plugin packages of the same themes are removed.
- A test requires every built-in palette theme to define each token (only listed ones may inherit from the base theme), so new tokens can't silently miss them.

Co-authored-by: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:53:12 +08:00
l0ng-ai 50308a956d feat(maven): Dependency Analyzer with conflicts, usage paths and Exclude (#97)
Maven sync ran a plain `dependency:tree`, which drops the nodes Maven omits (conflict losers, duplicates), so there was no data to show where a conflict comes from.

Sync now runs `maven-dependency-plugin:3.8.1:tree -Dverbose` (the project's own plugin version when offline) and records omitted / conflictWith / managedFrom per node; omitted nodes stay out of the Maven tool window and External Libraries, and older caches are marked stale. The new Dependency Analyzer (Maven toolbar, module / Dependencies node menus, pom.xml menus, Find Action) lists a module's resolved artifacts or tree with conflict markers, search and scope filters, and every path to the selected artifact with its status. Exclude writes an `<exclusion>` into the declaring pom (module or in-project parent), keeping indentation and line endings, then reloads; Jump to Source and Copy Coordinates are on each path. Gradle is not covered yet.

Fixes #87

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:51:33 +08:00
l0ng-ai c666cee075 feat(project-tree): Expand directories with a single click (#96)
Adds "Expand Directories with Single Click" to the Project view options (Behavior group, off by default). When on, a plain left click anywhere on a directory row expands or collapses it (a compacted path opens its whole chain); a double-click toggles once, and modifier clicks, drag-and-drop, inline rename and the context menu are unaffected. Project view option toggles now show their checked state in Find Action, and the options menu is translated.

Fixes #94

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:43:39 +08:00
l0ng-ai a971483162 fix(ci): Drop a stale Chinese catalog entry and unix-only imports on Windows
The Solarized dark variant's description no longer appears in the source, so the
catalog check failed on its leftover translation. LaunchError and Launcher are
only used by the unix-only tcp_server tests and were unused imports on Windows.
2026-10-27 18:17:06 +08:00
l0ng-ai 2616e3fe6d fix(i18n): Translate missing Chinese UI text and guard the text catalog (#93)
The source-text catalog (locales/text/zh.json) is keyed by the English text, so reworded or new UI strings silently fell back to English (e.g. the language server JDK hint on the Java settings page). Adds the 321 missing Chinese translations, updates the 3 reworded keys, removes 45 stale keys, and makes the file-refactoring failure titles translatable.

New guard test (src/platform/locales/textCatalog.test.ts) parses src/ for literals that reach the translation layer and fails on missing or stale catalog entries, with an explicit allowlist for untranslated text.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:04:35 +08:00
l0ng-ai b5bd8e3935 chore: v0.1.17 2026-10-27 17:58:55 +08:00
l0ng-aiтаbghtyu 24330192c0 feat(themes): Solarized and One theme plugins (#92)
Solarized Light/Dark and One Light/Dark ship as theme plugins (plugins/theme-solarized, plugins/theme-one) with complete UI tokens, editor schemes and terminal colours, and the original palettes' MIT notices. Installing a plugin now also copies its LICENSE/NOTICE/COPYING.

Theme handling that benefits every plugin theme:
- The last plugin theme is restored before first paint (splash, workbench); the native window background follows the theme.
- HSL / color-mix() / var() colours are resolved to RGB for native windows, the Settings window and Mermaid.
- Mermaid, the terminal and editor schemes follow switches between two themes of the same kind.
- An explicitly chosen editor scheme wins over a plugin theme's editor colours.

Supersedes #85.

Co-authored-by: bghtyu <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 17:53:07 +08:00
226 змінених файлів з 7165 додано та 697 видалено

No files matched your search

Створено
+30 -30
Переглянути файл
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -3980,7 +3980,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3994,7 +3994,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4009,11 +4009,11 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.16"
version = "0.1.17"
[[package]]
name = "ide-core"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"dunce",
"serde",
@@ -4025,7 +4025,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-run",
@@ -4039,7 +4039,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4056,7 +4056,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4076,7 +4076,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"libc",
@@ -4090,7 +4090,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4104,7 +4104,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"parking_lot",
@@ -4122,7 +4122,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"blake3",
"criterion",
@@ -4144,7 +4144,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"futures",
"ide-core",
@@ -4159,7 +4159,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"blake3",
"criterion",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"futures",
"globset",
@@ -4235,7 +4235,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-language",
@@ -4253,7 +4253,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-run",
@@ -4266,7 +4266,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4286,7 +4286,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"dunce",
"ide-core",
@@ -4305,7 +4305,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"criterion",
"globset",
@@ -4325,7 +4325,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"parking_lot",
@@ -4338,7 +4338,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-language",
@@ -4353,7 +4353,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"libc",
@@ -4366,7 +4366,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"criterion",
"ide-core",
@@ -4378,7 +4378,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"flate2",
"hex",
@@ -4398,7 +4398,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"dunce",
"gix",
@@ -4415,7 +4415,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"chardetng",
"dunce",
@@ -4436,7 +4436,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"ide-core",
"open",
@@ -4452,7 +4452,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"blake3",
"dunce",
@@ -5877,7 +5877,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.16"
version = "0.1.17"
dependencies = [
"dirs 6.0.0",
"dunce",
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.16"
version = "0.1.17"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+83
Переглянути файл
@@ -157,3 +157,86 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
## Solarized
The Solarized palettes in `src/styles/tokens.css` are adapted from
[Ethan Schoonover’s Solarized](https://github.com/altercation/solarized/tree/62f656a02f93c5190a8753159e34b385588d5ff3).
See [theme sources and mapping](docs/themes.md). MIT license:
```text
Copyright (c) 2011 Ethan Schoonover
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.
```
## Atom One Light and One Dark
The One palettes and semantic syntax mapping in `src/styles/tokens.css` are
adapted from GitHub’s Atom One syntax and UI themes.
Source revisions are listed in [theme sources and mapping](docs/themes.md).
Both syntax themes use the following MIT notice:
```text
Copyright (c) 2016 GitHub Inc.
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.
```
Both UI themes use the following MIT notice:
```text
Copyright (c) 2014 GitHub Inc.
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.
```
+19 -2
Переглянути файл
@@ -8,12 +8,13 @@
pub mod compile;
pub mod gradle;
pub mod maven;
pub mod pom_edit;
mod process;
mod sync;
mod xml;
pub use gradle::{GradleModel, GradleProject, GradleTask};
pub use maven::{MavenDependency, MavenModel, MavenPlugin, MavenProfile, MavenProject};
pub use maven::{MavenDependency, MavenModel, MavenPlugin, MavenProfile, MavenProject, Omission};
pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
use serde::{Deserialize, Serialize};
@@ -69,6 +70,10 @@ pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<Dependency
let modules: std::collections::HashSet<String> = m.projects.iter().map(MavenProject::key).collect();
let mut stack: Vec<&MavenDependency> = m.projects.iter().flat_map(|p| &p.dependencies).collect();
while let Some(d) = stack.pop() {
// Omitted occurrences (conflict losers, duplicates) are not on any classpath.
if !d.resolved() {
continue;
}
stack.extend(&d.children);
let Some(version) = d.version.as_deref().filter(|v| !v.is_empty() && !v.contains("${")) else {
continue;
@@ -150,7 +155,19 @@ mod tests {
artifact_id: "app".into(),
dependencies: vec![
dep("me", "core", Some("1"), vec![]),
dep("org.b", "y", Some("2"), vec![dep("org.c", "z", Some("3"), vec![])]),
dep(
"org.b",
"y",
Some("2"),
vec![
dep("org.c", "z", Some("3"), vec![]),
MavenDependency {
omitted: Some(Omission::Conflict),
conflict_with: Some("3".into()),
..dep("org.c", "z", Some("1"), vec![])
},
],
),
dep("org.d", "unresolved", Some("${v}"), vec![]),
],
..Default::default()
+141 -10
Переглянути файл
@@ -130,6 +130,37 @@ pub struct MavenDependency {
pub optional: bool,
/// Transitive dependencies (only after a sync).
pub children: Vec<MavenDependency>,
/// Why Maven left this occurrence out of the resolved graph (`dependency:tree -Dverbose`).
#[serde(default)]
#[specta(optional)]
pub omitted: Option<Omission>,
/// The version that won when `omitted` is `Conflict`.
#[serde(default)]
#[specta(optional)]
pub conflict_with: Option<String>,
/// The version requested before `<dependencyManagement>` replaced it.
#[serde(default)]
#[specta(optional)]
pub managed_from: Option<String>,
}
impl MavenDependency {
/// Part of the resolved graph (not a verbose-tree placeholder for an omitted occurrence).
pub fn resolved(&self) -> bool {
self.omitted.is_none()
}
}
/// Why a dependency occurrence is not part of the resolved graph.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Omission {
/// Another occurrence of the same version is nearer the root.
Duplicate,
/// Another version is nearer the root (or declared first) and wins.
Conflict,
/// The artifact depends on itself through this path.
Cycle,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -871,7 +902,7 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
classifier: d.classifier.clone(),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
optional: d.optional,
children: Vec::new(),
..MavenDependency::default()
})
.collect();
@@ -968,7 +999,7 @@ pub fn parse_effective_pom(text: &str) -> Vec<(String, Vec<MavenPlugin>, Vec<Mav
classifier: d.classifier.clone(),
scope: d.scope.clone().unwrap_or_else(|| "compile".into()),
optional: d.optional,
children: Vec::new(),
..MavenDependency::default()
})
.collect();
(format!("{group}:{}", raw.artifact_id), plugins, deps)
@@ -976,13 +1007,16 @@ pub fn parse_effective_pom(text: &str) -> Vec<(String, Vec<MavenPlugin>, Vec<Mav
.collect()
}
/// `g:a:type[:classifier]:version[:scope]` from a `dependency:tree` line.
/// `g:a:type[:classifier]:version[:scope]` from a `dependency:tree` line, with the
/// `-Dverbose` annotations: `(g:a:jar:1:compile - omitted for conflict with 2)`,
/// `g:a:jar:1:compile (version managed from 0.9)`, `(optional)`.
fn parse_coords(s: &str) -> Option<MavenDependency> {
let s = s.trim();
let (coords, extra) = match s.find(" (") {
Some(i) => (&s[..i], &s[i..]),
None => (s, ""),
let (s, wrapped) = match s.strip_prefix('(').and_then(|r| r.strip_suffix(')')) {
Some(inner) => (inner, true),
None => (s, false),
};
let (coords, notes) = s.split_once(' ').unwrap_or((s, ""));
let parts: Vec<&str> = coords.split(':').collect();
let (g, a, t, c, v, scope) = match parts.as_slice() {
[g, a, t, v] => (g, a, t, None, v, None),
@@ -990,16 +1024,35 @@ fn parse_coords(s: &str) -> Option<MavenDependency> {
[g, a, t, c, v, s] => (g, a, t, Some(*c), v, Some(*s)),
_ => return None,
};
Some(MavenDependency {
let mut dep = MavenDependency {
group_id: (*g).to_owned(),
artifact_id: (*a).to_owned(),
version: Some((*v).to_owned()),
kind: (*t).to_owned(),
classifier: c.map(|c| (*c).to_owned()),
scope: scope.unwrap_or("compile").to_owned(),
optional: extra.contains("optional"),
children: Vec::new(),
})
..MavenDependency::default()
};
let notes = notes.replace(['(', ')'], ";").replace(" - ", ";");
for note in notes.split(';').map(|n| n.trim().trim_start_matches("- ").trim()) {
if note == "optional" {
dep.optional = true;
} else if let Some(winner) = note.strip_prefix("omitted for conflict with ") {
dep.omitted = Some(Omission::Conflict);
dep.conflict_with = Some(winner.trim().to_owned());
} else if note == "omitted for duplicate" {
dep.omitted = Some(Omission::Duplicate);
} else if note == "omitted for cycle" {
dep.omitted = Some(Omission::Cycle);
} else if let Some(from) = note.strip_prefix("version managed from ") {
dep.managed_from = Some(from.trim().to_owned());
}
}
// A parenthesised line is always an omitted occurrence, even with an unknown reason.
if wrapped && dep.omitted.is_none() {
dep.omitted = Some(Omission::Duplicate);
}
Some(dep)
}
fn insert_at(list: &mut Vec<MavenDependency>, depth: usize, dep: MavenDependency) {
@@ -1327,4 +1380,82 @@ mod tests {
);
assert_eq!(trees[2].1[0].scope, "compile");
}
/// `mvn org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree -Dverbose` on a project
/// whose libraries ask for different commons-lang3 / commons-text / guava versions.
#[test]
fn verbose_dependency_tree_output() {
let trees = parse_dependency_tree(include_str!("../testdata/dependency-tree-verbose.txt"));
assert_eq!(trees.len(), 1);
let (key, deps) = &trees[0];
assert_eq!(key, "demo:conflict-demo");
let direct: Vec<&str> = deps.iter().map(|d| d.artifact_id.as_str()).collect();
assert_eq!(direct, ["hamcrest-core", "commons-text", "commons-configuration2", "guava", "guice", "junit"]);
assert!(deps.iter().all(MavenDependency::resolved));
let config = &deps[2].children;
let lang3 = &config[0];
assert_eq!(
(lang3.artifact_id.as_str(), lang3.version.as_deref(), lang3.omitted, lang3.conflict_with.as_deref()),
("commons-lang3", Some("3.14.0"), Some(Omission::Conflict), Some("3.12.0"))
);
assert_eq!(lang3.scope, "compile");
let logging = &config[2];
assert_eq!(
(logging.version.as_deref(), logging.managed_from.as_deref(), logging.omitted),
(Some("1.2"), Some("1.3.0"), None)
);
let guava = &deps[4].children[2];
assert_eq!((guava.version.as_deref(), guava.conflict_with.as_deref()), (Some("30.1-jre"), Some("32.1.3-jre")));
let hamcrest = &deps[5].children[0];
assert_eq!((hamcrest.omitted, hamcrest.scope.as_str()), (Some(Omission::Duplicate), "test"));
assert_eq!(deps[1].children[0].omitted, None, "the winning commons-lang3");
}
#[test]
fn verbose_annotations() {
// (line, omitted, conflict winner, managed from, optional)
type Case<'a> = (&'a str, Option<Omission>, Option<&'a str>, Option<&'a str>, bool);
let cases: &[Case] = &[
("(g:a:jar:1:compile - omitted for cycle)", Some(Omission::Cycle), None, None, false),
(
"(g:a:jar:1:compile - version managed from 0.9; omitted for duplicate)",
Some(Omission::Duplicate),
None,
Some("0.9"),
false,
),
("g:a:jar:1:compile (optional)", None, None, None, true),
(
"(g:a:jar:1:runtime (optional) - omitted for conflict with 2)",
Some(Omission::Conflict),
Some("2"),
None,
true,
),
(
"(g:a:jar:1:compile - scope updated from runtime; omitted for duplicate)",
Some(Omission::Duplicate),
None,
None,
false,
),
(
"g:a:jar:1:compile (version managed from 0.9; scope managed from runtime)",
None,
None,
Some("0.9"),
false,
),
];
for (line, omitted, winner, managed, optional) in cases {
let d = parse_coords(line).unwrap();
assert_eq!(
(d.omitted, d.conflict_with.as_deref(), d.managed_from.as_deref(), d.optional),
(*omitted, *winner, *managed, *optional),
"{line}"
);
assert_eq!((d.group_id.as_str(), d.version.as_deref()), ("g", Some("1")), "{line}");
}
}
}
+336
Переглянути файл
@@ -0,0 +1,336 @@
//! Edits of `pom.xml` text for the dependency analyzer: finding where a direct
//! dependency is declared and adding an `<exclusion>` to it, in the style
//! (indentation, line endings, one-line elements) of the surrounding POM.
use crate::maven::{self, MavenModel};
use crate::xml::{self, Element};
use ide_core::{Pos, Range, TextEdit};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{HashMap, HashSet};
/// `groupId:artifactId` of a dependency.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactKey {
pub group_id: String,
pub artifact_id: String,
}
impl ArtifactKey {
pub fn new(group_id: impl Into<String>, artifact_id: impl Into<String>) -> Self {
Self { group_id: group_id.into(), artifact_id: artifact_id.into() }
}
}
impl std::fmt::Display for ArtifactKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.group_id, self.artifact_id)
}
}
/// What adding an exclusion does to a POM.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Exclusion {
/// The edit that adds it.
Edit(TextEdit),
/// The dependency already excludes it (or everything, `*:*`).
Present,
}
/// Properties the coordinates of a POM's dependencies may refer to.
fn properties(project: &Element) -> HashMap<String, String> {
let mut props: HashMap<String, String> = project
.child("properties")
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
.unwrap_or_default();
let own_or_parent = |name: &str| project.text_of(name).or_else(|| project.child("parent")?.text_of(name));
for (key, value) in [
("project.groupId", own_or_parent("groupId")),
("project.version", own_or_parent("version")),
("project.artifactId", project.text_of("artifactId")),
] {
if let Some(v) = value {
props.insert(key.into(), v);
}
}
props
}
fn matches(e: &Element, key: &ArtifactKey, props: &HashMap<String, String>) -> bool {
let text = |name: &str| e.text_of(name).map(|t| maven::interpolate(&t, props));
text("groupId").as_deref() == Some(key.group_id.as_str())
&& text("artifactId").as_deref() == Some(key.artifact_id.as_str())
}
/// The `<dependency>` declaring `key` in the project's `<dependencies>`, else in a
/// profile's (never `<dependencyManagement>`, which declares no dependency).
fn find_dependency<'a>(project: &'a Element, key: &ArtifactKey) -> Option<&'a Element> {
let props = properties(project);
let own = project.list("dependencies", "dependency");
let profiles = project.list("profiles", "profile").into_iter().flat_map(|p| p.list("dependencies", "dependency"));
own.into_iter().chain(profiles).find(|d| matches(d, key, &props))
}
/// 0-based line / UTF-16 column of byte offset `at`.
fn pos_at(text: &str, at: usize) -> Pos {
let before = &text[..at];
let line_start = before.rfind('\n').map_or(0, |i| i + 1);
Pos::new(before.matches('\n').count() as u32, before[line_start..].encode_utf16().count() as u32)
}
fn line_start(text: &str, at: usize) -> usize {
text[..at].rfind('\n').map_or(0, |i| i + 1)
}
/// The whitespace before `at` on its line, or `None` when other text precedes it there.
fn indent_before(text: &str, at: usize) -> Option<&str> {
let ws = &text[line_start(text, at)..at];
ws.chars().all(|c| c == ' ' || c == '\t').then_some(ws)
}
/// One level of indentation: what the first child of `e` adds to `e`'s, else two spaces.
fn indent_unit(text: &str, e: &Element) -> String {
let outer = indent_before(text, e.start);
let inner = e.children.first().and_then(|c| indent_before(text, c.start));
match (outer, inner) {
(Some(o), Some(i)) if i.len() > o.len() && i.starts_with(o) => i[o.len()..].to_owned(),
(_, Some(i)) if i.starts_with('\t') => "\t".into(),
_ => " ".into(),
}
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;")
}
/// Range of the `<artifactId>` of the dependency declaring `key` in `text` (a POM), or of
/// the whole `<dependency>` when it has none; `None` when the POM does not declare it.
pub fn declaration(text: &str, key: &ArtifactKey) -> Option<Range> {
let project = xml::parse(text)?;
let dep = find_dependency(&project, key)?;
let target = dep.child("artifactId").unwrap_or(dep);
Some(Range::new(pos_at(text, target.start), pos_at(text, target.end)))
}
/// Adds `exclude` to the `<exclusions>` of the dependency declaring `dependency` in `text`
/// (a POM); `None` when the POM does not declare it.
pub fn add_exclusion(text: &str, dependency: &ArtifactKey, exclude: &ArtifactKey) -> Option<Exclusion> {
let project = xml::parse(text)?;
let dep = find_dependency(&project, dependency)?;
let nl = if text.contains("\r\n") { "\r\n" } else { "\n" };
let unit = indent_unit(text, dep);
let (g, a) = (escape(&exclude.group_id), escape(&exclude.artifact_id));
// Insert `block` (lines relative to `parent`'s indentation + one level) before `parent`'s
// end tag; on one line (`compact`) when `parent` is not laid out one element per line.
let insert = |parent: &Element, lines: &[(usize, String)], compact: String| {
let close_on_own_line = indent_before(text, parent.inner_end).is_some() && parent.inner_end < parent.end;
let (at, new_text) = match indent_before(text, parent.start) {
Some(base) if close_on_own_line => {
let mut out = String::new();
for (depth, line) in lines {
out.push_str(base);
out.push_str(&unit.repeat(depth + 1));
out.push_str(line);
out.push_str(nl);
}
(line_start(text, parent.inner_end), out)
}
_ => (parent.inner_end, compact),
};
let p = pos_at(text, at);
Exclusion::Edit(TextEdit { range: Range::point(p), new_text })
};
let exclusion_lines = |depth: usize| {
vec![
(depth, "<exclusion>".to_owned()),
(depth + 1, format!("<groupId>{g}</groupId>")),
(depth + 1, format!("<artifactId>{a}</artifactId>")),
(depth, "</exclusion>".to_owned()),
]
};
let compact = format!("<exclusion><groupId>{g}</groupId><artifactId>{a}</artifactId></exclusion>");
if let Some(exclusions) = dep.child("exclusions") {
let props = properties(&project);
let wildcard = ArtifactKey::new("*", "*");
let any_artifact = ArtifactKey::new(exclude.group_id.clone(), "*");
if exclusions
.children_named("exclusion")
.any(|e| [exclude, &wildcard, &any_artifact].iter().any(|k| matches(e, k, &props)))
{
return Some(Exclusion::Present);
}
return Some(insert(exclusions, &exclusion_lines(0), compact));
}
let mut lines = vec![(0, "<exclusions>".to_owned())];
lines.extend(exclusion_lines(1));
lines.push((0, "</exclusions>".to_owned()));
Some(insert(dep, &lines, format!("<exclusions>{compact}</exclusions>")))
}
/// The POMs that may declare a dependency of the module `pom` (project-relative), nearest
/// first: the module's own, then its parents that are part of the project.
pub fn declaring_poms(model: &MavenModel, pom: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
let mut current = model.projects.iter().find(|p| p.pom == pom);
while let Some(p) = current {
if !seen.insert(p.pom.clone()) {
break;
}
out.push(p.pom.clone());
current = p.parent.as_deref().and_then(|coords| {
model.projects.iter().find(|q| format!("{}:{}:{}", q.group_id, q.artifact_id, q.version) == coords)
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn apply(text: &str, edit: &TextEdit) -> String {
let offset = |p: Pos| {
let start: usize = text.split_inclusive('\n').take(p.line as usize).map(str::len).sum();
let line = &text[start..];
start + line.char_indices().nth(p.col as usize).map_or(line.len(), |(i, _)| i)
};
let (from, to) = (offset(edit.range.start), offset(edit.range.end));
format!("{}{}{}", &text[..from], edit.new_text, &text[to..])
}
fn exclude(text: &str, dep: (&str, &str), excl: (&str, &str)) -> Option<String> {
match add_exclusion(text, &ArtifactKey::new(dep.0, dep.1), &ArtifactKey::new(excl.0, excl.1))? {
Exclusion::Edit(e) => Some(apply(text, &e)),
Exclusion::Present => Some(text.to_owned()),
}
}
const POM: &str = "<project>
<groupId>demo</groupId>
<properties>
<guice.group>com.google.inject</guice.group>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>${guice.group}</groupId>
<artifactId>guice</artifactId>
</dependency>
</dependencies>
</project>
";
#[test]
fn adds_exclusions_to_the_declaration_not_the_managed_entry() {
let out = exclude(POM, ("com.google.inject", "guice"), ("com.google.guava", "guava")).unwrap();
let expected = POM.replace(
" <artifactId>guice</artifactId>\n </dependency>\n </dependencies>",
" <artifactId>guice</artifactId>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>",
);
assert_eq!(out, expected);
// A second exclusion joins the first; excluding it again changes nothing.
let twice = exclude(&out, ("com.google.inject", "guice"), ("aopalliance", "aopalliance")).unwrap();
assert!(twice.contains(
" </exclusion>
<exclusion>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
</exclusion>
</exclusions>"
));
assert_eq!(exclude(&twice, ("com.google.inject", "guice"), ("aopalliance", "aopalliance")).unwrap(), twice);
}
#[test]
fn keeps_tabs_crlf_and_one_line_dependencies() {
let tabs = "<project>\r\n\t<dependencies>\r\n\t\t<dependency>\r\n\t\t\t<groupId>g</groupId>\r\n\t\t\t<artifactId>a</artifactId>\r\n\t\t</dependency>\r\n\t</dependencies>\r\n</project>\r\n";
let out = exclude(tabs, ("g", "a"), ("x", "y")).unwrap();
assert!(out.contains("<artifactId>a</artifactId>\r\n\t\t\t<exclusions>\r\n\t\t\t\t<exclusion>\r\n\t\t\t\t\t<groupId>x</groupId>\r\n"));
assert!(out.contains("\t\t\t</exclusions>\r\n\t\t</dependency>"));
let inline = "<project><dependencies><dependency><groupId>g</groupId><artifactId>a</artifactId></dependency></dependencies></project>";
assert_eq!(
exclude(inline, ("g", "a"), ("x", "y")).unwrap(),
"<project><dependencies><dependency><groupId>g</groupId><artifactId>a</artifactId><exclusions><exclusion><groupId>x</groupId><artifactId>y</artifactId></exclusion></exclusions></dependency></dependencies></project>"
);
}
#[test]
fn wildcards_profiles_and_missing_declarations() {
let pom = "<project>
<profiles>
<profile>
<dependencies>
<dependency>
<groupId>g</groupId><artifactId>a</artifactId>
<exclusions><exclusion><groupId>x</groupId><artifactId>*</artifactId></exclusion></exclusions>
</dependency>
</dependencies>
</profile>
</profiles>
</project>";
let key = ArtifactKey::new("g", "a");
assert_eq!(add_exclusion(pom, &key, &ArtifactKey::new("x", "y")), Some(Exclusion::Present));
let out = exclude(pom, ("g", "a"), ("z", "w")).unwrap();
assert!(out.contains(
"</exclusion><exclusion><groupId>z</groupId><artifactId>w</artifactId></exclusion></exclusions>"
));
assert_eq!(add_exclusion(pom, &ArtifactKey::new("g", "other"), &key), None);
assert_eq!(add_exclusion("not xml", &key, &key), None);
}
#[test]
fn declaration_ranges_use_utf16_columns() {
let pom = "<project><!-- é😀 --><dependencies>\n <dependency><groupId>g</groupId><artifactId>a</artifactId></dependency>\n</dependencies></project>";
let r = declaration(pom, &ArtifactKey::new("g", "a")).unwrap();
assert_eq!(r, Range::new(Pos::new(1, 34), Pos::new(1, 60)));
let first = "<project><!-- é😀 --><dependencies><dependency><groupId>g</groupId><artifactId>a</artifactId>";
let r = declaration(&format!("{first}</dependency></dependencies></project>"), &ArtifactKey::new("g", "a"))
.unwrap();
let start = first.find("<artifactId>").unwrap();
assert_eq!(r.start.col as usize, first[..start].encode_utf16().count());
}
#[test]
fn declaring_poms_follow_parents_inside_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let write = |rel: &str, text: &str| {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
};
write(
"pom.xml",
"<project><groupId>d</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>",
);
write(
"app/pom.xml",
"<project><parent><groupId>d</groupId><artifactId>parent</artifactId><version>1</version></parent><artifactId>app</artifactId></project>",
);
let model = maven::load_with_repo(root, None);
assert_eq!(declaring_poms(&model, "app/pom.xml"), ["app/pom.xml", "pom.xml"]);
assert_eq!(declaring_poms(&model, "pom.xml"), ["pom.xml"]);
assert!(declaring_poms(&model, "missing/pom.xml").is_empty());
}
}
+43 -6
Переглянути файл
@@ -1,5 +1,5 @@
//! Reading the effective build from Maven / Gradle itself ("Reload" in the tool
//! windows): `mvn help:effective-pom dependency:tree` and `gradle tasks --all`,
//! windows): `mvn help:effective-pom dependency:tree -Dverbose` and `gradle tasks --all`,
//! run in the background with progress and cancellation. Results are cached
//! per project (`maven.json`, `gradle.json` in the cache directory) and merged
//! into the static model by [`crate::load`]; a changed build file marks them stale.
@@ -49,6 +49,9 @@ struct MavenCache {
at_ms: f64,
error: Option<String>,
projects: Vec<CachedMavenProject>,
/// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded.
#[serde(default)]
verbose: bool,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -60,6 +63,21 @@ struct GradleCache {
}
const MAVEN_CACHE: &str = "maven.json";
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, the project's own plugin version is used instead, since this one may not be cached.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
/// The goals that read the effective POM into `effective` and the verbose dependency trees.
fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
vec![
"help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()),
if offline { "dependency:tree".into() } else { DEPENDENCY_TREE.into() },
"-Dverbose".into(),
]
}
const GRADLE_CACHE: &str = "gradle.json";
fn read_cache<T: DeserializeOwned>(dir: &Path, name: &str) -> Option<T> {
@@ -110,7 +128,7 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
}
model.synced_at = Some(cache.at_ms);
model.sync_error = cache.error;
model.stale = cache.hash != hash_files(&maven::build_files(root, model));
model.stale = !cache.verbose || cache.hash != hash_files(&maven::build_files(root, model));
}
/// Merges the cached task list into `model`.
@@ -182,7 +200,8 @@ pub fn sync_maven(
) -> IdeResult<()> {
let model = maven::load(root);
std::fs::create_dir_all(cache_dir)?;
let mut cache = MavenCache { hash: hash_files(&maven::build_files(root, &model)), ..MavenCache::default() };
let mut cache =
MavenCache { hash: hash_files(&maven::build_files(root, &model)), verbose: true, ..MavenCache::default() };
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -195,9 +214,7 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
args.push("help:effective-pom".into());
args.push(format!("-Doutput={}", effective.to_string_lossy()));
args.push("dependency:tree".into());
args.extend(maven_sync_goals(&effective, options.offline));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
@@ -277,6 +294,7 @@ mod tests {
hash: hash_files(&maven::build_files(&root, &model)),
at_ms: 5.0,
error: None,
verbose: true,
projects: vec![CachedMavenProject {
key: "g:a".into(),
plugins: vec![maven::plugin(
@@ -327,6 +345,25 @@ mod tests {
assert!(!model.stale);
}
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline() {
let online = maven_sync_goals(Path::new("e.xml"), false);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let offline = maven_sync_goals(Path::new("e.xml"), true);
assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
}
#[test]
fn cache_written_before_omissions_existed_still_loads() {
let json = r#"{"hash":"x","at_ms":1.0,"error":null,"projects":[{"key":"g:a","plugins":[],
"dependencies":[{"groupId":"g","artifactId":"d","version":"1","type":"jar","classifier":null,
"scope":"compile","optional":false,"children":[]}]}]}"#;
let cache: MavenCache = serde_json::from_str(json).unwrap();
assert!(cache.projects[0].dependencies[0].resolved());
assert!(!cache.verbose, "reloaded to read the omitted occurrences");
}
#[test]
fn progress_and_error_lines() {
assert_eq!(
+42 -7
Переглянути файл
@@ -1,12 +1,19 @@
//! A small, forgiving XML element reader for POM files: elements, text and
//! CDATA; attributes, comments, processing instructions and DOCTYPEs are
//! skipped. Namespace prefixes are dropped (`<x:project>` → `project`).
//! Elements keep their byte offsets in the source, for edits ([`crate::pom_edit`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Element {
pub name: String,
pub text: String,
pub children: Vec<Element>,
/// Byte offset of the start tag's `<`.
pub start: usize,
/// Byte offset of the end tag's `<` (`end` for an empty or unclosed element).
pub inner_end: usize,
/// Byte offset just past the end tag (past the start tag for `<empty/>`).
pub end: usize,
}
impl Element {
@@ -76,6 +83,7 @@ fn local(name: &str) -> String {
pub fn parse(text: &str) -> Option<Element> {
let mut stack: Vec<Element> = vec![Element::default()];
let mut rest = text;
let at = |rest: &str| text.len() - rest.len();
while !rest.is_empty() {
let Some(lt) = rest.find('<') else {
decode_entities(rest, &mut stack.last_mut()?.text);
@@ -98,13 +106,19 @@ pub fn parse(text: &str) -> Option<Element> {
} else if let Some(body) = tag.strip_prefix("</") {
let end = body.find('>').unwrap_or(body.len());
let name = local(body[..end].trim());
if let Some(at) = stack.iter().rposition(|e| e.name == name).filter(|&i| i > 0) {
while stack.len() > at {
let done = stack.pop()?;
let close_start = at(tag);
rest = body.get(end + 1..).unwrap_or("");
let close_end = at(rest);
if let Some(i) = stack.iter().rposition(|e| e.name == name).filter(|&i| i > 0) {
while stack.len() > i {
let mut done = stack.pop()?;
// Elements closed implicitly by an outer end tag end where it starts.
let matched = stack.len() == i;
done.inner_end = close_start;
done.end = if matched { close_end } else { close_start };
stack.last_mut()?.children.push(done);
}
}
rest = body.get(end + 1..).unwrap_or("");
} else {
// Start or empty tag; skip quoted attribute values when looking for `>`.
let bytes = tag.as_bytes();
@@ -124,17 +138,22 @@ pub fn parse(text: &str) -> Option<Element> {
let empty = inner.ends_with('/');
let inner = inner.trim_end_matches('/');
let name_end = inner.find(|c: char| c.is_whitespace()).unwrap_or(inner.len());
let el = Element { name: local(&inner[..name_end]), ..Element::default() };
let start = at(tag);
rest = tag.get(i + 1..).unwrap_or("");
let after = at(rest);
let el =
Element { name: local(&inner[..name_end]), start, inner_end: after, end: after, ..Element::default() };
if empty {
stack.last_mut()?.children.push(el);
} else {
stack.push(el);
}
rest = tag.get(i + 1..).unwrap_or("");
}
}
while stack.len() > 1 {
let done = stack.pop()?;
let mut done = stack.pop()?;
done.inner_end = text.len();
done.end = text.len();
stack.last_mut()?.children.push(done);
}
stack.pop()?.children.into_iter().next()
@@ -167,6 +186,22 @@ mod tests {
assert_eq!(root.children_named("name").count(), 1);
}
#[test]
fn element_offsets() {
let doc = "<a>\n <b>x</b><c/>\n</a>";
let root = parse(doc).unwrap();
assert_eq!((root.start, root.inner_end, root.end), (0, doc.len() - 4, doc.len()));
let b = root.child("b").unwrap();
assert_eq!(&doc[b.start..b.end], "<b>x</b>");
assert_eq!(&doc[b.start..b.inner_end], "<b>x");
let c = root.child("c").unwrap();
assert_eq!(&doc[c.start..c.end], "<c/>");
let broken = parse("<a><b>x</a>").unwrap();
let b = broken.child("b").unwrap();
assert_eq!((b.inner_end, b.end), (7, 7));
assert_eq!(broken.end, 11);
}
#[test]
fn tolerates_broken_documents() {
let root = parse("<a><b>x</c><d>y").unwrap();
+24
Переглянути файл
@@ -0,0 +1,24 @@
[INFO] --- dependency:3.8.1:tree (default-cli) @ conflict-demo ---
[INFO] demo:conflict-demo:jar:1.0-SNAPSHOT
[INFO] +- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] +- org.apache.commons:commons-text:jar:1.10.0:compile
[INFO] | \- org.apache.commons:commons-lang3:jar:3.12.0:compile
[INFO] +- org.apache.commons:commons-configuration2:jar:2.10.1:compile
[INFO] | +- (org.apache.commons:commons-lang3:jar:3.14.0:compile - omitted for conflict with 3.12.0)
[INFO] | +- (org.apache.commons:commons-text:jar:1.11.0:compile - omitted for conflict with 1.10.0)
[INFO] | \- commons-logging:commons-logging:jar:1.2:compile (version managed from 1.3.0)
[INFO] +- com.google.guava:guava:jar:32.1.3-jre:compile
[INFO] | +- com.google.guava:failureaccess:jar:1.0.1:compile
[INFO] | +- com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava:compile
[INFO] | +- com.google.code.findbugs:jsr305:jar:3.0.2:compile
[INFO] | +- org.checkerframework:checker-qual:jar:3.37.0:compile
[INFO] | +- com.google.errorprone:error_prone_annotations:jar:2.21.1:compile
[INFO] | \- com.google.j2objc:j2objc-annotations:jar:2.8:compile
[INFO] +- com.google.inject:guice:jar:5.1.0:compile
[INFO] | +- javax.inject:javax.inject:jar:1:compile
[INFO] | +- aopalliance:aopalliance:jar:1.0:compile
[INFO] | \- (com.google.guava:guava:jar:30.1-jre:compile - omitted for conflict with 32.1.3-jre)
[INFO] \- junit:junit:jar:4.13.2:test
[INFO] \- (org.hamcrest:hamcrest-core:jar:1.3:test - omitted for duplicate)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
+3 -1
Переглянути файл
@@ -5,7 +5,9 @@ use ide_core::event::ServerStatus;
use ide_core::{CancellationToken, DocId, IdeEvent, LanguageId, Pos};
use ide_jsonrpc::{Handler, Peer};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
use ide_lsp::{LaunchError, Launcher, LspManager, ProcessLauncher};
#[cfg(unix)]
use ide_lsp::{LaunchError, Launcher};
use ide_lsp::{LspManager, ProcessLauncher};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::PathBuf;
+69 -2
Переглянути файл
@@ -29,14 +29,18 @@ pub use types::*;
use ide_core::{IdeError, IdeResult};
use ide_language::LanguageConfig;
use parking_lot::{Mutex, RwLock};
use parking_lot::{Condvar, Mutex, RwLock};
use runtime::{CallEffects, CallError, PluginEngine, Registrations, Runtime, RuntimeSetup};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
const STATE_FILE: &str = "state.json";
/// Top-level files copied with a package on install besides those the manifest references.
const LICENSE_FILES: &[&str] =
&["LICENSE", "LICENSE.md", "LICENSE.txt", "NOTICE", "NOTICE.md", "NOTICE.txt", "COPYING"];
/// Dev plugins live here, relative to a project root.
pub const DEV_PLUGINS_DIR: &str = ".openidea/plugins";
@@ -52,6 +56,10 @@ struct PersistedState {
struct ThemeRef {
plugin: String,
theme: String,
/// The theme's window frame colour as the UI resolved it (`#rrggbb[aa]`), so
/// new windows open in it before the plugin is loaded.
#[serde(default, skip_serializing_if = "Option::is_none")]
frame: Option<String>,
}
struct Meta {
@@ -95,6 +103,8 @@ pub struct PluginHost {
active_files: Arc<Mutex<HashMap<String, String>>>,
/// Serializes loading / unloading so concurrent windows can't race.
lifecycle: Mutex<()>,
/// Set once the first [`load_all`](Self::load_all) has finished.
initial_load: (Mutex<bool>, Condvar),
}
impl PluginHost {
@@ -114,6 +124,7 @@ impl PluginHost {
state: Mutex::new(state),
active_files: Arc::default(),
lifecycle: Mutex::new(()),
initial_load: (Mutex::new(false), Condvar::new()),
})
}
@@ -129,9 +140,24 @@ impl PluginHost {
self.load_dir(&dir, PluginSource::Installed, None);
}
}
let (done, cv) = &self.initial_load;
*done.lock() = true;
cv.notify_all();
self.emit(None, PluginEvent::CommandsChanged);
}
/// Waits (at most `timeout`) for the first [`load_all`](Self::load_all), so a
/// listing made at startup already holds the installed plugins and the
/// selected theme. Returns whether loading has finished.
pub fn wait_initial_load(&self, timeout: Duration) -> bool {
let (done, cv) = &self.initial_load;
let mut done = done.lock();
if !*done {
cv.wait_while_for(&mut done, |d| !*d, timeout);
}
*done
}
/// Loads new dev plugins from `<root>/.openidea/plugins/` and unloads vanished ones.
pub fn sync_project(&self, root: &Path) {
let _guard = self.lifecycle.lock();
@@ -251,6 +277,11 @@ impl PluginHost {
}
std::fs::copy(src.join(file), to)?;
}
for name in LICENSE_FILES {
if src.join(name).is_file() {
std::fs::copy(src.join(name), staging.join(name))?;
}
}
if target.exists() {
std::fs::remove_dir_all(&target)?;
}
@@ -345,13 +376,45 @@ impl PluginHost {
}
}
self.state.lock().theme =
selection.map(|(plugin, theme)| ThemeRef { plugin: plugin.into(), theme: theme.into() });
selection.map(|(plugin, theme)| ThemeRef { plugin: plugin.into(), theme: theme.into(), frame: None });
self.save_state();
let active = self.active_theme();
self.emit(None, PluginEvent::ThemeChanged { theme: active.clone() });
Ok(active)
}
/// Records the selected theme's resolved window frame colour (`#rgb`,
/// `#rrggbb` or `#rrggbbaa`); ignored without a selected theme.
pub fn set_theme_frame(&self, frame: Option<&str>) -> IdeResult<()> {
if let Some(f) = frame
&& !is_hex_color(f)
{
return Err(IdeError::invalid(format!("not a hex colour: {f:?}")));
}
let changed = match self.state.lock().theme.as_mut() {
Some(t) if t.frame.as_deref() != frame => {
t.frame = frame.map(str::to_owned);
true
}
_ => false,
};
if changed {
self.save_state();
}
Ok(())
}
/// Frame colour for a new window: the recorded one of the selected theme,
/// unless its plugin is disabled. Available before plugins are loaded.
pub fn startup_frame(&self) -> Option<String> {
let state = self.state.lock();
let t = state.theme.as_ref()?;
if state.disabled.contains(&t.plugin) {
return None;
}
t.frame.clone()
}
/// The selected plugin theme, when its plugin is enabled and running.
pub fn active_theme(&self) -> Option<ActiveTheme> {
let sel = self.state.lock().theme.clone()?;
@@ -568,6 +631,10 @@ impl Drop for PluginHost {
}
}
fn is_hex_color(s: &str) -> bool {
s.strip_prefix('#').is_some_and(|h| matches!(h.len(), 3 | 6 | 8) && h.bytes().all(|b| b.is_ascii_hexdigit()))
}
/// Plugin packages found in `dirs` (first occurrence of an id wins). Invalid
/// manifests are skipped; packages with missing files carry a `problem`.
pub fn scan_catalog(dirs: &[PathBuf]) -> Vec<CatalogPlugin> {
+87 -12
Переглянути файл
@@ -22,6 +22,33 @@ fn sample(name: &str) -> PathBuf {
repo().join("plugins").join(name)
}
fn theme_template() -> PathBuf {
repo().join("templates/theme-plugin")
}
/// A theme package with a light and a dark theme, plus licence files, in `dir`.
fn write_theme_pair(dir: &Path) {
std::fs::create_dir_all(dir.join("t")).unwrap();
std::fs::write(
dir.join("plugin.toml"),
"id = \"theme-pair\"\nname = \"Pair\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\n\
[[contributes.themes]]\npath = \"t/day.json\"\n[[contributes.themes]]\npath = \"t/night.json\"\n",
)
.unwrap();
std::fs::write(
dir.join("t/day.json"),
r##"{"id":"day","name":"Day","kind":"light","tokens":{"--bg-frame":"#eeeeee"}}"##,
)
.unwrap();
std::fs::write(
dir.join("t/night.json"),
r##"{"id":"night","name":"Night","kind":"dark","tokens":{"--bg-frame":"#111111"}}"##,
)
.unwrap();
std::fs::write(dir.join("LICENSE"), "MIT License\n").unwrap();
std::fs::write(dir.join("NOTICE"), "Palette notice\n").unwrap();
}
fn misbehave_pkg() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/misbehave")
}
@@ -217,10 +244,11 @@ fn runtime_language_and_theme_registration() {
#[test]
fn contribution_only_plugins() {
let f = fixture(Limits::default());
let theme = f.host.install_from_dir(&sample("theme-solarized-dark")).unwrap();
let theme = f.host.install_from_dir(&theme_template()).unwrap();
assert_eq!(theme.status, PluginStatus::Static);
assert!(!theme.has_code);
assert_eq!(theme.themes[0].id, "solarized-dark");
let ids: Vec<&str> = theme.themes.iter().map(|t| t.id.as_str()).collect();
assert_eq!(ids, ["harbor-night"]);
let lang = f.host.install_from_dir(&sample("language-toy")).unwrap();
assert_eq!(lang.status, PluginStatus::Static);
assert_eq!(lang.languages[0].id, "toy");
@@ -228,13 +256,14 @@ fn contribution_only_plugins() {
assert!(f.run("language-toy", "x", None).unwrap_err().contains("no code"));
f.take_events();
let active = f.host.set_theme(Some(("theme-solarized-dark", "solarized-dark"))).unwrap().unwrap();
assert_eq!(active.theme.tokens["--bg-app"], "#002b36");
let active = f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap().unwrap();
assert_eq!(active.theme.tokens["--bg-app"], "#14171c");
assert_eq!(active.theme.tokens["--syn-string"], "#9ccc7a");
assert!(f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::ThemeChanged { theme: Some(_) })));
assert_eq!(f.host.list(None).active_theme, Some(active));
// Disabling the plugin withdraws its theme and language.
f.host.set_enabled("theme-solarized-dark", false).unwrap();
f.host.set_enabled("theme-harbor-night", false).unwrap();
assert!(f.host.active_theme().is_none());
assert!(f.take_events().iter().any(|(_, e)| *e == PluginEvent::ThemeChanged { theme: None }));
f.host.set_enabled("language-toy", false).unwrap();
@@ -245,7 +274,7 @@ fn contribution_only_plugins() {
#[test]
fn theme_template_installs_with_its_editor_scheme() {
let f = fixture(Limits::default());
let info = f.host.install_from_dir(&repo().join("templates/theme-plugin")).unwrap();
let info = f.host.install_from_dir(&theme_template()).unwrap();
assert_eq!(info.status, PluginStatus::Static);
assert!(!info.has_code);
assert_eq!(info.themes[0].id, "harbor-night");
@@ -260,6 +289,47 @@ fn theme_template_installs_with_its_editor_scheme() {
assert!(tokens.len() > 150);
}
#[test]
fn theme_packages_install_with_their_licence() {
let f = fixture(Limits::default());
let dir = tempfile::tempdir().unwrap();
write_theme_pair(dir.path());
let info = f.host.install_from_dir(dir.path()).unwrap();
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
let installed = f.plugins_dir.join("theme-pair");
assert!(std::fs::read_to_string(installed.join("LICENSE")).unwrap().contains("MIT License"));
assert!(installed.join("NOTICE").is_file());
for (theme, kind) in [("day", ThemeKind::Light), ("night", ThemeKind::Dark)] {
let active = f.host.set_theme(Some(("theme-pair", theme))).unwrap().unwrap();
assert_eq!(active.theme.kind, kind);
}
}
#[test]
fn theme_frame_follows_the_selection() {
let f = fixture(Limits::default());
let dir = tempfile::tempdir().unwrap();
write_theme_pair(dir.path());
f.host.install_from_dir(dir.path()).unwrap();
// Nothing to attach it to without a selected theme.
f.host.set_theme_frame(Some("#111111")).unwrap();
assert_eq!(f.host.startup_frame(), None);
f.host.set_theme(Some(("theme-pair", "night"))).unwrap();
assert!(f.host.set_theme_frame(Some("hsl(220, 13%, 15%)")).is_err());
f.host.set_theme_frame(Some("#111111")).unwrap();
assert_eq!(f.host.startup_frame().as_deref(), Some("#111111"));
f.host.set_enabled("theme-pair", false).unwrap();
assert_eq!(f.host.startup_frame(), None);
f.host.set_enabled("theme-pair", true).unwrap();
assert_eq!(f.host.startup_frame().as_deref(), Some("#111111"));
// A new selection drops the old theme's colour until the UI reports the new one.
f.host.set_theme(Some(("theme-pair", "day"))).unwrap();
assert_eq!(f.host.startup_frame(), None);
f.host.set_theme_frame(Some("#eeeeee")).unwrap();
f.host.set_theme(None).unwrap();
assert_eq!(f.host.startup_frame(), None);
}
#[test]
fn theme_with_broken_editor_scheme_fails_to_load() {
let f = fixture(Limits::default());
@@ -282,17 +352,22 @@ fn theme_with_broken_editor_scheme_fails_to_load() {
fn state_persists_across_restarts() {
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("hello")).unwrap();
f.host.install_from_dir(&sample("theme-solarized-dark")).unwrap();
f.host.install_from_dir(&theme_template()).unwrap();
f.host.set_enabled("hello", false).unwrap();
f.host.set_theme(Some(("theme-solarized-dark", "solarized-dark"))).unwrap();
f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap();
f.host.set_theme_frame(Some("#1f252e")).unwrap();
let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap();
// Known before the plugins are loaded: new windows open in the theme's frame colour.
assert_eq!(again.startup_frame().as_deref(), Some("#1f252e"));
assert!(!again.wait_initial_load(Duration::from_millis(1)));
again.load_all();
assert!(again.wait_initial_load(Duration::ZERO));
let list = again.list(None);
let hello = list.plugins.iter().find(|p| p.id == "hello").unwrap();
assert!(!hello.enabled);
assert_eq!(hello.status, PluginStatus::Disabled);
assert_eq!(list.active_theme.unwrap().theme.id, "solarized-dark");
assert_eq!(list.active_theme.unwrap().theme.id, "harbor-night");
assert!(
again
.run_command("hello", "insert-date", None, Invocation::default())
@@ -386,15 +461,15 @@ fn catalog_lists_sample_packages() {
std::fs::create_dir_all(tmp.path().join("junk")).unwrap();
std::fs::write(tmp.path().join("junk/plugin.toml"), "garbage = ").unwrap();
let catalog = scan_catalog(&[repo().join("plugins"), tmp.path().to_path_buf()]);
let catalog = scan_catalog(&[repo().join("plugins"), repo().join("templates"), tmp.path().to_path_buf()]);
let ids: Vec<&str> = catalog.iter().map(|c| c.id.as_str()).collect();
for id in ["hello", "theme-solarized-dark", "language-toy", "x"] {
for id in ["hello", "theme-harbor-night", "language-toy", "x"] {
assert!(ids.contains(&id), "{id} missing from {ids:?}");
}
let hello = catalog.iter().find(|c| c.id == "hello").unwrap();
assert!(hello.has_code && hello.problem.is_none() && hello.change_notes.is_some());
assert_eq!(hello.commands.len(), 2);
let theme = catalog.iter().find(|c| c.id == "theme-solarized-dark").unwrap();
let theme = catalog.iter().find(|c| c.id == "theme-harbor-night").unwrap();
assert_eq!((theme.theme_count, theme.has_code), (1, false));
let x = catalog.iter().find(|c| c.id == "x").unwrap();
assert!(x.problem.as_deref().unwrap().contains("plugin.wasm"));
Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 169 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 133 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 171 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 135 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 164 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 129 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 168 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 131 KiB

+3 -2
Переглянути файл
@@ -1,7 +1,8 @@
# Theme plugins
OpenIDEA ships three built-in themes (Islands Light, Islands Dark, High
Contrast). Everything else comes from **theme plugins**, the same model as
OpenIDEA ships seven [built-in themes](../themes.md): Islands Light, Islands Dark,
High Contrast, Solarized Light, Solarized Dark, One Light and One Dark. Additional
themes come from **theme plugins**, the same model as
IntelliJ IDEA, where most themes are plugins rather than part of the IDE.
A theme plugin is data only. Like an IntelliJ theme (a `.theme.json` plus an
+100
Переглянути файл
@@ -0,0 +1,100 @@
# Built-in theme sources
OpenIDEA includes Islands Light, Islands Dark, High Contrast, Solarized Light,
Solarized Dark, One Light and One Dark. Select them in Settings › Appearance,
Welcome › Customize or the existing quick theme menu. The same themes are
available as explicit editor schemes; “Theme default” follows the UI theme.
“Sync with OS” uses the existing preferred light/dark theme settings. Existing
ids (`light`, `dark`, `dark-hc`, `system`) and attribute overrides remain valid.
## Upstream palettes and licenses
All sources below are the original authors’ repositories, pinned for reproducibility.
Full MIT notices are preserved in [THIRD_PARTY_LICENSES.md](../THIRD_PARTY_LICENSES.md).
| Theme | Original source revision | Palette / mapping source |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Solarized Light / Dark | [Ethan Schoonover, 62f656a](https://github.com/altercation/solarized/tree/62f656a02f93c5190a8753159e34b385588d5ff3) | README’s sixteen exact sRGB hex colours; `vim-colors-solarized/colors/solarized.vim` semantic roles; iTerm2 ANSI slots |
| One Light syntax | [GitHub / Atom, d845790](https://github.com/atom/one-light-syntax/tree/d84579027410c576086dfca14d934c4bd74b0438) | `styles/colors.less`, `styles/syntax-variables.less` |
| One Dark syntax | [GitHub / Atom, 9c96f44](https://github.com/atom/one-dark-syntax/tree/9c96f4454362267ac45322063e193ccf9d2debb1) | `styles/colors.less`, `styles/syntax-variables.less` |
| One Light UI | [GitHub / Atom, a27bce3](https://github.com/atom/one-light-ui/tree/a27bce35088ecd323e44f5c2510bcf2d4e9efcf8) | `styles/ui-variables.less`, `styles/ui-variables-custom.less` |
| One Dark UI | [GitHub / Atom, 18c2143](https://github.com/atom/one-dark-ui/tree/18c2143d41e17b337fff6dc7024562c4d999be17) | `styles/ui-variables.less`, `styles/ui-variables-custom.less` |
## Mapping into OpenIDEA
`src/platform/themes.ts` registers the stable ids. `data-theme` retains the
light/dark kind for icons, native controls and existing selectors;
`data-color-theme` selects the additional palette. High Contrast continues to
use `data-contrast="high"`. Plugin themes clear the built-in palette attribute
and retain their existing light/dark fallback; removing a plugin restores the
chosen built-in palette.
`src/styles/tokens.css` contains the shared mapping for all colour tokens and
four palette blocks. No new dependency is required. Solarized uses base3/base2
for light backgrounds and base03/base02 for dark backgrounds, base00/base0 for
text, and the original eight accents. Vim’s statements are green, constants
and strings cyan, identifiers blue, types yellow, and comments the original
subdued base1/base01. Solarized’s original ANSI slot order is preserved (the
bright slots intentionally include orange, violet and neutrals).
One retains the exact HSL definitions from Atom, avoiding rounded palette
approximations: 230° / 1% / 98% light and 220° / 13% / 18% dark editor backgrounds;
purple keywords, green strings, blue functions, red variables/tags, orange
numbers and attributes, yellow classes, and the original mono-3 comments.
UI frame/popup levels use Atom’s relative background lightness formulas with
the matching syntax theme. OpenIDEA’s shared UI text uses the syntax foreground
and mono-2 for readable secondary labels. Selection and cursor-line values
follow Atom’s syntax variables. Atom does not define a terminal ANSI palette:
One’s ANSI slots reuse its exact semantic syntax hues, repeating them for bright
colours rather than inventing a different palette. One Light maps ANSI white
and bright white to its mono-2 and mono-1 text colours so they remain visible
on the light terminal background.
Components without an upstream equivalent (feedback banners, tool window states,
search fills and focus decoration) use the original semantic hues, neutrals,
or explicit `color-mix()` tints. This adapts colours to the existing layout;
it does not recreate Atom’s or Vim’s UI. Platform traffic-light colours stay
platform colours. Original subdued comments and some syntax accents have lower
contrast than a high-contrast accessibility theme; High Contrast remains available.
Native windows open in the theme's frame colour before their page loads:
`src-tauri/src/theme_frame.rs` reads `--bg-frame` of each built-in theme from
`tokens.css` itself (resolving `var()` and `hsl()`), so there is no second
colour table to keep in sync. Elsewhere the frontend resolves HSL and
`color-mix()` tokens to RGB (`src/platform/cssColor.ts`) for Tauri's window
API, the native Settings window, Mermaid and the terminal.
`public/boot.js` restores the palette (`data-color-theme`) and the splash's
resolved frame, text and accent colours before the application stylesheet
loads, so a restart in One Dark or Solarized shows no flash of another theme.
The backend's settings persistence remains authoritative. Terminal, Mermaid
and editor-scheme observers also watch palette changes within the same
light/dark kind. Custom accents, explicit editor schemes, per-scheme attribute
overrides, compact mode and accessibility options retain their precedence.
`src/features/settings/__tests__/contrast.test.ts` requires every palette theme
to define every colour token of the base themes (in the shared mapping or its
own block), so a token added to `tokens.css` later can't silently fall back to
an Islands colour.
## Browser evidence
These approved screenshots are reused from the original theme implementation on
0.1.15; regression checks are rerun against the upstream contribution base.
Captured at 1400 × 900 in Linux Chromium 154 using OpenIDEA's public in-memory
`acme-api` project / Kotlin fixture and synthetic ANSI terminal output. The
terminal is a real xterm renderer, without a native PTY or shell. These images
cover the shell, sidebar, editor, gutter, find matches, terminal, Settings,
focused controls, disabled settings and the selected theme popup.
| Theme | Workbench, editor and terminal | Settings and theme popup |
|---|---|---|
| Solarized Light | [Screenshot](media/themes/solarized-light-workbench.png) | [Screenshot](media/themes/solarized-light-popup.png) |
| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
The browser regression also checks refresh / startup cache restoration,
selection visibility, same-kind switches, the quick menu, existing themes,
explicit editor schemes and preferred OS themes. Native startup colours are
covered by Rust unit tests.
+188
Переглянути файл
@@ -0,0 +1,188 @@
import { expect, openFromTree, test } from "./fixtures";
import type { Page } from "@playwright/test";
test.setTimeout(60_000);
const palettes = [
{
id: "solarized-light",
label: "Solarized Light",
kind: "light",
bg: "rgb(253, 246, 227)",
fg: "rgb(101, 123, 131)",
frame: [238, 232, 213, 255],
},
{
id: "solarized-dark",
label: "Solarized Dark",
kind: "dark",
bg: "rgb(0, 43, 54)",
fg: "rgb(131, 148, 150)",
frame: [7, 54, 66, 255],
},
{
id: "one-light",
label: "One Light",
kind: "light",
bg: "rgb(250, 250, 250)",
fg: "rgb(56, 58, 66)",
frame: [234, 234, 235, 255],
},
{
id: "one-dark",
label: "One Dark",
kind: "dark",
bg: "rgb(40, 44, 52)",
fg: "rgb(171, 178, 191)",
frame: [33, 37, 43, 255],
},
];
async function choose(page: Page, control: string, label: string) {
await page.getByRole("button", { name: control, exact: true }).click();
await page.getByRole("option", { name: label, exact: true }).click();
}
async function settings(page: Page) {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await dialog
.locator('[role="treeitem"][aria-level="2"]')
.filter({ hasText: /^Appearance$/ })
.click();
return dialog;
}
for (const palette of palettes) {
test(`${palette.label}: settings, editor, terminal, popup and reload`, async ({ workbench: page }, info) => {
const editor = await openFromTree(page, "build.gradle.kts");
await page.keyboard.press("Alt+F12");
await expect(page.locator(".xterm")).toBeVisible();
// Use only synthetic ANSI output; no shell, network or native PTY is involved.
await page.evaluate(async () => {
const path = "/src/features/terminal/store.ts";
const { activeSession } = await import(/* @vite-ignore */ path);
const session = activeSession();
session.term.clear();
session.term.writeln("Synthetic theme regression — no PTY");
session.term.writeln("\x1b[31merror\x1b[0m \x1b[33mwarning\x1b[0m \x1b[32msuccess\x1b[0m \x1b[34minfo\x1b[0m");
});
const dialog = await settings(page);
await choose(page, "Theme", palette.label);
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-color-theme", palette.id);
await expect(page.locator("html")).toHaveAttribute("data-theme", palette.kind);
expect(
await page.evaluate(async () => {
const path = "/src/workbench/theme.ts";
const { windowBackgroundColor, windowBackgroundHex } = await import(/* @vite-ignore */ path);
return { rgba: windowBackgroundColor(), hex: windowBackgroundHex() };
}),
).toEqual({
rgba: palette.frame,
hex:
"#" +
palette.frame
.slice(0, 3)
.map((n) => n.toString(16).padStart(2, "0"))
.join(""),
});
await page.screenshot({ path: info.outputPath(`${palette.id}-settings.png`), animations: "disabled" });
await page.keyboard.press("Escape");
await expect(editor).toHaveCSS("background-color", palette.bg);
await expect(editor).toHaveCSS("color", palette.fg);
await expect(editor.locator(".cm-gutters")).toHaveCSS("background-color", palette.bg);
await expect
.poll(() =>
page.evaluate(async () => {
const path = "/src/features/terminal/store.ts";
const { activeSession } = await import(/* @vite-ignore */ path);
return activeSession().term.options.theme.background;
}),
)
.toBe(
palette.id === "solarized-light"
? "#fdf6e3"
: palette.id === "solarized-dark"
? "#002b36"
: palette.id === "one-light"
? "#fafafa"
: "#282c34",
);
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+a");
await expect(editor.locator(".cm-selectionBackground").first()).toBeVisible();
await page.keyboard.press("ArrowRight");
await page.keyboard.press("Meta+f");
await page.getByRole("textbox", { name: "Find", exact: true }).fill("Order");
await expect(editor.locator(".cm-openidea-findMatch").first()).toBeVisible();
await page.screenshot({ path: info.outputPath(`${palette.id}-workbench.png`), animations: "disabled" });
await page.keyboard.press("Escape");
await settings(page);
await page.getByRole("button", { name: "Theme", exact: true }).click();
await expect(page.getByRole("listbox", { name: "Theme", exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath(`${palette.id}-popup.png`), animations: "disabled" });
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await page.reload();
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await expect(page.locator("html")).toHaveAttribute("data-color-theme", palette.id);
const cached = await page.evaluate(() => JSON.parse(localStorage.getItem("openidea.theme")!));
expect(cached).toMatchObject({ theme: palette.kind, colorTheme: palette.id });
});
}
test("same-kind switching, legacy themes, system mode and explicit editor schemes", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
const dialog = await settings(page);
for (const label of [
"Solarized Light",
"One Light",
"Solarized Dark",
"One Dark",
"Islands Light",
"Islands Dark",
"High Contrast",
]) {
await choose(page, "Theme", label);
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
if (label === "High Contrast") await expect(page.locator("html")).toHaveAttribute("data-contrast", "high");
else await expect(page.locator("html")).not.toHaveAttribute("data-contrast");
const added = palettes.find((p) => p.label === label);
if (added) await expect(page.locator("html")).toHaveAttribute("data-color-theme", added.id);
else await expect(page.locator("html")).not.toHaveAttribute("data-color-theme");
const bg =
added?.bg ??
(label === "Islands Light"
? "rgb(255, 255, 255)"
: label === "Islands Dark"
? "rgb(25, 26, 28)"
: "rgb(0, 0, 0)");
await expect(page.locator(".cm-editor").first()).toHaveCSS("background-color", bg);
}
await choose(page, "Theme", "One Light");
await choose(page, "Editor color scheme", "Solarized Dark");
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(page.locator(".cm-editor").first()).toHaveCSS("background-color", "rgb(0, 43, 54)");
await choose(page, "Editor color scheme", "Theme default");
await dialog.getByLabel("Sync with OS", { exact: true }).check();
await dialog.getByRole("button", { name: "Preferred themes", exact: true }).click();
await choose(page, "Preferred light theme", "Solarized Light");
await choose(page, "Preferred dark theme", "One Dark");
await page.keyboard.press("Escape");
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await page.emulateMedia({ colorScheme: "light" });
await expect(page.locator("html")).toHaveAttribute("data-color-theme", "solarized-light");
await page.emulateMedia({ colorScheme: "dark" });
await expect(page.locator("html")).toHaveAttribute("data-color-theme", "one-dark");
});
test("quick theme menu offers all four palettes and applies their kind", async ({ workbench: page }) => {
for (const palette of palettes) {
await page.getByRole("button", { name: "IDE and Project Settings", exact: true }).click();
await page.getByText("Theme", { exact: true }).click();
await page.getByText(palette.label, { exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-color-theme", palette.id);
await expect(page.locator("html")).toHaveAttribute("data-theme", palette.kind);
}
});
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.16",
"version": "0.1.17",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+3 -4
Переглянути файл
@@ -11,7 +11,6 @@ code at all.
plugins/
├─ build.sh # builds Rust plugins into components
├─ hello/ # Rust plugin: two commands
├─ theme-solarized-dark/ # manifest-only: a theme
└─ language-toy/ # manifest-only: a language definition
```
@@ -170,10 +169,10 @@ never affected.
```json
{
"id": "solarized-dark",
"name": "Solarized Dark",
"id": "harbor-night",
"name": "Harbor Night",
"kind": "dark",
"tokens": { "--bg-app": "#002b36", "--accent": "#268bd2", "--syn-keyword": "#859900" }
"tokens": { "--bg-app": "#14171c", "--accent": "#2b9e93", "--syn-keyword": "#e0a46e" }
}
```
-11
Переглянути файл
@@ -1,11 +0,0 @@
# Contribution-only plugin: no code, just a theme file.
id = "theme-solarized-dark"
name = "Solarized Dark Theme"
version = "1.0.0"
description = "Ethan Schoonover's Solarized palette, dark variant."
authors = ["OpenIDEA contributors"]
change-notes = "1.0.0 — Solarized Dark UI and syntax colours."
openidea-api = "0.1"
[[contributes.themes]]
path = "themes/solarized-dark.json"
-64
Переглянути файл
@@ -1,64 +0,0 @@
{
"id": "solarized-dark",
"name": "Solarized Dark",
"kind": "dark",
"tokens": {
"--bg-app": "#002b36",
"--bg-elev": "#03313c",
"--bg-popup": "#073642",
"--bg-hover": "#0a3d4a",
"--bg-selected": "#0d4554",
"--bg-selected-strong": "#104d5d",
"--bg-current-line": "#04323d",
"--bg-debug-line": "#0b3a50",
"--bg-backdrop": "#00212a",
"--bg-tooltip": "#073642",
"--bg-control": "#073642",
"--bg-control-hover": "#0a3d4a",
"--bg-active": "#104d5d",
"--border": "#06323d",
"--border-popup": "#0a3d4a",
"--border-strong": "#124b59",
"--border-window": "#0a3d4a",
"--control-off": "#2c5662",
"--fg-strong": "#eee8d5",
"--fg-emphasis": "#d9d4c1",
"--fg": "#93a1a1",
"--fg-secondary": "#839496",
"--fg-muted": "#839496",
"--fg-subtle": "#657b83",
"--fg-faint": "#586e75",
"--fg-gutter": "#4c636b",
"--fg-tooltip": "#eee8d5",
"--fg-on-accent": "#002b36",
"--accent": "#268bd2",
"--link": "#268bd2",
"--link-hover": "#5fa9e0",
"--danger": "#dc322f",
"--warning": "#b58900",
"--success": "#859900",
"--info": "#268bd2",
"--vcs-modified": "#b58900",
"--vcs-added": "#859900",
"--vcs-deleted": "#657b83",
"--vcs-untracked": "#cb4b16",
"--vcs-ignored": "#586e75",
"--vcs-conflict": "#d33682",
"--gutter-modified": "#268bd2",
"--gutter-added": "#859900",
"--gutter-deleted": "#dc322f",
"--syn-keyword": "#859900",
"--syn-string": "#2aa198",
"--syn-type": "#b58900",
"--syn-function": "#268bd2",
"--syn-comment": "#586e75",
"--syn-annotation": "#6c71c4",
"--syn-number": "#d33682",
"--syn-punct": "#839496",
"--syn-variable": "#93a1a1",
"--syn-property": "#93a1a1",
"--syn-constant": "#cb4b16",
"--syn-invalid": "#dc322f",
"--syn-inline-value": "#657b83"
}
}
+29 -2
Переглянути файл
@@ -3,9 +3,36 @@
// so a new window starts in it instead of flashing the light default.
// An external file because the CSP forbids inline scripts.
try {
const root = document.documentElement;
const addStyle = (id, css) => {
const style = document.createElement("style");
style.id = id;
style.textContent = css;
document.head.appendChild(style);
};
const last = JSON.parse(localStorage.getItem("openidea.theme") ?? "null");
if (last?.theme) document.documentElement.dataset.theme = last.theme;
if (last?.contrast) document.documentElement.dataset.contrast = last.contrast;
if (last?.theme) root.dataset.theme = last.theme;
if (last?.contrast) root.dataset.contrast = last.contrast;
// A built-in palette theme (Solarized, One) over its light / dark base (tokens.css).
if (typeof last?.colorTheme === "string" && /^[a-z][a-z0-9-]*$/.test(last.colorTheme))
root.dataset.colorTheme = last.colorTheme;
// A plugin theme's stylesheet (plugins/bridge.ts), so the workbench doesn't
// show the built-in theme until the plugin host answers.
const plugin = JSON.parse(localStorage.getItem("openidea.pluginTheme") ?? "null");
if (typeof plugin?.id === "string" && typeof plugin.css === "string" && !/[<\\]|url\(/i.test(plugin.css)) {
addStyle("openidea-plugin-theme", plugin.css);
root.dataset.pluginTheme = plugin.id;
root.dataset.pluginThemeKind = root.dataset.theme = plugin.kind === "light" ? "light" : "dark";
delete root.dataset.contrast;
delete root.dataset.colorTheme;
}
// The splash's frame, text and accent colours, resolved by theme.ts (splash.css).
const colors = [
["--boot-frame", last?.frame],
["--boot-fg", last?.fg],
["--boot-accent", last?.accent],
].filter(([, v]) => typeof v === "string" && /^#[0-9a-f]{3,8}$/i.test(v));
if (colors.length) addStyle("openidea-boot-colors", `:root { ${colors.map(([k, v]) => `${k}: ${v};`).join(" ")} }`);
} catch {
/* storage unavailable */
}
+10 -7
Переглянути файл
@@ -1,11 +1,14 @@
/* Linked, not inlined in index.html: release builds hash inline <style> blocks into the CSP,
which voids style-src 'unsafe-inline' and blocks the editor's runtime-injected styles. */
/* Start-up splash over the page until the window's launch project is open (platform/splash.ts).
Tokens aren't loaded yet, so the colours mirror --bg-frame / --fg-muted / --accent. */
Until tokens load, the colours are the last theme's --bg-frame / --fg-muted / --accent that
boot.js restored as --boot-*, else these built-in ones. */
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
body, .splash { background: #e9eaee; }
:root[data-theme="dark"] :is(body, .splash) { background: #26282c; }
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) { background: #1a1b1e; }
body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
:root[data-theme="dark"] :is(body, .splash) { background: var(--bg-frame, var(--boot-frame, #26282c)); }
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) {
background: var(--bg-frame, var(--boot-frame, #1a1b1e));
}
.splash {
position: fixed;
inset: 0;
@@ -17,7 +20,7 @@ body, .splash { background: #e9eaee; }
gap: 14px;
padding-bottom: 38px;
box-sizing: border-box;
color: #6c707e;
color: var(--fg-muted, var(--boot-fg, #6c707e));
-webkit-user-select: none;
user-select: none;
cursor: default;
@@ -25,7 +28,7 @@ body, .splash { background: #e9eaee; }
transition: opacity 160ms ease-out;
}
.splash.splash-out { opacity: 0; pointer-events: none; }
:root[data-theme^="dark"] .splash { color: #8c8f95; }
:root[data-theme^="dark"] .splash { color: var(--fg-muted, var(--boot-fg, #8c8f95)); }
.splash-logo { width: 56px; height: 56px; }
/* 15px Inter: 2048 units per em, the line box from ascender to descender. */
.splash-wordmark { width: 73.2px; height: 18.15px; }
@@ -34,7 +37,7 @@ body, .splash { background: #e9eaee; }
.splash-bar > i {
display: block;
height: 100%;
background: #3871e1;
background: var(--accent, var(--boot-accent, #3871e1));
transform-origin: left;
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
}
+71 -2
Переглянути файл
@@ -1,11 +1,12 @@
//! Maven / Gradle tool windows (the build model and its background sync) and
//! Build › Build Project (compiling with the project's build system).
use crate::state::AppState;
use crate::state::{AppState, apply_workspace_edit};
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{IdeError, IdeEvent, IdeResult, RequestId};
use ide_core::{FileEdit, IdeError, IdeEvent, IdeResult, Location, Range, RequestId, WorkspaceEdit};
use std::collections::BTreeMap;
use std::path::Path;
use tauri::ipc::Channel;
@@ -126,6 +127,74 @@ pub async fn build_sync(
result?
}
/// The POM declaring `dependency` for the Maven module `pom` (project-relative): the
/// module's own, else its nearest parent in the project; its path, text and declaration.
fn declaring_pom(
project: &crate::state::Project,
pom: &str,
dependency: &ArtifactKey,
) -> IdeResult<(std::path::PathBuf, String, Range)> {
let model = ide_build::maven::load(&project.root);
for rel in ide_build::pom_edit::declaring_poms(&model, pom) {
let path = project.root.join(&rel);
let text = project.text_of(&path)?;
if let Some(range) = ide_build::pom_edit::declaration(&text, dependency) {
return Ok((path, text, range));
}
}
Err(IdeError::not_found(format!(
"{dependency} is not declared in a pom.xml of this project (it may come from an imported BOM or an external parent POM)"
)))
}
/// Where the direct dependency `dependency` of the Maven module `pom` is declared.
#[tauri::command]
#[specta::specta]
pub async fn maven_dependency_declaration(
window: Window,
state: State<'_, AppState>,
pom: String,
dependency: ArtifactKey,
) -> IdeResult<Location> {
let project = state.project(window.label())?;
tauri::async_runtime::spawn_blocking(move || {
let (path, _, range) = declaring_pom(&project, &pom, &dependency)?;
Ok(Location::file(path, range))
})
.await
.map_err(join_err)?
}
/// Adds an `<exclusion>` of `exclusion` to the declaration of the direct dependency
/// `dependency` of the Maven module `pom`, through the open document when there is one
/// (saved). Returns the declaration; nothing changes when it already excludes it.
#[tauri::command]
#[specta::specta]
pub async fn maven_exclude_dependency(
window: Window,
state: State<'_, AppState>,
pom: String,
dependency: ArtifactKey,
exclusion: ArtifactKey,
) -> IdeResult<Location> {
let project = state.project(window.label())?;
tauri::async_runtime::spawn_blocking(move || {
let (path, text, range) = declaring_pom(&project, &pom, &dependency)?;
match ide_build::pom_edit::add_exclusion(&text, &dependency, &exclusion) {
Some(Exclusion::Edit(edit)) => {
let edit =
WorkspaceEdit { files: vec![FileEdit::Edit { path: path.clone().into(), edits: vec![edit] }] };
apply_workspace_edit(&project.documents, &edit)?;
}
Some(Exclusion::Present) => {}
None => return Err(IdeError::not_found(format!("{dependency} is not declared in {}", path.display()))),
}
Ok(Location::file(path, range))
})
.await
.map_err(join_err)?
}
/// Build › Build Project / Rebuild Project / Build Module (`file`: a file or folder of the
/// module) / Build Artifacts, streaming the console and messages on `on_event`; cancellable
/// with `cancel_request(request)`. Diagnostics of `clear` (the files of the previous build)
+3
Переглянути файл
@@ -246,6 +246,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
run::run_test_reports,
build::build_model,
build::build_sync,
build::maven_dependency_declaration,
build::maven_exclude_dependency,
build::build_run,
java::java_resolve_launch,
java::java_debug_server,
@@ -330,6 +332,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
plugin::plugin_run_command,
plugin::plugin_set_active_file,
plugin::plugin_set_theme,
plugin::plugin_set_theme_frame,
perf::app_metrics,
perf::clear_caches,
analysis::inspect_code,
+14
Переглянути файл
@@ -11,9 +11,13 @@ use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use tauri::ipc::Channel;
use tauri::{AppHandle, Manager, State, Window};
/// How long `plugin_list` waits for the startup load before answering with what it has.
const INITIAL_LOAD_WAIT: Duration = Duration::from_secs(5);
/// Window label → its event channel.
static SUBSCRIBERS: LazyLock<Mutex<HashMap<String, Channel<PluginEvent>>>> = LazyLock::new(Default::default);
@@ -62,6 +66,8 @@ pub async fn plugin_list(window: Window, state: State<'_, AppState>) -> IdeResul
let host = state.plugins.clone();
let root = state.project(window.label()).ok().map(|p| p.root.clone());
blocking(move || {
// A window opened at startup would otherwise see no plugins and drop the selected theme.
host.wait_initial_load(INITIAL_LOAD_WAIT);
if let Some(root) = &root {
host.sync_project(root);
}
@@ -156,3 +162,11 @@ pub fn plugin_set_theme(
_ => state.plugins.set_theme(None),
}
}
/// The UI reports the selected plugin theme's resolved frame colour (`#rrggbb[aa]`),
/// which new windows open in before their page loads.
#[tauri::command]
#[specta::specta]
pub fn plugin_set_theme_frame(state: State<'_, AppState>, color: Option<String>) -> IdeResult<()> {
state.plugins.set_theme_frame(color.as_deref())
}
+1
Переглянути файл
@@ -9,6 +9,7 @@ mod logging;
mod menu;
mod shell_env;
mod state;
mod theme_frame;
mod windows;
use state::AppState;
+159
Переглянути файл
@@ -0,0 +1,159 @@
//! Built-in themes' window frame colour (`--bg-frame`), read from the UI's own
//! `src/styles/tokens.css` so a native window opens in the colour its page paints.
use std::collections::HashMap;
use std::sync::LazyLock;
use tauri::utils::config::Color;
const TOKENS_CSS: &str = include_str!("../../src/styles/tokens.css");
/// A top-level rule: its selector list and custom-property declarations.
type Block = (Vec<String>, HashMap<String, String>);
/// The rule blocks of tokens.css, in source order.
static BLOCKS: LazyLock<Vec<Block>> = LazyLock::new(|| blocks(TOKENS_CSS));
/// `--bg-frame` of built-in theme `id` (`light`, `dark`, `dark-hc` or a palette
/// theme with a `:root[data-color-theme="<id>"]` block); `None` for any other id.
pub fn builtin_frame(id: &str) -> Option<Color> {
builtin_frame_in(&BLOCKS, id)
}
fn builtin_frame_in(blocks: &[Block], id: &str) -> Option<Color> {
let palette = format!(":root[data-color-theme=\"{id}\"]");
let mut selectors = vec![":root".to_owned()];
match id {
"dark" => {}
"light" => selectors.push(":root[data-theme=\"light\"]".into()),
"dark-hc" => selectors.push(":root[data-theme=\"dark-hc\"]".into()),
_ if blocks.iter().any(|(sel, _)| sel.contains(&palette)) => {
if id.ends_with("light") {
selectors.push(":root[data-theme=\"light\"]".into());
}
selectors.push(":root[data-color-theme]".into());
selectors.push(palette);
}
_ => return None,
}
// Later matching blocks win, as in the page (the selectors involved share a specificity order).
let mut vars: HashMap<&str, &str> = HashMap::new();
for (sel, decls) in blocks {
if sel.iter().any(|s| selectors.contains(s)) {
vars.extend(decls.iter().map(|(k, v)| (k.as_str(), v.as_str())));
}
}
let mut value = *vars.get("--bg-frame")?;
for _ in 0..8 {
match value.strip_prefix("var(").and_then(|v| v.strip_suffix(')')) {
Some(name) => value = vars.get(name.split(',').next()?.trim())?,
None => return parse_color(value),
}
}
None
}
fn blocks(css: &str) -> Vec<Block> {
let mut text = String::with_capacity(css.len());
let mut rest = css;
while let Some(start) = rest.find("/*") {
text.push_str(&rest[..start]);
rest = rest[start + 2..].find("*/").map_or("", |end| &rest[start + 2 + end + 2..]);
}
text.push_str(rest);
let mut out = Vec::new();
let mut rest = text.as_str();
while let Some(open) = rest.find('{') {
let selector = rest[..open].trim();
// Matching close brace (nested at-rule blocks are skipped whole).
let mut depth = 0;
let Some(close) = rest[open..].char_indices().find_map(|(i, c)| {
match c {
'{' => depth += 1,
'}' => depth -= 1,
_ => {}
}
(depth == 0).then_some(open + i)
}) else {
break;
};
if !selector.starts_with('@') {
let decls = rest[open + 1..close]
.split(';')
.filter_map(|d| d.split_once(':'))
.filter(|(k, _)| k.trim().starts_with("--"))
.map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))
.collect();
out.push((selector.split(',').map(|s| s.trim().to_owned()).collect(), decls));
}
rest = &rest[close + 1..];
}
out
}
/// `#hex` or `hsl(h, s%, l%)`, rounded to 8-bit channels as browsers do.
fn parse_color(value: &str) -> Option<Color> {
if value.starts_with('#') {
return serde_json::from_value(serde_json::Value::String(value.to_owned())).ok();
}
let args = value.strip_prefix("hsl(")?.strip_suffix(')')?;
let nums: Vec<f64> = args
.split([',', ' '])
.filter(|s| !s.is_empty())
.map(|s| s.trim_end_matches("deg").trim_end_matches('%').parse())
.collect::<Result<_, _>>()
.ok()?;
let [h, s, l] = nums[..] else { return None };
let (s, l) = (s / 100.0, l / 100.0);
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let hp = (h.rem_euclid(360.0)) / 60.0;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let (r, g, b) = match hp as u8 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = l - c / 2.0;
let byte = |v: f64| ((v + m) * 255.0).round().clamp(0.0, 255.0) as u8;
Some(Color(byte(r), byte(g), byte(b), 0xff))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_every_builtin_frame_from_tokens_css() {
for (id, color) in [
("light", Color(0xe9, 0xea, 0xee, 0xff)),
("dark", Color(0x26, 0x28, 0x2c, 0xff)),
("dark-hc", Color(0x1a, 0x1b, 0x1e, 0xff)),
("solarized-light", Color(0xee, 0xe8, 0xd5, 0xff)),
("solarized-dark", Color(0x07, 0x36, 0x42, 0xff)),
("one-light", Color(0xea, 0xea, 0xeb, 0xff)),
("one-dark", Color(0x21, 0x25, 0x2b, 0xff)),
] {
assert_eq!(builtin_frame(id), Some(color), "{id}");
}
assert_eq!(builtin_frame("system"), None);
assert_eq!(builtin_frame("nope"), None);
}
#[test]
fn resolves_var_chains_and_hsl() {
let css = r#"
/* a { comment } */
:root { --bg-frame: #000; --p: hsl(0, 100%, 50%); }
@media (x) { :root { --bg-frame: #fff; } }
:root[data-color-theme] { --bg-frame: var(--q); }
:root[data-color-theme="t-dark"] { --q: var(--p, #123); }
"#;
let b = blocks(css);
assert_eq!(builtin_frame_in(&b, "dark"), Some(Color(0, 0, 0, 0xff)));
assert_eq!(builtin_frame_in(&b, "t-dark"), Some(Color(0xff, 0, 0, 0xff)));
assert_eq!(builtin_frame_in(&b, "u-dark"), None);
}
}
+50 -14
Переглянути файл
@@ -11,6 +11,7 @@
//! [`Launch::settings_page`] tells it which page to show.
use crate::state::AppState;
use crate::theme_frame::builtin_frame;
use ide_core::settings::AppearanceSettings;
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
@@ -212,29 +213,32 @@ fn window_config(app: &AppHandle) -> IdeResult<WindowConfig> {
/// The theme's `--bg-frame` (tokens.css), mirroring `resolveThemeId` in theme.ts.
pub fn frame_color(appearance: &AppearanceSettings, os_dark: bool) -> Color {
const LIGHT: Color = Color(0xe9, 0xea, 0xee, 0xff);
const DARK: Color = Color(0x26, 0x28, 0x2c, 0xff);
const DARK_HC: Color = Color(0x1a, 0x1b, 0x1e, 0xff);
let sync = appearance.sync_with_os || appearance.theme == "system";
let theme = match (sync, os_dark) {
(false, _) => &appearance.theme,
(true, true) => &appearance.preferred_dark_theme,
(true, false) => &appearance.preferred_light_theme,
};
match theme.as_str() {
"dark-hc" => DARK_HC,
"dark" => DARK,
"light" => LIGHT,
_ if sync && os_dark => DARK,
_ => LIGHT,
}
builtin_frame(theme)
.or_else(|| builtin_frame(if sync && os_dark { "dark" } else { "light" }))
.unwrap_or(Color(0xe9, 0xea, 0xee, 0xff))
}
/// A `#rgb` / `#rrggbb` / `#rrggbbaa` colour sent by the UI (Tauri's own parser).
fn hex_color(hex: &str) -> Option<Color> {
serde_json::from_value(serde_json::Value::String(hex.to_owned())).ok()
}
/// Builds a project window painted in the saved theme's frame colour, so it
/// doesn't flash the light default before its page (and splash) loads.
fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<WebviewWindow> {
let appearance = app.try_state::<AppState>().map(|s| s.global_settings.effective().appearance);
if let Some(a) = &appearance {
let state = app.try_state::<AppState>();
let appearance = state.as_ref().map(|s| s.global_settings.effective().appearance);
// A plugin theme replaces the built-in one in either OS mode; the UI records its resolved frame.
let plugin_frame = state.as_ref().and_then(|s| s.plugins.startup_frame()).and_then(|c| hex_color(&c));
if let Some(color) = plugin_frame {
config.background_color = Some(color);
} else if let Some(a) = &appearance {
config.background_color = Some(frame_color(a, false));
}
let window = WebviewWindowBuilder::from_config(app, &config)
@@ -242,7 +246,7 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
apply_zoom(app, &window);
// "Sync with OS" needs the OS mode, known once the window exists.
if let Some(a) = appearance.filter(|a| a.sync_with_os || a.theme == "system")
if let Some(a) = appearance.filter(|a| plugin_frame.is_none() && (a.sync_with_os || a.theme == "system"))
&& window.theme().is_ok_and(|t| t == Theme::Dark)
{
let _ = window.set_background_color(Some(frame_color(&a, true)));
@@ -418,7 +422,7 @@ pub fn open_settings_window(
config.fullscreen = false;
config.drag_drop_enabled = false;
// macOS shows a child window as soon as it is attached, before the page loads: paint the theme's frame colour.
if let Some(color) = background.and_then(|c| serde_json::from_value(serde_json::Value::String(c)).ok()) {
if let Some(color) = background.as_deref().and_then(hex_color) {
config.background_color = Some(color);
}
windows.set_launch(&label, Launch { project: None, settings_page: page, new_projects });
@@ -465,6 +469,38 @@ mod tests {
assert_eq!(frame_color(&a, true), Color(0x26, 0x28, 0x2c, 0xff));
}
#[test]
fn additional_palettes_keep_native_startup_and_os_preferences_in_sync() {
for (id, color) in [
("solarized-light", Color(0xee, 0xe8, 0xd5, 0xff)),
("solarized-dark", Color(0x07, 0x36, 0x42, 0xff)),
("one-light", Color(0xea, 0xea, 0xeb, 0xff)),
("one-dark", Color(0x21, 0x25, 0x2b, 0xff)),
] {
let mut a = AppearanceSettings { theme: id.into(), ..Default::default() };
assert_eq!(frame_color(&a, false), color);
assert_eq!(frame_color(&a, true), color);
a.sync_with_os = true;
a.preferred_light_theme = id.into();
a.preferred_dark_theme = id.into();
assert_eq!(frame_color(&a, false), color);
assert_eq!(frame_color(&a, true), color);
}
}
#[test]
fn frame_colours_from_the_ui_parse_as_hex() {
for (hex, expected) in [
("#eaeaeb", Color(0xea, 0xea, 0xeb, 0xff)),
("#21252b", Color(0x21, 0x25, 0x2b, 0xff)),
("#8040bfcc", Color(0x80, 0x40, 0xbf, 0xcc)),
("#fff", Color(0xff, 0xff, 0xff, 0xff)),
] {
assert_eq!(hex_color(hex), Some(expected), "{hex}");
}
assert_eq!(hex_color("hsl(220, 13%, 15%)"), None);
}
#[test]
fn labels_sort_main_first_then_numerically() {
assert_eq!(
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.16",
"version": "0.1.17",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+34
Переглянути файл
@@ -478,6 +478,14 @@ export const commands = {
* Returns the refreshed model; a failed build is reported in its `syncError`.
*/
buildSync: (tool: BuildTool, request: RequestId, offline: boolean, profiles: string[], onProgress: Channel<SyncProgress>) => typedError<BuildModel, IdeError>(__TAURI_INVOKE("build_sync", { tool, request, offline, profiles, onProgress })),
/** Where the direct dependency `dependency` of the Maven module `pom` is declared. */
mavenDependencyDeclaration: (pom: string, dependency: ArtifactKey) => typedError<Location, IdeError>(__TAURI_INVOKE("maven_dependency_declaration", { pom, dependency })),
/**
* Adds an `<exclusion>` of `exclusion` to the declaration of the direct dependency
* `dependency` of the Maven module `pom`, through the open document when there is one
* (saved). Returns the declaration; nothing changes when it already excludes it.
*/
mavenExcludeDependency: (pom: string, dependency: ArtifactKey, exclusion: ArtifactKey) => typedError<Location, IdeError>(__TAURI_INVOKE("maven_exclude_dependency", { pom, dependency, exclusion })),
/**
* Build › Build Project / Rebuild Project / Build Module (`file`: a file or folder of the
* module) / Build Artifacts, streaming the console and messages on `on_event`; cancellable
@@ -690,6 +698,11 @@ export const commands = {
pluginId: string,
theme: ThemeDef,
} | null, IdeError>(__TAURI_INVOKE("plugin_set_theme", { pluginId, themeId })),
/**
* The UI reports the selected plugin theme's resolved frame colour (`#rrggbb[aa]`),
* which new windows open in before their page loads.
*/
pluginSetThemeFrame: (color: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_set_theme_frame", { color })),
/**
* Snapshot of process memory and subsystem sizes, summed over all projects.
* Async: the process walk runs on the blocking pool, not the main thread.
@@ -1097,6 +1110,12 @@ export type ApplyOutcome = {
conflicts: string[],
};
/** `groupId:artifactId` of a dependency. */
export type ArtifactKey = {
groupId: string,
artifactId: string,
};
export type AttachKind = "java" | "node" | "python" | "go" | "native";
export type AttachableProcess = {
@@ -3507,6 +3526,12 @@ export type MavenDependency = {
optional: boolean,
/** Transitive dependencies (only after a sync). */
children: MavenDependency[],
/** Why Maven left this occurrence out of the resolved graph (`dependency:tree -Dverbose`). */
omitted?: Omission | null,
/** The version that won when `omitted` is `Conflict`. */
conflictWith?: string | null,
/** The version requested before `<dependencyManagement>` replaced it. */
managedFrom?: string | null,
};
export type MavenModel = {
@@ -3718,6 +3743,15 @@ export type NotificationSettings = {
export type NotifyLevel = "info" | "warning" | "error";
/** Why a dependency occurrence is not part of the resolved graph. */
export type Omission =
/** Another occurrence of the same version is nearer the root. */
"duplicate" |
/** Another version is nearer the root (or declared first) and wins. */
"conflict" |
/** The artifact depends on itself through this path. */
"cycle";
/** How `open_project_window` satisfied the request. */
export type OpenOutcome =
/** Already open in `label`; that window was focused. */
+22
Переглянути файл
@@ -283,6 +283,28 @@ export function contributedAt<T>(state: EditorState, key: string, pos: number):
return state.languageDataAt<T>(key, pos)[0];
}
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵) before the language server's. */
export interface ContributedIntention {
id: string;
label: string;
icon?: string;
run: () => void | Promise<void>;
}
/** Providers of `ContributedIntention`s for the caret of `view` (cheap and synchronous: also drives the light bulb). */
export const intentionProviders = Facet.define<(view: EditorView) => ContributedIntention[]>();
export function contributedIntentions(view: EditorView): ContributedIntention[] {
return view.state.facet(intentionProviders).flatMap((p) => {
try {
return p(view);
} catch (e) {
console.error("intention provider failed", e);
return [];
}
});
}
// --- navigation history ------------------------------------------------------
/** One entry of the Back/Forward (⌘[ / ⌘]) history. 0-based line, UTF-16 col. */
+2 -1
Переглянути файл
@@ -54,6 +54,7 @@ import {
} from "./cm/structural";
import type { DocModel } from "./model/document";
import { structure } from "@/editor/structure";
import { tx } from "@/platform/i18n";
/** Text-editing actions: the editor has focus, or a popup (Find Action) runs them on it. */
export const TEXT_WHEN = "editorTextFocus || textEditorActive && popupOpen";
@@ -293,7 +294,7 @@ function copyReference(view: EditorView, slot: EditorSlot) {
});
recordClipboard(reference);
void navigator.clipboard?.writeText(reference).catch(() => {});
void executeAction("editor.showHint", { text: `Copied reference: ${reference}` });
void executeAction("editor.showHint", { text: tx`Copied reference: ${reference}` });
}
/** ⌃G; when nothing more is found, a hint first and the search from the top on the next press (IDEA). */
+2 -1
Переглянути файл
@@ -5,6 +5,7 @@
*/
import { EditorView } from "@codemirror/view";
import type { EditorState } from "@codemirror/state";
import { tx } from "@/platform/i18n";
export const MAX_CLIPBOARD_ENTRIES = 30;
@@ -45,7 +46,7 @@ export function clipLabel(text: string, max = 80): { label: string; detail: stri
const first = (lines.find((l) => l.trim()) ?? "").trim();
const label = first.length > max ? `${first.slice(0, max - 1)}…` : first || "(whitespace)";
const count = text.endsWith("\n") ? lines.length - 1 : lines.length;
return { label, detail: count > 1 ? `${count} lines` : undefined };
return { label, detail: count > 1 ? tx`${count} lines` : undefined };
}
export const clipboardHistoryExtension = EditorView.domEventHandlers({
+2 -1
Переглянути файл
@@ -12,6 +12,7 @@ import { openideaHighlightStyle } from "./highlight";
import { openideaTheme } from "./theme";
import { findLanguageDescription, loadSupport, loadedSupport, uiModeForPath } from "./languages";
import { fontExtension } from "./setup";
import { tx } from "@/platform/i18n";
export async function previewExtensions(path: string, settings: EditorSettings | undefined): Promise<Extension> {
const open = editorsFor(path)[0]?.ctx;
@@ -25,7 +26,7 @@ export async function previewExtensions(path: string, settings: EditorSettings |
syntaxHighlighting(openideaHighlightStyle),
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({ "aria-label": `Preview of ${path}` }),
EditorView.contentAttributes.of({ "aria-label": tx`Preview of ${path}` }),
support ?? [],
];
}
+2 -1
Переглянути файл
@@ -51,6 +51,7 @@ import { gutterLineDrag } from "./gutterDrag";
import { overwriteField } from "./overwrite";
import { clipboardHistoryExtension } from "../clipboardHistory";
import type { LanguageInfo } from "../backend";
import { tx } from "@/platform/i18n";
export const compartments = {
language: new Compartment(),
@@ -309,7 +310,7 @@ export function baseExtensions(o: SetupOptions): Extension {
findExtension(),
overviewLane,
codeLensExtension,
EditorView.contentAttributes.of({ spellcheck: "false", autocorrect: "off", autocapitalize: "off", "aria-label": `Editor for ${o.ctx.path}` }),
EditorView.contentAttributes.of({ spellcheck: "false", autocorrect: "off", autocapitalize: "off", "aria-label": tx`Editor for ${o.ctx.path}` }),
tabKeymap,
keymap.of([...closeBracketsKeymap, ...editorBaseKeymap, indentWithTab]),
compartments.language.of(o.language ?? []),
+2 -1
Переглянути файл
@@ -5,6 +5,7 @@
* every language with a grammar is covered.
*/
import type { Text } from "@codemirror/state";
import { tx } from "@/platform/i18n";
export interface ChainNode {
kind: string;
@@ -133,7 +134,7 @@ export function unwrapOptions(doc: Text, chain: readonly ChainNode[]): UnwrapOpt
const key = `${target.from}:${target.to}:${label}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({ label: `Unwrap '${label}'`, target: { from: target.from, to: target.to }, ...replacement(doc, target, child) });
out.push({ label: tx`Unwrap '${label}'`, target: { from: target.from, to: target.to }, ...replacement(doc, target, child) });
}
return out;
}
+4 -1
Переглянути файл
@@ -26,7 +26,10 @@ export function installColorScheme(): () => void {
if (s.settings !== prev.settings) apply();
});
const observer = typeof MutationObserver !== "undefined" ? new MutationObserver(apply) : null;
observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "data-contrast"] });
observer?.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme"],
});
return () => {
unsubscribe();
observer?.disconnect();
+3 -2
Переглянути файл
@@ -8,11 +8,12 @@ import { basename } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import type { DocModel } from "./model/document";
import { tx } from "@/platform/i18n";
export function readOnlyQuestion(name: string, readOnly: boolean) {
return readOnly
? { title: "Make File Writable", message: `'${name}' is read-only. Make it writable?`, confirm: "Make Writable" }
: { title: "Make File Read-only", message: `Make '${name}' read-only?`, confirm: "Make Read-only" };
? { title: "Make File Writable", message: tx`'${name}' is read-only. Make it writable?`, confirm: "Make Writable" }
: { title: "Make File Read-only", message: tx`Make '${name}' read-only?`, confirm: "Make Read-only" };
}
/** Applies the toggle without asking. Returns the new read-only state, or null on failure. */
+2 -1
Переглянути файл
@@ -44,6 +44,7 @@ import {
} from "../cm/setup";
import { setMethodLines, softWrapActive } from "../cm/prefs";
import type { EditorSlot } from "./slot";
import { tx } from "@/platform/i18n";
export type Banner = "binary" | "tooLarge" | "readOnly" | "library" | null;
@@ -237,7 +238,7 @@ export class DocModel {
manager.notify({
level: "warning",
title: "Editor resynchronised",
body: `Some unsaved edits to ${this.path} could not be applied and were replaced by the file's current content.`,
body: tx`Some unsaved edits to ${this.path} could not be applied and were replaced by the file's current content.`,
}),
onError: (e) => console.warn(`document ${this.path}: sync error`, e),
},
+2 -1
Переглянути файл
@@ -44,6 +44,7 @@ import { FindBar } from "./FindBar";
import { EditorBanners, VirtualBanner } from "./Banner";
import { CodeBreadcrumbs } from "./StatusItems";
import styles from "./EditorArea.module.css";
import { tx } from "@/platform/i18n";
export function EditorAreaView() {
const layout = useTabs((s) => s.layout);
@@ -343,7 +344,7 @@ function PaneContent({ paneId, tab }: { paneId: string; tab: Tab }) {
);
}
const kind = kinds.get(tab.input.kind);
if (!kind) return <EmptyState icon="file" title={`No editor for “${tab.input.kind}”`} />;
if (!kind) return <EmptyState icon="file" title={tx`No editor for “${tab.input.kind}”`} />;
const Component = kind.component;
return (
<div className={styles.kind} data-editor-focus="" tabIndex={-1} key={tab.id}>
+2 -1
Переглянути файл
@@ -16,6 +16,7 @@ import { posToOffset } from "./positions";
import { onLspRefresh, serverBackoff } from "./availability";
import { editorPrefs } from "@/platform/editorSettings";
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
import { tx } from "@/platform/i18n";
const LENS_KINDS = new Set<SymbolKind>([
"class",
@@ -190,7 +191,7 @@ class UsagesLensPlugin {
lenses.push({
pos: offset,
title: usagesLabel(n),
tooltip: n ? `Show usages of ${t.name}` : undefined,
tooltip: n ? tx`Show usages of ${t.name}` : undefined,
order: 10,
run: n ? (v) => openUsages(v, Math.min(offset, v.state.doc.length)) : undefined,
});
+2 -1
Переглянути файл
@@ -14,6 +14,7 @@ import { call, commands, isTauri, onIdeEvent, type PathCompletion } from "@/plat
import { fileIconName, folderIconName } from "@/ui";
import { setFileDiagnostics } from "./diagnostics";
import { docOf, lspDoc } from "./lsp";
import { tx } from "@/platform/i18n";
// --- completion ---------------------------------------------------------------
@@ -118,7 +119,7 @@ export function unresolvedReferences(): Extension {
refs.map((r) => ({
range: r.range,
severity: "warning",
message: `Cannot resolve file '${r.value}'`,
message: tx`Cannot resolve file '${r.value}'`,
source: doc.language === "html" || doc.language === "vue" || doc.language === "svelte" ? "HTML" : "CSS",
code: null,
})),
+1 -1
Переглянути файл
@@ -161,7 +161,7 @@ export async function reformatDialog(
const name = ctx.path.slice(ctx.path.lastIndexOf("/") + 1);
openPopup({
kind: "reformat",
title: `Reformat File: ${name}`,
title: tx`Reformat File: ${name}`,
hasSelection: !sel.empty,
canOptimizeImports: !contributedAt(view.state, CONTRIBUTED_FORMAT, 0),
initial: lastOptions,
+2 -1
Переглянути файл
@@ -17,6 +17,7 @@ import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { offsetsToRange, posToOffset } from "./positions";
import { onLspRefresh, serverBackoff } from "./availability";
import { gotoTargets } from "./navigation";
import { tx } from "@/platform/i18n";
const KIND_LABEL: Record<InlayHint["kind"], string> = {
type: "Type hints",
@@ -39,7 +40,7 @@ function typeHintOffset(view: EditorView, at: number): number | null {
/** Right-click on a hint: turn its kind off (IDEA's "Disable '…' hints"), or open the settings. */
export function inlayMenuItems(kind: InlayHint["kind"]): MenuItem[] {
return [
{ label: `Disable ${KIND_LABEL[kind]}`, run: () => void setEditorSetting(`inlay.${kind}`, false) },
{ label: tx`Disable ${KIND_LABEL[kind]}`, run: () => void setEditorSetting(`inlay.${kind}`, false) },
{ kind: "separator" },
{ label: "Inlay Hints Settings…", run: () => void executeAction("file.settings", "editor.inlayHints") },
];
+9 -7
Переглянути файл
@@ -7,7 +7,7 @@ import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { forEachDiagnostic } from "@codemirror/lint";
import { commands, isCancelled, type CodeAction } from "@/platform/ipc";
import { whenSynced } from "@/editor/api";
import { contributedIntentions, whenSynced } from "@/editor/api";
import { shortcutLabel } from "@/platform/keymap";
import { debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { offsetsToRange } from "./positions";
@@ -21,6 +21,7 @@ import { spellingIntentions } from "./spelling";
import { inspectionsAt } from "./diagnostics";
import { SPELLING_INSPECTION } from "@/platform/inspections";
import { editInspectionSettings, intentionControls } from "@/platform/inspectionControls";
import { tx } from "@/platform/i18n";
const isQuickFix = (a: CodeAction) => !!a.kind && (a.kind === "quickfix" || a.kind.startsWith("quickfix."));
@@ -195,7 +196,7 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
...items,
...inspections.map((inspection) => ({
id: `inspection:${inspection.id}`,
label: `Inspection '${inspection.name}' options`,
label: tx`Inspection '${inspection.name}' options`,
icon: "settings",
run: () => editInspectionSettings(inspection.id),
submenu: intentionControls(inspection),
@@ -206,8 +207,8 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
/** ⌥↵ */
export async function showIntentions(view: EditorView) {
try {
// Typo fixes come first and need no language server.
const local = spellingIntentions(view);
// Typo fixes and feature-contributed actions come first and need no language server.
const local: ListPopupItem[] = [...spellingIntentions(view), ...contributedIntentions(view)];
let actions: CodeAction[] = [];
let failure: { error: unknown } | null = null;
try {
@@ -337,20 +338,21 @@ const bulbPlugin = ViewPlugin.fromClass(
if (!doc || doc.readOnly || !this.view.dom.isConnected) return;
const state = this.view.state;
const typoFix = spellingIntentions(this.view).length > 0;
const local = typoFix || contributedIntentions(this.view).length > 0;
const backoff = serverBackoff.active(doc.doc);
if (backoff && !typoFix) return;
if (backoff && !local) return;
let actions: CodeAction[] = [];
if (!backoff) {
try {
actions = await fetchIntentions(this.view);
} catch (e) {
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
if (!typoFix) return;
if (!local) return;
}
}
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection)) return;
const line = state.doc.lineAt(state.selection.main.head).number;
const any = actions.length > 0 || typoFix;
const any = actions.length > 0 || local;
this.view.dispatch({
effects: setBulb.of(any ? { line, quickFix: typoFix || actions.some(isQuickFix) } : null),
});
+2 -1
Переглянути файл
@@ -52,6 +52,7 @@ import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
import { shortcutLabel } from "@/platform/keymap";
import { isNavigationGesture, onNavigationModifier } from "@/platform/navigationModifier";
import { create } from "zustand";
import { tx } from "@/platform/i18n";
export async function navigateTo(loc: Location) {
await editorService().openFile(loc.path, {
@@ -224,7 +225,7 @@ async function gotoWebReference(view: EditorView, doc: EditorDocContext, pos: Po
openPopup({
kind: "list",
anchor: caretAnchor(view, offset),
title: `Choose Declaration of '${label}' (${targets.length} found)`,
title: tx`Choose Declaration of '${label}' (${targets.length} found)`,
items: await locationItems(targets),
pin: pinToFind(label, targets),
});
+6 -5
Переглянути файл
@@ -29,6 +29,7 @@ import {
renameRisks,
type LocalRenamePlan,
} from "./syntaxFallback";
import { tx } from "@/platform/i18n";
async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
@@ -83,7 +84,7 @@ export async function startRename(view: EditorView) {
openPopup({
kind: "rename",
anchor: caretAnchor(view, from),
title: `Rename '${oldName}'`,
title: tx`Rename '${oldName}'`,
initial,
onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
});
@@ -99,7 +100,7 @@ export async function startRename(view: EditorView) {
startInplaceRename(view, {
primary: { from, to },
others,
hint: keys ? `Press ${keys} to show dialog with more options` : "Rename in place: ↵ to finish, Esc to cancel",
hint: keys ? tx`Press ${keys} to show dialog with more options` : "Rename in place: ↵ to finish, Esc to cancel",
commit: (newName) => void commitInplace(view, doc, pos, oldName, newName),
dialog,
});
@@ -223,7 +224,7 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
}
openPopup({
kind: "preview",
title: `Rename '${oldName}' to '${newName}'`,
title: tx`Rename '${oldName}' to '${newName}'`,
summary,
confirmLabel: "Do Refactor",
onConfirm: () => void applyEdit(view, edit),
@@ -265,7 +266,7 @@ async function startSyntaxRename(view: EditorView, doc: EditorDocContext, pos: P
openPopup({
kind: "rename",
anchor: caretAnchor(view, rangeToOffsets(view.state.doc, (at ?? plan.occurrences[0]!).range).from),
title: `Rename '${plan.symbol.name}'`,
title: tx`Rename '${plan.symbol.name}'`,
initial: plan.symbol.name,
note: `${SYNTAX_NOTE}: local occurrences only`,
onSubmit: (newName) => void commitSyntaxRename(view, doc, plan, newName),
@@ -315,7 +316,7 @@ export async function commitSyntaxRename(view: EditorView, doc: EditorDocContext
});
openPopup({
kind: "preview",
title: `Rename '${oldName}' to '${newName}'`,
title: tx`Rename '${oldName}' to '${newName}'`,
summary: {
files: 1,
occurrences: occurrences.length,
+5 -4
Переглянути файл
@@ -27,6 +27,7 @@ import { rangeToOffsets } from "./positions";
import { showHint } from "./hint";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { renameNamePart } from "./rename";
import { tx } from "@/platform/i18n";
const CHECK_DELAY = 800;
@@ -124,7 +125,7 @@ async function changeTo(view: EditorView, typo: PlacedTypo) {
openPopup({
kind: "list",
anchor: caretAnchor(view, typo.from),
title: `${rename ? "Rename" : "Change"} '${typo.word}' to`,
title: rename ? tx`Rename '${typo.word}' to` : tx`Change '${typo.word}' to`,
items: suggestions.map((s, i) => ({ id: `${i}`, label: s, run: () => applyCorrection(view, typo, s) })),
});
}
@@ -142,7 +143,7 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] {
? [
{
id: "spelling.saveProject",
label: `Save '${typo.word}' to project-level dictionary`,
label: tx`Save '${typo.word}' to project-level dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, "project"),
},
@@ -150,7 +151,7 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] {
: []),
{
id: "spelling.saveIde",
label: `Save '${typo.word}' to application-level dictionary`,
label: tx`Save '${typo.word}' to application-level dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, "ide"),
},
@@ -210,7 +211,7 @@ export function spellingExtension(): Extension {
typos.map((t) => ({
range: t.range,
severity: "info",
message: `Typo: In word '${t.word}'`,
message: tx`Typo: In word '${t.word}'`,
source: "Spelling",
code: null,
})),
+2 -1
Переглянути файл
@@ -9,6 +9,7 @@ import type { Location, Pos, Range, SymbolKind, SymbolMatch } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { structure, type Locals, type LocalSymbol, type NodeAt } from "@/editor/structure";
import { comparePos, rangeContains, rangeToOffsets } from "./positions";
import { tx } from "@/platform/i18n";
/** Subtle marker for answers that did not come from the language server. */
export const SYNTAX_NOTE = "Based on syntax (language server not ready)";
@@ -237,7 +238,7 @@ export async function planLocalRename(
if (locals.status === "notLocal")
return {
kind: "refused",
message: `Can't rename '${locals.name}' without the language server: only local variables can be renamed based on syntax`,
message: tx`Can't rename '${locals.name}' without the language server: only local variables can be renamed based on syntax`,
};
const { symbol } = locals;
const ranges = [symbol.definition, ...symbol.references].sort((a, b) => comparePos(a.start, b.start));
+2 -1
Переглянути файл
@@ -20,6 +20,7 @@ import { editorService } from "@/workbench/contributions";
import { fileIconName } from "@/ui";
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { baseName, memberAt, methodStop, superMethods } from "./structureNav";
import { tx } from "@/platform/i18n";
const EDITOR_WHEN = "textEditorActive && (editorFocus || popupOpen || !toolWindowFocus)";
@@ -97,7 +98,7 @@ async function superMethod(view: EditorView) {
openPopup({
kind: "list",
anchor: caretAnchor(view, head),
title: method ? `Choose Super Method of ${baseName(method.name)} (${locs.length} found)` : `Choose Super Class or Interface (${locs.length} found)`,
title: method ? tx`Choose Super Method of ${baseName(method.name)} (${locs.length} found)` : tx`Choose Super Class or Interface (${locs.length} found)`,
items: await locationItems(locs),
});
}
+3 -2
Переглянути файл
@@ -35,6 +35,7 @@ import {
type DeclResult,
type Declaration,
} from "./templates";
import { tx } from "@/platform/i18n";
/** Why the language server could not do it (see `withFallback`). */
export type FallbackReason = "notReady" | "error" | "empty";
@@ -594,7 +595,7 @@ async function chooseOccurrences(p: Prepared, self: Occurrence, others: Occurren
},
{
id: "all",
label: `Replace all ${others.length + 1} occurrences`,
label: tx`Replace all ${others.length + 1} occurrences`,
onActive: () => highlightRanges(view, [self, ...others]),
run: () => apply(true),
},
@@ -663,7 +664,7 @@ function applyAndName(p: Prepared, plan: Plan, names: string[]) {
initial: name,
suggestions: names,
note: NOTES[p.reason],
hint: `↵ Apply · Esc Keep '${name}'`,
hint: tx`↵ Apply · Esc Keep '${name}'`,
onSubmit: (chosen) => void rename(p, chosen, name, { original, applied, plan, ranges }),
});
}
+2 -2
Переглянути файл
@@ -264,7 +264,7 @@ describe("safeDelete in the editor", () => {
expect((await run("delete")).state.doc.toString()).toBe("fn unused() {\n unused();\n}\n\nfn main() {}\n");
});
it("confirms first ('Delete function …?') and searches nothing when cancelled", async () => {
it("confirms first ('Delete Function …?') and searches nothing when cancelled", async () => {
const v = editor(text, "unused() {");
outline = ok([item(text, "unused", "fn unused() {\n unused();\n}")]);
confirmAnswer = null;
@@ -272,7 +272,7 @@ describe("safeDelete in the editor", () => {
expect(confirmChecked).toHaveBeenCalledTimes(1);
const opts = confirmChecked.mock.calls[0]![0];
expect(opts.title).toBe("Safe Delete");
expect(opts.message).toBe("Delete function 'unused'?");
expect(opts.message).toBe("Delete Function 'unused'?");
expect(opts.checkbox).toBe("Search in comments and strings");
expect(lspReferences).not.toHaveBeenCalled();
expect(v.state.doc.toString()).toBe(text);
+17 -8
Переглянути файл
@@ -25,6 +25,7 @@ import { ask, confirmChecked } from "@/workbench/messages";
import { openPopup, type PreviewOccurrence } from "@/editor/lsp/popupStore";
import { cannotPerform } from "./catalog";
import { cancelled, languageName } from "./query";
import { tx } from "@/platform/i18n";
// ---------------------------------------------------------------------------
// Deletion range (pure)
@@ -269,11 +270,19 @@ export function usagesMessage(
): { message: string; detail: string } {
const n = usages.length;
const files = new Set(usages.map((u) => u.path)).size;
const noun = n === 1 ? "usage that is" : "usages that are";
return {
message: `${n} ${n === 1 ? "usage" : "usages"} found`,
detail: `${subject} ${plural ? "have" : "has"} ${n} ${noun} not safe to delete${files > 1 ? ` (in ${files} files)` : ""}.`,
};
const where = files > 1 ? tx` (in ${files} files)` : "";
let detail: string;
if (plural)
detail =
n === 1
? tx`${subject} have ${n} usage that is not safe to delete${where}.`
: tx`${subject} have ${n} usages that are not safe to delete${where}.`;
else
detail =
n === 1
? tx`${subject} has ${n} usage that is not safe to delete${where}.`
: tx`${subject} has ${n} usages that are not safe to delete${where}.`;
return { message: n === 1 ? tx`${n} usage found` : tx`${n} usages found`, detail };
}
/** IDEA's "Usages Detected" question; resolves "cancel" when dismissed. */
@@ -391,7 +400,7 @@ function previewTextOccurrences(
});
openPopup({
kind: "preview",
title: `Safe Delete ${target.kind.toLowerCase()} '${target.name}'`,
title: tx`Safe Delete ${target.kind} '${target.name}'`,
summary: {
files: 1,
occurrences: occurrences.length,
@@ -436,7 +445,7 @@ export async function safeDelete(view: EditorView): Promise<void> {
// IDEA always confirms first; usages are searched after OK.
const confirmed = await confirmChecked({
title: "Safe Delete",
message: `Delete ${target.kind.toLowerCase()} '${target.name}'?`,
message: tx`Delete ${target.kind} '${target.name}'?`,
ok: "OK",
checkbox: "Search in comments and strings",
checked: searchInComments,
@@ -453,7 +462,7 @@ export async function safeDelete(view: EditorView): Promise<void> {
]);
if (view.state.doc !== docBefore) return;
if (usages.length) {
const answer = await askUsagesDetected(`${target.kind} '${target.name}'`, usages);
const answer = await askUsagesDetected(tx`${target.kind} '${target.name}'`, usages);
if (answer === "view") viewUsages(target.name, usages);
else if (answer === "delete") applyDeletion(view, docBefore, target, comments);
else view.focus();
+4 -3
Переглянути файл
@@ -27,6 +27,7 @@ import type { RefactoringId } from "./catalog";
import { expressionCandidates, expressionPreview } from "./introduce";
import { findTextOccurrences } from "./occurrences";
import { isIdentifier, isKeyword, suggestNames, uniqueNames } from "./names";
import { tx } from "@/platform/i18n";
/** Refactorings that take an expression (chosen first when nothing is selected). */
export const EXPRESSION_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([
@@ -135,7 +136,7 @@ export function chooseOccurrences(view: EditorView, actions: readonly CodeAction
},
{
id: "all",
label: n > 1 ? `Replace all ${n} occurrences` : "Replace all occurrences",
label: n > 1 ? tx`Replace all ${n} occurrences` : "Replace all occurrences",
onActive: () => highlightRanges(view, n ? occurrences : [{ from: sel.from, to: sel.to }]),
run: () => applyIntroduceAction(view, variants.all, id),
},
@@ -291,13 +292,13 @@ export async function applyIntroduceAction(view: EditorView, action: CodeAction,
primary,
others,
suggestions: names.length > 1 ? names : undefined,
hint: keys ? `Press ${keys} to show dialog with more options` : "↵ to finish, Esc to keep the name",
hint: keys ? tx`Press ${keys} to show dialog with more options` : "↵ to finish, Esc to keep the name",
commit: (name) => renameIntroduced(view, [primary, ...others], found.name, name),
dialog: (typed) =>
openPopup({
kind: "rename",
anchor: caretAnchor(view, primary.from),
title: `Rename '${found.name}'`,
title: tx`Rename '${found.name}'`,
initial: typed,
suggestions: names,
onSubmit: (name) => renameIntroduced(view, [primary, ...others], found.name, name),
+3 -2
Переглянути файл
@@ -7,6 +7,7 @@ import { Icon, IconButton, Spinner, T, Tree, showContextMenu, type MenuItem } fr
import { age, branchLabel, groupTasks, isBusy, type TaskGroup } from "./model";
import { archiveTask, deleteTask, openHome, openTask, useAgents } from "./store";
import styles from "./Agents.module.css";
import { tx } from "@/platform/i18n";
export function AgentsHeaderActions() {
return <IconButton icon="plus" action="agents.newTask" size="small" />;
@@ -117,8 +118,8 @@ async function confirmDelete(task: AgentTask) {
const r = await confirmChecked({
title: "Delete Agent Task",
message: worktree
? `Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: `Delete “${task.title}”? Files it changed are kept.`,
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree ? "Also remove its worktree folder" : undefined,
+1 -1
Переглянути файл
@@ -157,7 +157,7 @@ export function Composer(props: ComposerProps) {
for (const file of picked) {
if (!file.type.startsWith("image/")) continue;
if (file.size > MAX_IMAGE_BYTES) {
notifications().notify({ level: "warning", title: "Image too large", body: `${file.name} is over 5 MB.` });
notifications().notify({ level: "warning", title: "Image too large", body: tx`${file.name} is over 5 MB.` });
continue;
}
const reader = new FileReader();
+2 -1
Переглянути файл
@@ -1,5 +1,6 @@
/** Pure composer helpers: `@` / `/` completion, attachments, history recall, settings. */
import type { AgentCommand, AgentConfigOption, AgentImage, AgentPrompt, AgentUsage } from "@/bindings";
import { tx } from "@/platform/i18n";
export interface FileRef {
/** Absolute path (in the task's directory). */
@@ -114,7 +115,7 @@ export function usageLabel(u: AgentUsage): { short: string; detail: string } {
const pct = Math.min(100, Math.round((u.used / u.size) * 100));
const k = (n: number) => (n >= 1000 ? `${Math.round(n / 1000)}k` : `${Math.round(n)}`);
const cost = u.cost != null ? ` · ${u.currency === "USD" || !u.currency ? "$" : `${u.currency} `}${u.cost.toFixed(2)}` : "";
return { short: `${pct}%`, detail: `${k(u.used)} / ${k(u.size)} tokens${cost}` };
return { short: `${pct}%`, detail: tx`${k(u.used)} / ${k(u.size)} tokens${cost}` };
}
/** `data:image/png;base64,AAA` → an image attachment. */
+2 -1
Переглянути файл
@@ -28,6 +28,7 @@ import {
type StructuralForm,
} from "./structural";
import styles from "./Analysis.module.css";
import { tx } from "@/platform/i18n";
function InspectCodeDialog({ onClose }: { onClose: () => void }) {
const [scope, setScope] = useState<ScopeChoice>(() => defaultScope());
@@ -363,7 +364,7 @@ function ReplacePreviewDialog({ files, onClose }: { files: StructuralFile[]; onC
<Checkbox
checked={!excluded.has(key)}
onChange={(on) => toggle(key, on)}
aria-label={`Replace in ${f.relPath}:${m.range.start.line + 1}`}
aria-label={tx`Replace in ${f.relPath}:${m.range.start.line + 1}`}
/>
<div className={styles.previewBody}>
<span className={styles.previewWhere}>
+2 -1
Переглянути файл
@@ -11,6 +11,7 @@ import { maybeEditorService, notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { removeTask, upsertTask } from "@/workbench/tasks";
import { changedFiles, currentFile, type ScopeChoice } from "./scope";
import { tx } from "@/platform/i18n";
export interface CleanupOptions {
fixAll: boolean;
@@ -97,7 +98,7 @@ export async function runCodeCleanup(choice: ScopeChoice, options: CleanupOption
}
if (
files.length > CONFIRM_ABOVE &&
!(await confirm({ title: "Code Cleanup", message: `Clean up ${files.length} files?`, ok: "Clean Up" }))
!(await confirm({ title: "Code Cleanup", message: tx`Clean up ${files.length} files?`, ok: "Clean Up" }))
)
return;
const editors = maybeEditorService();
+2 -1
Переглянути файл
@@ -21,6 +21,7 @@ import {
} from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { resolveScope, type ScopeChoice } from "./scope";
import { tx } from "@/platform/i18n";
const STATE_KEY = "openidea.analysis.structural.v1";
@@ -152,7 +153,7 @@ export async function showStructuralResults(
group: "analysis",
level: "warning",
title: "Search Structurally",
body: `Stopped after ${summary.matches} matches`,
body: tx`Stopped after ${summary.matches} matches`,
});
}
}
+2 -1
Переглянути файл
@@ -10,6 +10,7 @@ import { useProject } from "@/platform/project";
import { notifications, registerEditorBanner } from "@/workbench/contributions";
import { promptInput } from "@/workbench/inputDialogs";
import { showNewProject } from "./NewProject";
import { tx } from "@/platform/i18n";
/** localStorage prefixes of IDE-level state exported with the settings (templates, macros, layouts). */
export const EXPORTED_STORAGE = [
@@ -93,7 +94,7 @@ async function renameProject() {
initial: project.name,
okLabel: "Rename",
validate: () => null,
hint: `Leave empty to use the folder name (${folder}).`,
hint: tx`Leave empty to use the folder name (${folder}).`,
});
if (name === null) return;
try {
+8 -3
Переглянути файл
@@ -43,6 +43,7 @@ import {
useBuild,
} from "./store";
import styles from "./BuildTools.module.css";
import { tx } from "@/platform/i18n";
export function MavenView() {
return <BuildToolView tool="maven" />;
@@ -152,6 +153,7 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
action={`${tool}.toggleOffline`}
pressed={maven ? settings.maven.offline : settings.gradle.offline}
/>
{maven && <IconButton icon="build-dependencies" size="small" iconSize={16} action="maven.analyzeDependencies" />}
{maven && (
<IconButton
icon="skip-tests"
@@ -291,8 +293,8 @@ function BuildToolView({ tool }: { tool: BuildTool }) {
const config = isRunnable(node) && model ? nodeConfig(nodes.filter(isRunnable), model) : null;
if (config) {
items.push(
{ label: `Run '${config.name}'`, icon: "run", run: () => runConfig(config, "run") },
{ label: `Debug '${config.name}'`, icon: "debug", run: () => runConfig(config, "debug") },
{ label: tx`Run '${config.name}'`, icon: "run", run: () => runConfig(config, "run") },
{ label: tx`Debug '${config.name}'`, icon: "debug", run: () => runConfig(config, "debug") },
{ kind: "separator" },
);
if (node.kind === "runConfig")
@@ -308,13 +310,16 @@ function BuildToolView({ tool }: { tool: BuildTool }) {
},
{ kind: "action", action: "maven.reload", label: "Reload All Maven Projects" },
{ kind: "action", action: "maven.executeGoal" },
{ kind: "action", action: "maven.analyzeDependencies", arg: { pom: node.project.pom } },
);
}
if (node.kind === "dependencies")
items.push({ kind: "action", action: "maven.analyzeDependencies", arg: { pom: node.project.pom } });
if (node.kind === "gradleProject") {
const file = node.project.buildFile;
if (file)
items.push({
label: `Open ${file.split("/").pop()}`,
label: tx`Open ${file.split("/").pop()}`,
icon: "file-gradle",
run: () => void editorService().openFile(`${root}/${file}`),
});
+205
Переглянути файл
@@ -0,0 +1,205 @@
.view {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
background: var(--bg-editor);
}
.toolbar {
flex: none;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
min-height: 36px;
padding: 4px 8px;
border-bottom: 1px solid var(--border);
}
.module {
min-width: 160px;
max-width: 260px;
}
.search {
flex: 1 1 200px;
min-width: 140px;
max-width: 360px;
}
.scope {
min-width: 110px;
}
.sep {
width: 1px;
height: 16px;
margin: 0 2px;
background: var(--border);
}
.banner {
flex: none;
display: flex;
align-items: center;
gap: 6px;
min-height: 28px;
padding: 2px 10px;
font-size: var(--fs-small);
color: var(--fg-secondary);
border-bottom: 1px solid var(--border);
}
.bannerText {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.body {
flex: 1;
min-height: 0;
display: flex;
}
.body > * {
flex: 1;
min-width: 0;
}
.panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.panel > * {
flex: 1;
min-height: 0;
}
.row {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
flex: 1;
white-space: nowrap;
}
.icon {
flex: none;
}
.label {
flex: 0 1 auto;
min-width: 24px;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
.selectedLabel {
color: var(--fg-strong);
}
.version {
flex: none;
font-family: var(--font-mono);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.detail {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.conflict {
color: var(--warning);
}
.omitted .label,
.omitted .version {
color: var(--fg-muted);
}
.usages {
display: flex;
flex-direction: column;
min-height: 0;
height: 100%;
}
.usagesHeader {
flex: none;
display: flex;
align-items: center;
gap: 6px;
min-height: 32px;
padding: 0 10px;
border-bottom: 1px solid var(--border);
}
.usagesTitle {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
color: var(--fg-strong);
}
.conflictNote {
flex: none;
display: flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
font-size: var(--fs-small);
color: var(--fg-secondary);
background: var(--bg-feedback-warning);
border-bottom: 1px solid var(--border-feedback-warning);
}
.usageList {
flex: 1;
min-height: 0;
overflow: auto;
padding: 4px 0;
}
.usage {
padding: 6px 10px 8px;
border-bottom: 1px solid var(--border);
}
.usageHeader {
display: flex;
align-items: center;
gap: 6px;
min-height: 26px;
}
.usageVersion {
flex: none;
font-family: var(--font-mono);
color: var(--fg);
}
.usageStatus {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--fs-small);
color: var(--fg-muted);
}
.spacer {
flex: 1;
}
.path {
margin: 4px 0 0;
padding: 0;
list-style: none;
}
.step {
display: flex;
align-items: center;
gap: 6px;
min-height: 22px;
white-space: nowrap;
}
.stepLabel {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-secondary);
}
.stepTarget {
color: var(--fg-strong);
}
+118
Переглянути файл
@@ -0,0 +1,118 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import type { BuildModel, MavenDependency } from "@/platform/ipc";
import { menuGroupItems, provideEditorService, type EditorService } from "@/workbench/contributions";
import { DependencyAnalyzer } from "./DependencyAnalyzer";
import { activate } from "./index";
import { ANALYZER_KIND, useAnalyzer, useBuild } from "./store";
const ipc = vi.hoisted(() => ({ exclude: vi.fn(), declaration: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
call: (value: unknown) => value,
commands: { ...real.commands, mavenExcludeDependency: ipc.exclude, mavenDependencyDeclaration: ipc.declaration },
};
});
function dep(coords: string, extra: Partial<MavenDependency> = {}, children: MavenDependency[] = []): MavenDependency {
const [groupId, artifactId, version] = coords.split(":");
return {
groupId: groupId!,
artifactId: artifactId!,
version: version!,
type: "jar",
classifier: null,
scope: "compile",
optional: false,
children,
...extra,
};
}
const model: BuildModel = {
maven: {
projects: [
{
pom: "pom.xml",
dir: "",
groupId: "demo",
artifactId: "conflict-demo",
version: "1.0",
packaging: "jar",
displayName: "conflict-demo",
parent: null,
modules: [],
aggregated: false,
plugins: [],
dependencies: [
dep("com.google.guava:guava:32.1.3-jre"),
dep("com.google.inject:guice:5.1.0", {}, [
dep("com.google.guava:guava:30.1-jre", { omitted: "conflict", conflictWith: "32.1.3-jre" }),
]),
],
profiles: [],
javaVersion: 17,
command: "mvn",
options: [],
env: {},
},
],
profiles: [],
syncedAt: 1,
stale: false,
syncError: null,
},
gradle: null,
};
describe("dependency analyzer", () => {
let dispose: () => void = () => {};
const openInput = vi.fn(() => Promise.resolve());
const openFile = vi.fn(() => Promise.resolve());
beforeEach(() => {
provideEditorService({ openInput, openFile, activePath: () => null } as unknown as EditorService);
setContext("projectOpen", true);
dispose = activate();
act(() => useBuild.setState({ root: "/p", model }));
});
afterEach(() => {
dispose();
setContext("projectOpen", false);
vi.clearAllMocks();
});
it("opens as an editor tab from the action and from a pom.xml's menus", async () => {
await executeAction("maven.analyzeDependencies", { pom: "pom.xml" });
expect(openInput).toHaveBeenCalledWith(expect.objectContaining({ kind: ANALYZER_KIND }), { focus: true });
expect(useAnalyzer.getState().pom).toBe("pom.xml");
for (const menu of ["editor", "projectView", "editorTab"] as const) {
const items = menuGroupItems(menu, { paths: ["/p/pom.xml"] });
expect(items[0]).toMatchObject({ action: "maven.analyzeDependencies", arg: { pom: "pom.xml" } });
}
expect(menuGroupItems("editor", { paths: ["/p/other/pom.xml"] })).toEqual([]);
expect(menuGroupItems("editor", { paths: ["/p/src/Main.java"] })).toEqual([]);
});
it("marks conflicts, shows their usages and excludes through the direct dependency", async () => {
ipc.exclude.mockResolvedValue({ path: "/p/pom.xml", range: {} });
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
expect(screen.queryByText("com.google.inject:guice")).toBeNull();
fireEvent.mouseDown(screen.getByText("com.google.guava:guava").closest("[role=treeitem]")!, { button: 0 });
expect(screen.getByText("omitted for conflict with 32.1.3-jre")).toBeTruthy();
expect(screen.getByText("com.google.inject:guice:5.1.0")).toBeTruthy();
// Only the transitive usage can be excluded.
const exclude = screen.getAllByRole("button", { name: "Exclude" });
expect(exclude).toHaveLength(1);
await act(async () => fireEvent.click(exclude[0]!));
expect(ipc.exclude).toHaveBeenCalledWith(
"pom.xml",
{ groupId: "com.google.inject", artifactId: "guice" },
{ groupId: "com.google.guava", artifactId: "guava" },
);
});
});
+420
Переглянути файл
@@ -0,0 +1,420 @@
/**
* Dependency Analyzer editor tab: a Maven module's resolved artifacts (flat list or
* the transitive tree) with conflicts marked, and for the selected artifact every
* path that brings it in, with Exclude / Jump to Source / Copy Coordinates.
*/
import { useMemo, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { call, commands, type MavenDependency, type MavenProject } from "@/platform/ipc";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
import {
Button,
Checkbox,
EmptyState,
Icon,
IconButton,
SearchField,
Select,
SplitGroup,
SplitHandle,
SplitPanel,
Spinner,
T,
Tree,
copyText,
showContextMenu,
type MenuItem,
type SelectOption,
} from "@/ui";
import {
analyze,
artifactKey,
coordinates,
exclusionFor,
filterArtifacts,
filterTree,
scopesOf,
sortedUsages,
statusText,
usageStatus,
type AnalyzedArtifact,
type DependencyTreeNode,
type DependencyUsage,
} from "./analyzer";
import { syncTool, useAnalyzer, useBuild } from "./store";
import styles from "./DependencyAnalyzer.module.css";
type Mode = "list" | "tree";
type Node =
| { kind: "artifact"; key: string; artifact: AnalyzedArtifact }
| { kind: "node"; key: string; node: DependencyTreeNode; children: Node[] };
const ALL_SCOPES = "*";
function errorText(e: unknown) {
return e instanceof Error ? e.message : String(e);
}
async function jumpToDeclaration(pom: string, d: MavenDependency) {
try {
const loc = await call(commands.mavenDependencyDeclaration(pom, { groupId: d.groupId, artifactId: d.artifactId }));
const { start, end } = loc.range;
await editorService().openFile(loc.path, {
focus: true,
selection: { line: start.line, col: start.col, endLine: end.line, endCol: end.col },
});
} catch (e) {
notifications().notify({
level: "warning",
group: "tools",
title: "Cannot find the declaration",
body: errorText(e),
});
}
}
async function exclude(pom: string, usage: DependencyUsage) {
const target = exclusionFor(usage);
if (!target) return;
const what = `${target.exclusion.groupId}:${target.exclusion.artifactId}`;
try {
await call(commands.mavenExcludeDependency(pom, target.dependency, target.exclusion));
} catch (e) {
notifications().notify({ level: "error", group: "tools", title: `Cannot exclude ${what}`, body: errorText(e) });
return;
}
await syncTool("maven");
}
function versionLabel(d: MavenDependency) {
return d.version ?? "";
}
function moduleOptions(projects: readonly MavenProject[]): SelectOption[] {
return projects
.filter((p) => p.packaging !== "pom" || p.dependencies.length > 0)
.map((p) => ({ value: p.pom, label: p.displayName, detail: p.pom, icon: "maven-project" }));
}
function ArtifactRow({ artifact, selected }: { artifact: AnalyzedArtifact; selected: boolean }) {
const tx = useTx();
return (
<span className={styles.row}>
<Icon name={artifact.conflict ? "warning" : "library"} size={16} className={styles.icon} />
<span className={clsx(styles.label, artifact.conflict && styles.conflict, selected && styles.selectedLabel)}>
{artifact.key}
</span>
<span className={styles.version}>{artifact.version ?? tx("omitted")}</span>
{artifact.conflict && (
<span className={styles.detail}>{artifact.requested.filter((v) => v !== artifact.version).join(", ")}</span>
)}
{artifact.scope !== "compile" && <span className={styles.detail}>({artifact.scope})</span>}
</span>
);
}
function TreeRow({ node, conflict, selected }: { node: DependencyTreeNode; conflict: boolean; selected: boolean }) {
const tx = useTxTemplate();
const d = node.dependency;
const status = statusText(usageStatus(d));
return (
<span className={clsx(styles.row, d.omitted != null && styles.omitted)}>
<Icon name={conflict ? "warning" : "library"} size={16} className={styles.icon} />
<span className={clsx(styles.label, conflict && styles.conflict, selected && styles.selectedLabel)}>
{artifactKey(d)}
</span>
<span className={styles.version}>{versionLabel(d)}</span>
{d.scope !== "compile" && <span className={styles.detail}>({d.scope})</span>}
{status && <span className={styles.detail}>{tx(status)}</span>}
</span>
);
}
function UsageBlock({ usage, module, pom }: { usage: DependencyUsage; module: MavenProject; pom: string }) {
const tx = useTxTemplate();
const status = usageStatus(usage.dependency);
const text = statusText(status);
const direct = usage.path[0]!;
const canExclude = !!exclusionFor(usage);
return (
<section className={styles.usage} aria-label={coordinates(usage.dependency)}>
<div className={styles.usageHeader}>
<Icon
name={status.kind === "conflict" ? "warning" : status.kind === "resolved" ? "success" : "info"}
size={16}
className={styles.icon}
/>
<span className={styles.usageVersion}>{status.version}</span>
<span className={clsx(styles.usageStatus, status.kind === "conflict" && styles.conflict)}>
{text ? tx(text) : tx("resolved")}
</span>
<span className={styles.spacer} />
{canExclude && (
<Button size="small" variant="ghost" onClick={() => void exclude(pom, usage)}>
Exclude
</Button>
)}
<IconButton
icon="autoscroll-to-source"
size="small"
title="Jump to Source"
onClick={() => void jumpToDeclaration(pom, direct)}
/>
</div>
<ol className={styles.path}>
<li className={styles.step} style={{ paddingLeft: 0 }}>
<Icon name="maven-project" size={16} className={styles.icon} />
<span className={styles.stepLabel}>{module.displayName}</span>
</li>
{usage.path.map((d, i) => (
<li key={i} className={styles.step} style={{ paddingLeft: (i + 1) * 16 }}>
<Icon name="library" size={16} className={styles.icon} />
<span className={clsx(styles.stepLabel, i === usage.path.length - 1 && styles.stepTarget)}>
{coordinates(d)}
</span>
{d.scope !== "compile" && <span className={styles.detail}>({d.scope})</span>}
</li>
))}
</ol>
</section>
);
}
function UsagesPane({
artifact,
module,
pom,
}: {
artifact: AnalyzedArtifact | null;
module: MavenProject;
pom: string;
}) {
if (!artifact) return <EmptyState title="Select a dependency to see its usages" />;
const usages = sortedUsages(artifact.usages);
const coords = coordinates({ ...artifact, version: artifact.version });
return (
<div className={styles.usages}>
<div className={styles.usagesHeader}>
<span className={clsx(styles.usagesTitle, artifact.conflict && styles.conflict)}>{coords}</span>
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(coords)} />
</div>
{artifact.conflict && (
<div className={styles.conflictNote} role="note">
<Icon name="warning" size={16} />
<span>
<T>Versions requested</T>: {artifact.requested.join(", ")}
</span>
</div>
)}
<div className={styles.usageList} aria-label="Usages">
{usages.map((u, i) => (
<UsageBlock key={i} usage={u} module={module} pom={pom} />
))}
</div>
</div>
);
}
export function DependencyAnalyzer(_props: { input: EditorInput }) {
const tx = useTx();
const maven = useBuild((s) => s.model?.maven ?? null);
const syncing = useBuild((s) => s.syncing.maven);
const chosen = useAnalyzer((s) => s.pom);
const [query, setQuery] = useState("");
const [conflictsOnly, setConflictsOnly] = useState(false);
const [scope, setScope] = useState<string>(ALL_SCOPES);
const [mode, setMode] = useState<Mode>("list");
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const options = useMemo(() => moduleOptions(maven?.projects ?? []), [maven]);
const pom = options.some((o) => o.value === chosen) ? chosen! : (options[0]?.value ?? null);
const module = maven?.projects.find((p) => p.pom === pom) ?? null;
const artifacts = useMemo(() => analyze(module?.dependencies ?? []), [module]);
const conflicted = useMemo(() => new Set(artifacts.filter((a) => a.conflict).map((a) => a.key)), [artifacts]);
const filter = useMemo(
() => ({ query, conflictsOnly, scope: scope === ALL_SCOPES ? null : scope }),
[query, conflictsOnly, scope],
);
const listed = useMemo(() => filterArtifacts(artifacts, filter), [artifacts, filter]);
const tree = useMemo(() => filterTree(module?.dependencies ?? [], filter, conflicted), [module, filter, conflicted]);
const roots: Node[] = useMemo(() => {
const toNode = (node: DependencyTreeNode): Node => ({
kind: "node",
key: `n:${node.key}`,
node,
children: node.children.map(toNode),
});
return mode === "list"
? listed.map((artifact) => ({ kind: "artifact", key: `a:${artifact.key}`, artifact }))
: tree.map(toNode);
}, [mode, listed, tree]);
// A narrowing filter opens the tree down to its matches until the user expands or collapses.
const filterId = `${mode}|${filter.query}|${filter.conflictsOnly}|${filter.scope}|${pom}`;
const [manual, setManual] = useState<{ id: string; keys: Set<string> } | null>(null);
const expanded = useMemo(() => {
if (manual?.id === filterId) return manual.keys;
const keys = new Set<string>();
if (filter.conflictsOnly || filter.scope != null || filter.query.trim()) {
const walk = (nodes: readonly Node[]) => {
for (const n of nodes)
if (n.kind === "node" && n.children.length) {
keys.add(n.key);
walk(n.children);
}
};
walk(roots);
}
return keys;
}, [manual, filterId, filter, roots]);
const selected = artifacts.find((a) => a.key === selectedKey) ?? null;
const scopeOptions: SelectOption[] = [
{ value: ALL_SCOPES, label: tx("All scopes") },
...scopesOf(artifacts).map((s) => ({ value: s, label: s })),
];
const nodeArtifactKey = (n: Node) => (n.kind === "artifact" ? n.artifact.key : artifactKey(n.node.dependency));
/** The usage a row stands for: a tree node's own, else the artifact's direct (or first) one. */
const usageOf = (n: Node): DependencyUsage | undefined => {
if (n.kind === "node")
return artifacts
.find((a) => a.key === nodeArtifactKey(n))
?.usages.find((u) => u.dependency === n.node.dependency);
return n.artifact.usages.find((u) => u.path.length === 1) ?? n.artifact.usages[0];
};
const contextMenu = (n: Node | null, _sel: Set<string>, e: MouseEvent) => {
if (!n || !pom) return;
e.preventDefault();
const usage = usageOf(n);
if (!usage) return;
const items: MenuItem[] = [
{ label: "Jump to Source", icon: "autoscroll-to-source", run: () => void jumpToDeclaration(pom, usage.path[0]!) },
];
if (exclusionFor(usage)) items.push({ label: "Exclude", run: () => void exclude(pom, usage) });
items.push({ label: "Copy Coordinates", icon: "copy", run: () => void copyText(coordinates(usage.dependency)) });
showContextMenu({ x: e.clientX, y: e.clientY }, items);
};
if (!maven) return <EmptyState title="No Maven projects" />;
return (
<div className={styles.view}>
<div className={styles.toolbar} role="toolbar" aria-label="Dependency Analyzer">
<Select
aria-label="Module"
className={styles.module}
value={pom}
options={options}
onChange={(v) => {
useAnalyzer.setState({ pom: v });
setSelectedKey(null);
}}
/>
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder={tx("Search dependencies")}
aria-label="Search dependencies"
clearable
/>
<Checkbox checked={conflictsOnly} onChange={setConflictsOnly} label="Show conflicts only" />
<Select aria-label="Scope" className={styles.scope} value={scope} options={scopeOptions} onChange={setScope} />
<span className={styles.sep} />
<IconButton
icon="list"
size="small"
iconSize={16}
title="Show as List"
pressed={mode === "list"}
onClick={() => setMode("list")}
/>
<IconButton
icon="hierarchy"
size="small"
iconSize={16}
title="Show as Tree"
pressed={mode === "tree"}
onClick={() => setMode("tree")}
/>
<span className={styles.sep} />
{syncing ? (
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
) : (
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
)}
</div>
{syncing ? (
<div className={styles.banner} role="status">
<Spinner size={12} />
<span className={styles.bannerText}>{syncing.message}</span>
</div>
) : maven.stale && maven.syncedAt != null ? (
<div className={styles.banner}>
<Icon name="maven-load-changes" size={16} />
<span className={styles.bannerText}>
<T>Dependency trees may be out of date</T>
</span>
<Button size="small" variant="ghost" onClick={() => void syncTool("maven")}>
Load Maven Changes
</Button>
</div>
) : null}
{maven.syncedAt == null ? (
<EmptyState
title="Dependency trees are read when Maven projects are reloaded"
actions={
<Button size="small" onClick={() => void syncTool("maven")} disabled={!!syncing}>
Reload All Maven Projects
</Button>
}
/>
) : !module || !pom ? (
<EmptyState title="No Maven modules" />
) : (
<div className={styles.body}>
<SplitGroup orientation="horizontal" id="maven-dependency-analyzer-split">
<SplitPanel id="dependencies" minSize={200} className={styles.panel}>
<Tree<Node>
aria-label="Dependencies"
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "artifact" ? n.artifact.key : artifactKey(n.node.dependency))}
getChildren={(n) => (n.kind === "node" ? n.children : undefined)}
isExpandable={(n) => n.kind === "node" && n.node.children.length > 0}
expanded={expanded}
onExpandedChange={(next) => setManual({ id: filterId, keys: next })}
onSelectionChange={(_keys, lead) => setSelectedKey(lead ? nodeArtifactKey(lead) : null)}
renderNode={(n, state) =>
n.kind === "artifact" ? (
<ArtifactRow artifact={n.artifact} selected={state.selected} />
) : (
<TreeRow
node={n.node}
conflict={conflicted.has(artifactKey(n.node.dependency))}
selected={state.selected}
/>
)
}
onActivate={(n) => {
const usage = usageOf(n);
if (usage) void jumpToDeclaration(pom, usage.path[0]!);
}}
onContextMenu={contextMenu}
multiSelect={false}
empty={<EmptyState title={artifacts.length ? "No dependencies match the filter" : "No dependencies"} />}
/>
</SplitPanel>
<SplitHandle />
<SplitPanel id="usages" minSize={240} className={styles.panel}>
<UsagesPane artifact={selected} module={module} pom={pom} />
</SplitPanel>
</SplitGroup>
</div>
)}
</div>
);
}
+1
Переглянути файл
@@ -70,6 +70,7 @@ describe("build tools feature", () => {
it("offers its actions in Search Everywhere only for Maven projects and toggles run options", async () => {
const visible = () => allActions().filter((a) => !a.hidden && a.id.startsWith("maven."));
expect(visible().map((a) => a.id).sort()).toEqual([
"maven.analyzeDependencies",
"maven.executeGoal",
"maven.reload",
"maven.toggleOffline",
+124
Переглянути файл
@@ -0,0 +1,124 @@
import { describe, expect, it } from "vitest";
import type { MavenDependency } from "@/platform/ipc";
import {
analyze,
coordinates,
exclusionFor,
filterArtifacts,
filterTree,
scopesOf,
sortedUsages,
statusText,
usageStatus,
type AnalyzerFilter,
} from "./analyzer";
function dep(coords: string, extra: Partial<MavenDependency> = {}, children: MavenDependency[] = []): MavenDependency {
const [groupId, artifactId, version, scope = "compile"] = coords.split(":");
return {
groupId: groupId!,
artifactId: artifactId!,
version: version!,
type: "jar",
classifier: null,
scope,
optional: false,
children,
...extra,
};
}
/** The tree `dependency:tree -Dverbose` printed for the conflict demo project. */
const TREE: MavenDependency[] = [
dep("org.hamcrest:hamcrest-core:1.3"),
dep("org.apache.commons:commons-text:1.10.0", {}, [dep("org.apache.commons:commons-lang3:3.12.0")]),
dep("org.apache.commons:commons-configuration2:2.10.1", {}, [
dep("org.apache.commons:commons-lang3:3.14.0", { omitted: "conflict", conflictWith: "3.12.0" }),
dep("org.apache.commons:commons-text:1.11.0", { omitted: "conflict", conflictWith: "1.10.0" }),
dep("commons-logging:commons-logging:1.2", { managedFrom: "1.3.0" }),
]),
dep("com.google.guava:guava:32.1.3-jre", {}, [dep("com.google.guava:failureaccess:1.0.1")]),
dep("com.google.inject:guice:5.1.0", {}, [
dep("javax.inject:javax.inject:1"),
dep("com.google.guava:guava:30.1-jre", { omitted: "conflict", conflictWith: "32.1.3-jre" }),
]),
dep("junit:junit:4.13.2:test", {}, [dep("org.hamcrest:hamcrest-core:1.3:test", { omitted: "duplicate" })]),
];
const ALL: AnalyzerFilter = { query: "", conflictsOnly: false, scope: null };
const byKey = (key: string) => analyze(TREE).find((a) => a.key === key)!;
describe("dependency analyzer", () => {
it("collects every artifact with its resolved version and conflicts", () => {
const artifacts = analyze(TREE);
expect(artifacts.filter((a) => a.conflict).map((a) => a.key)).toEqual([
"com.google.guava:guava",
"org.apache.commons:commons-lang3",
"org.apache.commons:commons-text",
]);
const lang3 = byKey("org.apache.commons:commons-lang3");
expect(lang3).toMatchObject({ version: "3.12.0", requested: ["3.12.0", "3.14.0"], scope: "compile" });
const hamcrest = byKey("org.hamcrest:hamcrest-core");
expect(hamcrest.conflict).toBe(false);
expect(hamcrest.usages).toHaveLength(2);
// Managed versions count the version that was asked for.
expect(byKey("commons-logging:commons-logging").requested).toEqual(["1.3.0"]);
});
it("lists usage paths from the direct dependency, resolved first", () => {
const usages = sortedUsages(byKey("com.google.guava:guava").usages);
expect(usages.map((u) => u.path.map((d) => d.artifactId))).toEqual([["guava"], ["guice", "guava"]]);
expect(usages.map((u) => statusText(usageStatus(u.dependency)))).toEqual([
null,
"omitted for conflict with 32.1.3-jre",
]);
expect(statusText(usageStatus(byKey("commons-logging:commons-logging").usages[0]!.dependency))).toBe(
"version managed from 1.3.0",
);
expect(statusText(usageStatus(dep("a:b:1", { omitted: "duplicate" })))).toBe("omitted for duplicate");
});
it("excludes through the direct dependency that brings an occurrence in", () => {
const [direct, transitive] = sortedUsages(byKey("com.google.guava:guava").usages);
expect(exclusionFor(direct!)).toBeNull();
expect(exclusionFor(transitive!)).toEqual({
dependency: { groupId: "com.google.inject", artifactId: "guice" },
exclusion: { groupId: "com.google.guava", artifactId: "guava" },
});
});
it("filters by conflicts, scope and text (including requested versions)", () => {
const keys = (f: Partial<AnalyzerFilter>) => filterArtifacts(analyze(TREE), { ...ALL, ...f }).map((a) => a.key);
expect(keys({ conflictsOnly: true })).toHaveLength(3);
expect(keys({ scope: "test" })).toEqual(["junit:junit", "org.hamcrest:hamcrest-core"]);
expect(keys({ query: "LANG3" })).toEqual(["org.apache.commons:commons-lang3"]);
expect(keys({ query: "30.1-jre" })).toEqual(["com.google.guava:guava"]);
expect(scopesOf(analyze(TREE))).toEqual(["compile", "test"]);
});
it("keeps the paths to matches in the tree view", () => {
const conflicted = new Set(
analyze(TREE)
.filter((a) => a.conflict)
.map((a) => a.key),
);
expect(filterTree(TREE, ALL, conflicted)).toHaveLength(TREE.length);
const tree = filterTree(TREE, { ...ALL, conflictsOnly: true }, conflicted);
expect(tree.map((n) => n.dependency.artifactId)).toEqual([
"commons-text",
"commons-configuration2",
"guava",
"guice",
]);
expect(tree[1]!.children.map((n) => n.dependency.artifactId)).toEqual(["commons-lang3", "commons-text"]);
expect(tree[3]!.children.map((n) => n.key)).toEqual(["/4/1"]);
expect(filterTree(TREE, { ...ALL, query: "hamcrest", scope: "test" }, conflicted).map((n) => n.key)).toEqual([
"/5",
]);
});
it("formats coordinates with the classifier", () => {
expect(coordinates(dep("g:a:1", { classifier: "linux" }))).toBe("g:a:linux:1");
expect(coordinates(dep("g:a:1"))).toBe("g:a:1");
});
});
+188
Переглянути файл
@@ -0,0 +1,188 @@
/**
* Dependency Analyzer model: the artifacts of a Maven module's dependency tree
* (read with `dependency:tree -Dverbose`, so it also lists the occurrences Maven
* omitted), which of them conflict, and every path that brings them in.
*/
import type { ArtifactKey, MavenDependency } from "@/platform/ipc";
/** One occurrence of an artifact in the tree, with the path from a direct dependency down to it. */
export interface DependencyUsage {
/** `path[0]` is the module's direct dependency, the last element the occurrence. */
path: MavenDependency[];
dependency: MavenDependency;
}
export interface AnalyzedArtifact {
/** `groupId:artifactId[:classifier]`. */
key: string;
groupId: string;
artifactId: string;
classifier: string | null;
/** Version on the classpath; `null` when every occurrence was omitted. */
version: string | null;
/** Scope of the resolved occurrence (else of the first one). */
scope: string;
/** Distinct versions asked for (before conflict resolution and dependency management). */
requested: string[];
/** Several versions were asked for and some lost. */
conflict: boolean;
usages: DependencyUsage[];
}
export interface AnalyzerFilter {
query: string;
conflictsOnly: boolean;
/** `null` = any scope. */
scope: string | null;
}
export const artifactKey = (d: Pick<MavenDependency, "groupId" | "artifactId" | "classifier">) =>
[d.groupId, d.artifactId, d.classifier].filter(Boolean).join(":");
/** `groupId:artifactId[:classifier]:version`. */
export function coordinates(d: Pick<MavenDependency, "groupId" | "artifactId" | "classifier" | "version">): string {
return [d.groupId, d.artifactId, d.classifier, d.version].filter(Boolean).join(":");
}
const isResolved = (d: MavenDependency) => d.omitted == null;
/** The version a usage asked for: before `<dependencyManagement>` replaced it, if it did. */
export const requestedVersion = (d: MavenDependency) => d.managedFrom ?? d.version ?? null;
/** Every artifact of `deps` (a module's dependency tree), sorted by key. */
export function analyze(deps: readonly MavenDependency[]): AnalyzedArtifact[] {
const byKey = new Map<string, AnalyzedArtifact>();
const walk = (list: readonly MavenDependency[], parents: MavenDependency[]) => {
for (const d of list) {
const path = [...parents, d];
const key = artifactKey(d);
let a = byKey.get(key);
if (!a) {
a = {
key,
groupId: d.groupId,
artifactId: d.artifactId,
classifier: d.classifier ?? null,
version: null,
scope: d.scope,
requested: [],
conflict: false,
usages: [],
};
byKey.set(key, a);
}
a.usages.push({ path, dependency: d });
if (isResolved(d) && a.version == null) {
a.version = d.version ?? null;
a.scope = d.scope;
}
const requested = requestedVersion(d);
if (requested && !a.requested.includes(requested)) a.requested.push(requested);
if (d.omitted === "conflict") a.conflict = true;
walk(d.children, path);
}
};
walk(deps, []);
return [...byKey.values()].sort((x, y) => x.key.localeCompare(y.key));
}
/** Scopes used in the tree, in Maven's order. */
export function scopesOf(artifacts: readonly AnalyzedArtifact[]): string[] {
const order = ["compile", "provided", "runtime", "test", "system", "import"];
const found = new Set(artifacts.flatMap((a) => a.usages.map((u) => u.dependency.scope)));
return [...found].sort((x, y) => (order.indexOf(x) + 1 || 99) - (order.indexOf(y) + 1 || 99) || x.localeCompare(y));
}
function matchesQuery(d: Pick<MavenDependency, "groupId" | "artifactId" | "classifier" | "version">, query: string) {
const q = query.trim().toLowerCase();
return !q || coordinates(d).toLowerCase().includes(q);
}
export function filterArtifacts(artifacts: readonly AnalyzedArtifact[], f: AnalyzerFilter): AnalyzedArtifact[] {
return artifacts.filter(
(a) =>
(!f.conflictsOnly || a.conflict) &&
(f.scope == null || a.usages.some((u) => u.dependency.scope === f.scope)) &&
(matchesQuery(a, f.query) || a.requested.some((v) => matchesQuery({ ...a, version: v }, f.query))),
);
}
/** A node of the tree view; `key` is unique (index path). */
export interface DependencyTreeNode {
key: string;
dependency: MavenDependency;
children: DependencyTreeNode[];
}
/**
* The tree view: nodes that pass the filter, with their ancestors (so every match keeps
* its path), and every descendant of a match when no filter narrows them.
*/
export function filterTree(
deps: readonly MavenDependency[],
f: AnalyzerFilter,
conflicted: ReadonlySet<string>,
): DependencyTreeNode[] {
const narrowing = f.conflictsOnly || f.scope != null || !!f.query.trim();
const passes = (d: MavenDependency) =>
(!f.conflictsOnly || conflicted.has(artifactKey(d))) &&
(f.scope == null || d.scope === f.scope) &&
matchesQuery(d, f.query);
const build = (list: readonly MavenDependency[], parent: string): DependencyTreeNode[] =>
list.flatMap((dependency, i) => {
const key = `${parent}/${i}`;
const children = build(dependency.children, key);
return !narrowing || passes(dependency) || children.length ? [{ key, dependency, children }] : [];
});
return build(deps, "");
}
export type UsageStatus =
| { kind: "resolved"; version: string | null; managedFrom: string | null }
| { kind: "conflict"; version: string | null; winner: string | null }
| { kind: "duplicate"; version: string | null }
| { kind: "cycle"; version: string | null };
export function usageStatus(d: MavenDependency): UsageStatus {
const version = d.version ?? null;
switch (d.omitted) {
case "conflict":
return { kind: "conflict", version, winner: d.conflictWith ?? null };
case "duplicate":
return { kind: "duplicate", version };
case "cycle":
return { kind: "cycle", version };
default:
return { kind: "resolved", version, managedFrom: d.managedFrom ?? null };
}
}
/** Human-readable status, e.g. `omitted for conflict with 3.12.0`. */
export function statusText(s: UsageStatus): string | null {
switch (s.kind) {
case "conflict":
return s.winner ? `omitted for conflict with ${s.winner}` : "omitted for conflict";
case "duplicate":
return "omitted for duplicate";
case "cycle":
return "omitted for cycle";
default:
return s.managedFrom ? `version managed from ${s.managedFrom}` : null;
}
}
/** What Exclude on `usage` adds: an exclusion of the occurrence to the direct dependency bringing it in. */
export function exclusionFor(usage: DependencyUsage): { dependency: ArtifactKey; exclusion: ArtifactKey } | null {
const [direct] = usage.path;
if (!direct || usage.path.length < 2) return null;
return {
dependency: { groupId: direct.groupId, artifactId: direct.artifactId },
exclusion: { groupId: usage.dependency.groupId, artifactId: usage.dependency.artifactId },
};
}
/** The resolved usage first, then the ones that lost a conflict, then the rest; shorter paths first. */
export function sortedUsages(usages: readonly DependencyUsage[]): DependencyUsage[] {
const rank = (u: DependencyUsage) => (isResolved(u.dependency) ? 0 : u.dependency.omitted === "conflict" ? 1 : 2);
return [...usages].sort((a, b) => rank(a) - rank(b) || a.path.length - b.path.length);
}
+54 -1
Переглянути файл
@@ -7,14 +7,23 @@ import { registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { onIdeEvent, type BuildModel, type BuildTool } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { registerOverlay, registerRunAnythingProvider, registerToolWindow } from "@/workbench/contributions";
import {
registerEditorKind,
registerMenuGroup,
registerOverlay,
registerRunAnythingProvider,
registerToolWindow,
} from "@/workbench/contributions";
import { lazyComponent } from "@/ui";
import { GradleView, MavenView } from "./BuildToolView";
import { ExecutePopupHost } from "./ExecutePopup";
import { buildToolsRunAnything } from "./runAnything";
import { expandableKeys, gradleChildren, gradleRoots, mavenChildren, mavenRoots } from "./model";
import {
ANALYZER_KIND,
cancelSync,
loadModel,
openAnalyzer,
resetBuild,
setExpanded,
syncTool,
@@ -45,6 +54,19 @@ function openExecute(tool: BuildTool) {
useBuild.setState({ executeOpen: tool });
}
/** Project-relative `pom` of a Maven project from an action argument: `{ pom }`, or `{ path }` of a pom.xml. */
function analyzerPom(arg: unknown): string | null {
const { model, root, current } = useBuild.getState();
const projects = model?.maven?.projects ?? [];
const a = (arg ?? {}) as { pom?: unknown; path?: unknown };
if (typeof a.pom === "string") return a.pom;
if (typeof a.path === "string" && root) {
const rel = a.path.startsWith(`${root}/`) ? a.path.slice(root.length + 1) : a.path;
if (projects.some((p) => p.pom === rel)) return rel;
}
return current.maven ?? null;
}
const synced = new Set<string>();
/** Registers / unregisters the tool windows to match the model; first sync of a never-synced build. */
@@ -85,6 +107,27 @@ export function activate(): () => void {
const disposers: Array<() => void> = [
registerOverlay({ id: "build-tools.execute", component: ExecutePopupHost }),
registerRunAnythingProvider(buildToolsRunAnything),
registerEditorKind({
kind: ANALYZER_KIND,
component: lazyComponent(() => import("./DependencyAnalyzer").then((m) => m.DependencyAnalyzer)),
title: () => "Dependency Analyzer",
icon: () => "build-dependencies",
restorable: true,
}),
// pom.xml in the editor, its tab and the project view: Analyze Dependencies of that module.
registerMenuGroup({
id: "maven.analyzeDependencies",
menus: ["editor", "editorTab", "projectView"],
order: 30,
items: (_menu, { paths, dirs }) => {
const path = paths.length === 1 && !dirs?.[0] ? paths[0]! : null;
if (!path || !path.endsWith("/pom.xml")) return [];
const { model, root } = useBuild.getState();
const pom = root && path.startsWith(`${root}/`) ? path.slice(root.length + 1) : null;
if (!pom || !model?.maven?.projects.some((p) => p.pom === pom)) return [];
return [{ kind: "action", action: "maven.analyzeDependencies", arg: { pom }, label: "Analyze Dependencies…" }];
},
}),
useBuild.subscribe((s, prev) => {
if (s.model !== prev.model || s.root !== prev.root) apply(s.root ? s.model : null, registered);
}),
@@ -130,6 +173,16 @@ export function activate(): () => void {
keywords: ["maven", "mvn", "goal", "run anything"],
run: () => openExecute("maven"),
},
{
id: "maven.analyzeDependencies",
title: "Analyze Dependencies…",
description: "Shows a Maven module's dependency tree, version conflicts and where each library comes from",
category: "Maven",
icon: "build-dependencies",
when: MAVEN_WHEN,
keywords: ["maven", "dependency", "dependencies", "conflict", "tree", "exclude", "analyzer"],
run: ({ arg }) => openAnalyzer(analyzerPom(arg)),
},
{
id: "maven.toggleOffline",
title: "Toggle Offline Mode",
+10 -7
Переглянути файл
@@ -181,8 +181,10 @@ export function mavenChildren(node: BuildNode, model: MavenModel, configs: reado
}));
case "dependencies":
return dependencyNodes(node.key, node.dependencies);
case "dependency":
return node.dependency.children.length ? dependencyNodes(node.key, node.dependency.children) : undefined;
case "dependency": {
const kids = dependencyNodes(node.key, node.dependency.children);
return kids.length ? kids : undefined;
}
case "runConfigs":
return node.configs.map((config) => ({ kind: "runConfig", key: `${node.key}:${config.id}`, config }));
default:
@@ -190,12 +192,13 @@ export function mavenChildren(node: BuildNode, model: MavenModel, configs: reado
}
}
/** The resolved dependencies; occurrences Maven omitted are shown by the Dependency Analyzer only. */
function dependencyNodes(parent: string, deps: readonly MavenDependency[]): BuildNode[] {
return deps.map((dependency, i) => ({
kind: "dependency",
key: `${parent}/${dependency.groupId}:${dependency.artifactId}:${i}`,
dependency,
}));
return deps.flatMap((dependency, i) =>
dependency.omitted == null
? [{ kind: "dependency" as const, key: `${parent}/${dependency.groupId}:${dependency.artifactId}:${i}`, dependency }]
: [],
);
}
// ---------------------------------------------------------------------------
+16 -1
Переглянути файл
@@ -22,7 +22,7 @@ import {
} from "@/platform/ipc";
import { downloadJdkActions } from "@/platform/jdk";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { editorService, notifications } from "@/workbench/contributions";
import { removeTask, upsertTask } from "@/workbench/tasks";
import { profilesList, type GradleRunOptions, type MavenRunOptions } from "./model";
@@ -232,6 +232,7 @@ export function cancelSync(tool: BuildTool) {
export function resetBuild() {
generation++;
useAnalyzer.setState({ pom: null });
for (const tool of ["maven", "gradle"] as const) {
cancelSync(tool);
removeTask(`build-sync:${tool}`);
@@ -269,3 +270,17 @@ export function setExpanded(tool: BuildTool, expanded: Set<string>) {
export function setCurrentProject(tool: BuildTool, id: string | undefined) {
if (useBuild.getState().current[tool] !== id) useBuild.setState((s) => ({ current: { ...s.current, [tool]: id } }));
}
// ---------------------------------------------------------------------------
// Dependency Analyzer (an editor tab)
export const ANALYZER_KIND = "maven.dependencyAnalyzer";
/** Module the Dependency Analyzer shows (`pom`, project-relative); `null` = the first one. */
export const useAnalyzer = create<{ pom: string | null }>(() => ({ pom: null }));
/** Opens (or focuses) the Dependency Analyzer tab, showing the module `pom` when given. */
export async function openAnalyzer(pom: string | null) {
if (pom) useAnalyzer.setState({ pom });
await editorService().openInput({ kind: ANALYZER_KIND, key: ANALYZER_KIND, data: {} }, { focus: true });
}
+3 -2
Переглянути файл
@@ -27,6 +27,7 @@ import {
type HierarchyNode,
} from "./hierarchy";
import styles from "./HierarchyView.module.css";
import { tx } from "@/platform/i18n";
type Node = { kind: "root"; id: string } | { kind: "item"; id: string; node: HierarchyNode };
@@ -78,7 +79,7 @@ function HierarchyToolbar() {
icon="arrow-up"
size="small"
iconSize={16}
title={`${directionLabel(mode, "incoming")} Hierarchy`}
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
pressed={direction === "incoming"}
onClick={() => setDirection("incoming")}
/>
@@ -86,7 +87,7 @@ function HierarchyToolbar() {
icon="arrow-down"
size="small"
iconSize={16}
title={`${directionLabel(mode, "outgoing")} Hierarchy`}
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
pressed={direction === "outgoing"}
onClick={() => setDirection("outgoing")}
/>
+4 -3
Переглянути файл
@@ -7,6 +7,7 @@ import { downloadJdkActions } from "@/platform/jdk";
import { relativePath, useProject } from "@/platform/project";
import { STATUS_LABEL, restartServer, serversSummary, useServers } from "./servers";
import styles from "./ServerStatus.module.css";
import { tx } from "@/platform/i18n";
export function ServerStatus() {
const map = useServers((s) => s.servers);
@@ -23,7 +24,7 @@ export function ServerStatus() {
<BarButton
ref={ref}
aria-expanded={open}
aria-label={`Language servers: ${summary.text}`}
aria-label={tx`Language servers: ${summary.text}`}
tooltip="Language servers"
onClick={() => setOpen((v) => !v)}
>
@@ -65,7 +66,7 @@ export function ServerStatus() {
) : s.status === "missing" && canInstall ? (
<Button
size="small"
aria-label={`Install ${s.name}`}
aria-label={tx`Install ${s.name}`}
onClick={() => {
setOpen(false);
void executeAction("tools.install", s.name);
@@ -77,7 +78,7 @@ export function ServerStatus() {
<IconButton
icon="refresh"
size="small"
title={`Restart ${s.name}`}
title={tx`Restart ${s.name}`}
disabled={s.status === "missing" || s.status === "starting"}
onClick={() => void restartServer(s.id)}
/>
+4 -5
Переглянути файл
@@ -1,17 +1,16 @@
/** "problems" file decorations: files with errors (and their folders) get IDEA's red underline. */
import { setFileDecorations, type FileDecoration } from "@/workbench/contributions";
import { countSeverities, fileDiagnostics, useProblems, type ProblemsMap } from "./problemsStore";
import { tx } from "@/platform/i18n";
export function problemDecorations(map: ProblemsMap): Map<string, FileDecoration> {
const out = new Map<string, FileDecoration>();
for (const path of map.keys()) {
const c = countSeverities(fileDiagnostics(map, path));
if (!c.error) continue;
out.set(path, {
error: true,
propagate: true,
tooltip: `${c.error} ${c.error === 1 ? "error" : "errors"}${c.warning ? `, ${c.warning} ${c.warning === 1 ? "warning" : "warnings"}` : ""}`,
});
const errors = c.error === 1 ? tx`${c.error} error` : tx`${c.error} errors`;
const warnings = !c.warning ? "" : c.warning === 1 ? tx`${c.warning} warning` : tx`${c.warning} warnings`;
out.set(path, { error: true, propagate: true, tooltip: warnings ? `${errors}, ${warnings}` : errors });
}
return out;
}
+2 -1
Переглянути файл
@@ -7,6 +7,7 @@ import { call, commands, isTauri, type InstallCommand, type RunConfig } from "@/
import { notifications, toolWindowService, type ExecutorLaunch, type RunExecutorContribution } from "@/workbench/contributions";
import { coverageSupports, formatPercent } from "./model";
import { addSuite } from "./store";
import { tx } from "@/platform/i18n";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
@@ -47,7 +48,7 @@ export function notifyMissingTool(
level: "warning",
key: `${group}-missing-${tool}`,
title: `${tool} is not installed`,
body: line ? `${missing.message} Install it with: ${line}` : missing.homepage ? `${missing.message} ${missing.homepage}` : missing.message,
body: line ? tx`${missing.message} Install it with: ${line}` : missing.homepage ? `${missing.message} ${missing.homepage}` : missing.message,
sticky: true,
actions,
});
+4 -3
Переглянути файл
@@ -8,6 +8,7 @@ import { CodePreview } from "./CodePreview";
import { guessSeparator, importEdits, parseDelimited } from "./model";
import { closeDialog, detailsKey, loadDetails, openConsoleWith, targetLabel, useDatabase } from "./store";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
function when(t: number): string {
const d = new Date(t);
@@ -60,7 +61,7 @@ export function HistoryDialog({ id, path }: { id: string; path: string | null })
<Dialog
open
onClose={closeDialog}
title={`${targetLabel(id)} Query History`}
title={tx`${targetLabel(id)} Query History`}
width={820}
footerStart={
<IconButton icon="trash" title="Clear History" disabled={!entries?.length} onClick={() => void remove(null)} />
@@ -192,12 +193,12 @@ export function ImportDialog({ id, schema, table }: { id: string; schema: string
<Dialog
open
onClose={closeDialog}
title={`Import Data into ${schema}.${table}`}
title={tx`Import Data into ${schema}.${table}`}
width={720}
buttons={[
{ label: "Cancel", role: "cancel" },
{
label: `Import ${edits.length} Rows`,
label: tx`Import ${edits.length} Rows`,
role: "default",
disabled: !edits.length || !mapped.length || busy,
onClick: () => void run(),
+4 -3
Переглянути файл
@@ -21,6 +21,7 @@ import {
} from "./resultView";
import { openDialog } from "./store";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
export type DataPanel = "record" | "value" | "aggregates";
@@ -30,7 +31,7 @@ export function exportMenu(data: ExportData, source: string, format?: ExportForm
{ label: "Export Data…", icon: "export", run: () => openDialog({ kind: "export", data, source, format }) },
{ kind: "separator" },
...EXPORT_FORMATS.map((f): MenuItem => ({
label: `Copy as ${f.label}`,
label: tx`Copy as ${f.label}`,
icon: "copy",
run: () => void navigator.clipboard?.writeText(exportData(f.id, data)),
})),
@@ -207,14 +208,14 @@ function FilterPopup(props: {
anchor={props.anchor}
placement="bottom-start"
onClose={props.onClose}
aria-label={`Local filter of ${props.column}`}
aria-label={tx`Local filter of ${props.column}`}
className={styles.filterPopup}
trapFocus
>
<Input
autoFocus
aria-label="Search values"
placeholder={`Values of ${props.column}`}
placeholder={tx`Values of ${props.column}`}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
+3 -2
Переглянути файл
@@ -7,6 +7,7 @@ import { SourceDialog } from "./SourceDialog";
import { closeDialog, useDatabase } from "./store";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
import { tx } from "@/platform/i18n";
const ObjectDialogs = lazyComponent(() => import("./ObjectDialogs").then((m) => m.ObjectDialogs));
const ExportDialog = lazyComponent(() => import("./ExportDialog").then((m) => m.ExportDialog));
@@ -28,7 +29,7 @@ function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok:
<Dialog
open
onClose={() => done(false)}
title={`Connect to ${source.name}`}
title={tx`Connect to ${source.name}`}
width={400}
buttons={[
{ label: "Cancel", role: "cancel" },
@@ -82,7 +83,7 @@ function SshSecretDialog({
<Dialog
open
onClose={() => done(false)}
title={`SSH: ${sshLabel(source) || source.name}`}
title={tx`SSH: ${sshLabel(source) || source.name}`}
width={440}
buttons={[
{ label: "Cancel", role: "cancel" },
+2 -1
Переглянути файл
@@ -38,6 +38,7 @@ import {
} from "./store";
import { openTableData } from "./treeActions";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
/** Read-only SQL with the editor's syntax colours (IDEA's dialog Preview pane). */
function SqlPreview({ sql, label = "Preview" }: { sql: string; label?: string }) {
@@ -287,7 +288,7 @@ function ModifyTableDialog(props: ModifyProps) {
<Dialog
open
onClose={closeDialog}
title={`Modify Table ${table}`}
title={tx`Modify Table ${table}`}
width={440}
buttons={[{ label: "Cancel", role: "cancel" }]}
>
+16 -10
Переглянути файл
@@ -17,7 +17,7 @@ import {
type DbSslMode,
type DbTxMode,
} from "@/platform/ipc";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { tx, useTx, useTxTemplate } from "@/platform/i18n";
import { Button, Checkbox, Dialog, IconButton, Input, Select, Tabs, T, type SelectOption } from "@/ui";
import { colorVar, connectRemedy, fileSourceName, newSourceId, parseSourceUrl, sshLabel } from "./model";
import { closeDialog, loadDatabases, loadSchemas, saveSource, useDatabase } from "./store";
@@ -224,7 +224,7 @@ function SecondsOption({
<Input
className={styles.secondsInput}
inputMode="numeric"
aria-label={`${label} (seconds)`}
aria-label={tx`${label} (seconds)`}
disabled={!on}
value={draft}
onChange={(e) => {
@@ -243,14 +243,18 @@ function SecondsOption({
/** Schemas tab: "All …" or a choice of names and `*` / `?` patterns. */
function NamePicker({
title,
allLabel,
addLabel,
all,
chosen,
known,
onAll,
onChosen,
}: {
title: string;
/** "All databases" */
allLabel: string;
/** Accessible name of the pattern input. */
addLabel: string;
all: boolean;
chosen: string[];
known: string[];
@@ -266,7 +270,7 @@ function NamePicker({
};
return (
<div className={styles.namePicker}>
<Checkbox checked={all} onChange={onAll} label={`All ${title}`} />
<Checkbox checked={all} onChange={onAll} label={allLabel} />
{!all && (
<div className={styles.nameList}>
{names.map((n) => (
@@ -282,7 +286,7 @@ function NamePicker({
className={styles.fill}
value={pattern}
placeholder="Name or pattern, e.g. app_*"
aria-label={`Add ${title} pattern`}
aria-label={addLabel}
onChange={(e) => setPattern(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !isImeKey(e.nativeEvent)) {
@@ -401,7 +405,7 @@ export function SourceDialog({
setTest(null);
try {
const v = await call(commands.dbTest(effective(), password ?? null, sshOn ? (sshSecret ?? null) : null));
setTest({ ok: true, text: `Succeeded: ${v}` });
setTest({ ok: true, text: tx`Succeeded: ${v}` });
} catch (e) {
const text = e instanceof Error ? e.message : String(e);
const trust = e instanceof IpcError && connectRemedy(e.kind, e.message) === "trustHostKey";
@@ -802,7 +806,8 @@ export function SourceDialog({
<div className={styles.formWide}>
{postgres && (
<NamePicker
title="databases"
allLabel={tx("All databases")}
addLabel={tx("Add databases pattern")}
all={intro.allDatabases !== false}
chosen={intro.databases ?? []}
known={knownDbs}
@@ -811,7 +816,8 @@ export function SourceDialog({
/>
)}
<NamePicker
title={s.driver === "mysql" ? "schemas (databases)" : "schemas"}
allLabel={s.driver === "mysql" ? tx("All schemas (databases)") : tx("All schemas")}
addLabel={s.driver === "mysql" ? tx("Add schemas (databases) pattern") : tx("Add schemas pattern")}
all={intro.allSchemas !== false}
chosen={intro.schemas ?? []}
known={knownSchemas}
@@ -921,7 +927,7 @@ export function SourceDialog({
<Dialog
open
onClose={closeDialog}
title={initial ? `Data Source: ${initial.name}` : "New Data Source"}
title={initial ? tx`Data Source: ${initial.name}` : "New Data Source"}
width={640}
footerStart={
<Button onClick={() => void runTest()} disabled={busy || !valid}>
+2 -1
Переглянути файл
@@ -29,6 +29,7 @@ import {
import { openDialog, sourceById, withConnection } from "./store";
import type { TableRef } from "./tableInput";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
const PAGE_SIZES = ["100", "500", "1000", "5000"];
@@ -306,7 +307,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
) : (
<div className={styles.fill}>
<DataView
aria-label={`${ref.table} data`}
aria-label={tx`${ref.table} data`}
columns={gridColumns}
rowCount={rowCount}
fixedRows={loaded}
+2 -1
Переглянути файл
@@ -58,6 +58,7 @@ import {
useDatabase,
} from "./store";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
@@ -287,7 +288,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
<Select
aria-label="Row limit"
value={String(maxRows)}
options={ROW_LIMITS.map((v) => ({ value: v, label: `${Number(v).toLocaleString("en")} rows` }))}
options={ROW_LIMITS.map((v) => ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))}
onChange={(v) => useDatabase.setState({ maxRows: Number(v) })}
/>
<span className={styles.toolbarSeparator} />
+4 -3
Переглянути файл
@@ -38,6 +38,7 @@ import type { ExportData, ExportFormat } from "./export";
import type { DbObjectRef } from "./objects";
import { formatted } from "./sql/format";
import { bindParams, findParams } from "./sql/params";
import { tx } from "@/platform/i18n";
export const DB_TOOL_WINDOW = "database";
export const RESULTS_VIEW = "dbResults";
@@ -281,7 +282,7 @@ export async function renameSource(id: string, name: string): Promise<void> {
export async function removeSource(source: DataSource): Promise<void> {
const ok = await confirm({
title: "Remove Data Source",
message: `Remove data source '${source.name}'? Its query console file stays on disk.`,
message: tx`Remove data source '${source.name}'? Its query console file stays on disk.`,
ok: "Remove",
});
if (!ok) return;
@@ -788,7 +789,7 @@ export async function executeConsole(
.filter((o) => o.result?.columns.length)
.map((outcome) => {
const n = nextTab++;
return { id: n, title: `Result ${n}`, path, sourceId: id, outcome };
return { id: n, title: tx`Result ${n}`, path, sourceId: id, outcome };
});
const failed = outcomes.some((o) => o.error);
useDatabase.setState((s) => ({
@@ -957,7 +958,7 @@ export async function finishTransaction(id: string, commit: boolean): Promise<bo
async function askEndTransaction(source: DataSource): Promise<boolean | null> {
const { button } = await ask({
title: "Switch to Auto-Commit",
body: `${source.name} has uncommitted changes. Commit or roll them back before switching to auto-commit?`,
body: tx`${source.name} has uncommitted changes. Commit or roll them back before switching to auto-commit?`,
buttons: [
{ id: "rollback", label: "Roll Back" },
{ id: "commit", label: "Commit", primary: true },
+8 -6
Переглянути файл
@@ -37,6 +37,7 @@ import {
removeSource,
} from "./store";
import { tableInput } from "./tableInput";
import { tx } from "@/platform/i18n";
/** Context key: the Database tree has focus. */
export const DB_VIEW_FOCUS = "databaseViewFocus";
@@ -57,11 +58,12 @@ function sourceOf(n: DbNode | null): DataSource | undefined {
return n ? sourceById(nodeTarget(n)) : undefined;
}
async function copy(text: string, what: string) {
/** Copies `text`; `failure` is the notification title when the clipboard refuses it. */
async function copy(text: string, failure: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
notifications().notify({ level: "error", title: `Cannot copy the ${what}` });
notifications().notify({ level: "error", title: failure });
}
}
@@ -373,10 +375,10 @@ export function registerDatabaseTreeActions(): () => void {
const n = nodeFrom(arg);
if (!n) return;
const id = nodeTarget(n);
if (n.kind === "source") return void copy(n.source.name ?? "", "name");
if (n.kind === "database") return void copy(n.name, "name");
if (n.kind === "source") return void copy(n.source.name ?? "", tx("Cannot copy the name"));
if (n.kind === "database") return void copy(n.name, tx("Cannot copy the name"));
const o = objectOf(n);
if (id && o) void copy(reference(driverOf(id), o), "reference");
if (id && o) void copy(reference(driverOf(id), o), tx("Cannot copy the reference"));
},
}),
tree({
@@ -397,7 +399,7 @@ export function registerDatabaseTreeActions(): () => void {
run: async ({ arg }) => {
const n = nodeFrom(arg);
const ddl = n && (await ddlOf(n));
if (ddl) await copy(ddl.text, "DDL");
if (ddl) await copy(ddl.text, tx("Cannot copy the DDL"));
},
}),
tree({
+2 -1
Переглянути файл
@@ -43,6 +43,7 @@ import {
openSmartStepChooser,
useOverlays,
} from "./ui/popoverStore";
import { tx } from "@/platform/i18n";
function isRunConfig(arg: unknown): arg is RunConfig {
return !!arg && typeof arg === "object" && "command" in arg && "args" in arg && "debugAdapter" in arg;
@@ -159,7 +160,7 @@ async function listenForJvm(name: string, host: string, port: number): Promise<n
key,
sticky: true,
title: `'${name}': listening for the remote JVM on port ${port}`,
body: `Start the remote JVM with -agentlib:jdwp=transport=dt_socket,server=n,address=${host}:${port},suspend=y`,
body: tx`Start the remote JVM with -agentlib:jdwp=transport=dt_socket,server=n,address=${host}:${port},suspend=y`,
actions: [{ label: "Cancel", run: () => void commands.cancelRequest(request) }],
});
try {
+2 -1
Переглянути файл
@@ -8,6 +8,7 @@
import { call, commands, isTauri, type DebugEvent, type DebugSessionId } from "@/platform/ipc";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { isLive, useDebug, type DebugSession } from "./state";
import { tx } from "@/platform/i18n";
const KEY = "debug.hotswap";
/** `BUILD_COMPLETE` events of our own build are not worth a prompt. */
@@ -25,7 +26,7 @@ function plural(n: number, word: string) {
export function hotSwapMessage(changed: number, errors: string[]): { level: "info" | "error"; title: string; body?: string } {
if (errors.length) return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
if (changed === 0) return { level: "info", title: "Loaded classes are up to date. Nothing to reload." };
return { level: "info", title: `${plural(changed, "class")} reloaded` };
return { level: "info", title: tx`${plural(changed, "class")} reloaded` };
}
/** Compiles (unless `build` is false) and reloads changed classes into every Java debug session. */
+7 -7
Переглянути файл
@@ -5,11 +5,11 @@
import { IpcError } from "@/platform/ipc";
/** Adapters the tools installer can provide (adapter id → tool name). */
const INSTALLABLE: Record<string, { tool: string; label: string }> = {
debugpy: { tool: "debugpy", label: "debugpy" },
"js-debug": { tool: "js-debug", label: "the JavaScript debugger (vscode-js-debug)" },
delve: { tool: "delve", label: "Delve" },
codelldb: { tool: "codelldb", label: "CodeLLDB" },
const INSTALLABLE: Record<string, { tool: string; title: string }> = {
debugpy: { tool: "debugpy", title: "debugpy is not installed" },
"js-debug": { tool: "js-debug", title: "The JavaScript debugger (vscode-js-debug) is not installed" },
delve: { tool: "delve", title: "Delve is not installed" },
codelldb: { tool: "codelldb", title: "CodeLLDB is not installed" },
};
export interface MissingAdapter {
@@ -25,14 +25,14 @@ export function missingAdapter(adapter: string, e: unknown): MissingAdapter | nu
if (adapter === "debugpy" && e.message.startsWith("debugpy is not installed")) {
return {
tool: entry.tool,
title: "debugpy is not installed",
title: entry.title,
body: `${e.message}. OpenIDEA can install a private copy that every Python interpreter uses for debugging.`,
};
}
if (!e.message.startsWith(`debug adapter \`${adapter}\` not found`)) return null;
return {
tool: entry.tool,
title: `${entry.label[0]!.toUpperCase()}${entry.label.slice(1)} is not installed`,
title: entry.title,
body: e.message,
};
}
+2 -1
Переглянути файл
@@ -40,6 +40,7 @@ import {
} from "../state";
import { VariablesView, type VarRoot } from "./VariablesView";
import styles from "./DebugToolWindow.module.css";
import { tx } from "@/platform/i18n";
function useActionEnabled(id: string): boolean {
const ctx = useContextKeys();
@@ -114,7 +115,7 @@ export function DebugTabs() {
if (!list.length) return null;
const items: TabItem[] = list.map((s) => ({
id: String(s.id),
label: s.parent != null ? `${s.name} (child)` : s.name,
label: s.parent != null ? tx`${s.name} (child)` : s.name,
text: s.name,
icon: "debug",
italic: s.status === "terminated",
+3 -2
Переглянути файл
@@ -34,6 +34,7 @@ import { VariablesView, type VarRoot } from "./VariablesView";
import { pushHistory, readHistory } from "./expressionHistory";
import styles from "./Overlays.module.css";
import { isImeKey } from "@/platform/ime";
import { tx } from "@/platform/i18n";
export function DebuggerOverlays() {
return (
@@ -447,7 +448,7 @@ function BreakpointsDialog() {
<Checkbox
checked={r.bp.enabled}
onChange={(enabled) => updateSpecial(r.bp.id, { enabled })}
aria-label={`Enable ${specialTitle(r.bp)}`}
aria-label={tx`Enable ${specialTitle(r.bp)}`}
/>
<Icon name={r.bp.kind === "method" ? "breakpoint-method" : "breakpoint-field"} size={14} />
<span className={styles.bpName}>{specialTitle(r.bp)}</span>
@@ -467,7 +468,7 @@ function BreakpointsDialog() {
<Checkbox
checked={r.bp.enabled}
onChange={(enabled) => updateBreakpoint(r.path, r.bp.id, { enabled })}
aria-label={`Enable breakpoint at ${basename(r.path)}:${r.bp.line + 1}`}
aria-label={tx`Enable breakpoint at ${basename(r.path)}:${r.bp.line + 1}`}
/>
<span
className={styles.bpDot}
+4 -3
Переглянути файл
@@ -35,6 +35,7 @@ import {
import { addComment, checkoutPullRequest, openCommentLocation, openFileDiff, openUrl, submitReview } from "./ops";
import { cancelBusy, loadDetails, refreshAll, select, setQuery, useGithub, type DetailTab } from "./store";
import styles from "./Github.module.css";
import { tx } from "@/platform/i18n";
const STATES: Array<{ value: PrStateFilter; label: string }> = [
{ value: "open", label: "Open" },
@@ -515,9 +516,9 @@ function Details() {
aria-label="Pull request"
items={[
{ id: "overview", label: "Overview" },
{ id: "files", label: `Files ${pr.files.length}` },
{ id: "commits", label: `Commits ${pr.commits.length}` },
{ id: "conversation", label: `Conversation ${pr.timeline.length + comments.length}` },
{ id: "files", label: tx`Files ${pr.files.length}` },
{ id: "commits", label: tx`Commits ${pr.commits.length}` },
{ id: "conversation", label: tx`Conversation ${pr.timeline.length + comments.length}` },
]}
/>
{tab === "overview" && <Overview pr={pr} />}
+3 -2
Переглянути файл
@@ -5,6 +5,7 @@ import type { ReviewEvent } from "@/platform/ipc";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Input, Select, T } from "@/ui";
import styles from "./Github.module.css";
import { tx } from "@/platform/i18n";
interface Entry {
id: number;
@@ -134,7 +135,7 @@ function CreateDialog(props: {
/>
<div className={styles.formRow}>
<Checkbox checked={draft} onChange={setDraft} label="Draft" />
<Checkbox checked={push} onChange={setPush} label={`Push '${props.head}' first`} />
<Checkbox checked={push} onChange={setPush} label={tx`Push '${props.head}' first`} />
</div>
</div>
</Dialog>
@@ -165,7 +166,7 @@ function ReviewDialog(props: {
return (
<Dialog
open
title={`Review #${props.number}`}
title={tx`Review #${props.number}`}
onClose={() => props.onDone(null)}
width={520}
buttons={[
+2 -1
Переглянути файл
@@ -10,6 +10,7 @@ import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, Spinner, T
import { bodyKind, formatMs, formatSize, prettyBody } from "./format";
import { cancelRunning, clearHistory, refreshHistory, selectEntry, useHttpClient } from "./store";
import styles from "./HttpClient.module.css";
import { tx } from "@/platform/i18n";
function statusTone(status: number | null | undefined): string {
if (status == null) return styles.statusError ?? "";
@@ -73,7 +74,7 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
onSelect={(id) => setTab(id as Tab)}
items={[
{ id: "body", label: "Response" },
{ id: "headers", label: `Headers${r ? ` (${r.headers.length})` : ""}` },
{ id: "headers", label: r ? tx`Headers (${r.headers.length})` : "Headers" },
{ id: "request", label: "Request" },
]}
trailing={
+31 -1
Переглянути файл
@@ -1,7 +1,8 @@
/**
* HTTP Client (IDEA's `.http` / `.rest` files): highlighting, ▶ gutter per
* request, environments, Run All, and a tool window with the responses and
* their history. Parsing, variable resolution and sending happen in Rust
* their history, and requests generated from Spring Web mappings in Java /
* Kotlin sources (`spring/`). Parsing, variable resolution and sending happen in Rust
* (`ide-http`).
*/
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
@@ -19,6 +20,15 @@ import { HTTP_LANGUAGE, httpEditorExtension, refreshRequests, requestAtCaret } f
import { HttpClientHeaderActions, HttpClientView } from "./HttpClientView";
import { httpLanguageDescription } from "./language";
import { SERVICE_VIEW, resetHttpClient, runAll, runRequest } from "./store";
import {
GENERATE_CONTROLLER_REQUESTS,
GENERATE_REQUEST,
generateAtCaret,
menuGroupItems,
springEditorExtension,
} from "./spring/editor";
const SPRING_WHEN = "editorLangId == java || editorLangId == kotlin";
export const NEW_REQUEST_TEMPLATE = `### Example request
# Variables come from http-client.env.json / http-client.private.env.json
@@ -105,6 +115,8 @@ export function activate(): () => void {
}),
registerLanguageMode(httpLanguageDescription),
registerEditorContribution({ id: "http.requests", order: 56, extensions: httpEditorExtension }),
registerEditorContribution({ id: "http.spring", order: 57, extensions: springEditorExtension }),
registerMenuGroup({ id: "http.spring", menus: ["editor"], order: 40, items: (_menu, ctx) => menuGroupItems(ctx) }),
registerServiceView({
id: SERVICE_VIEW,
title: "HTTP Client",
@@ -156,6 +168,24 @@ export function activate(): () => void {
else if (isTauri()) await newRequest(directory ?? undefined);
},
},
{
id: GENERATE_REQUEST,
title: "Generate Request in HTTP Client",
category: "Tools",
icon: "file-http",
keywords: ["spring", "request mapping", "rest", "endpoint", "http client"],
when: SPRING_WHEN,
run: () => generateAtCaret("endpoint"),
},
{
id: GENERATE_CONTROLLER_REQUESTS,
title: "Generate Requests for Controller",
category: "Tools",
icon: "file-http",
keywords: ["spring", "request mapping", "rest", "endpoints", "http client"],
when: SPRING_WHEN,
run: () => generateAtCaret("controller"),
},
{
id: "http.showToolWindow",
title: "HTTP Client",
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more