Compare commits

...
Author SHA1 Message Date
l0ng-ai 971b520399 feat(agents): fold shell commands that only read or search into exploration runs (#5898)
A shell command whose every segment only reads or searches (grep, rg, git grep, find, cat, sed -n, ls, git status/diff/log/show…) now joins the exploration run with reasoning and counts in its summary as a read or a search. Commands that may change something (builds, tests, writes, redirects, command substitution, unknown programs) still show on their own row. The leading cd parsing moves into the same module and is shared with command titles.
2026-11-25 20:39:48 +08:00
l0ng-ai c67363ec6b test(sdk): use an absolute temp path for the explicit Dart tool path (#5899)
'/opt/dart/bin/dart' is not absolute on Windows, so it resolved against the project root's drive and the Flutter SDK test failed on windows-latest. The test now uses an absolute path under the temp dir.
2026-11-25 20:37:09 +08:00
l0ng-ai 2568772700 perf(window): close project tabs in parallel and move teardown off the UI thread (#5882)
Quit, closing a tab group and Close Other/Left/Right Tabs now close their windows in parallel and hide them together in one frame; a window that needs to ask (unsaved changes, running processes, remote backend) takes the prompt turn and comes forward, so prompts still appear one at a time. Agent, terminal and process teardown moves off the UI thread into the project's background shutdown, idle agent tasks are no longer rewritten on close, and opening a project only waits for closes of overlapping roots.
2026-11-25 20:19:17 +08:00
l0ng-ai 536f85b9df feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854)
Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu.

## What changes

- **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path):
  - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`.
  - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`.

  The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone.
- **Outputs.** Every project writes to `<cache>/java-build/<build>/out/<group>.<name>/classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs.
- **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle.
- **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded).
  - A build compiles the changed sources.
  - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow.
  - Downstream sets follow an API change log.
  - A changed constant recompiles the set and everything compiled against it.
  - Sources a failed compile left behind stay dirty.
  - Sets whose annotation processors aggregate compile from scratch.
- **Build menu.**
  - Build Project and Build Module compile with the service.
  - Recompile compiles the file with the service and publishes javac's diagnostics.
- **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801.
- **When it applies.**
  - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on.
  - Gradle modules when Settings › Gradle › *Build and run using* is the IDE.
  - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles.
  - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below).
- **Fallback.** These go to the build tool's own build:
  - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds;
  - a failed prepare run.

The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`.

## Tests

- `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing):
  - first build, no-op build, only changed files recompile;
  - API changes reach dependents, including through subclasses and across modules;
  - constant changes recompile dependents;
  - resource changes run only the resources step;
  - deleted sources, compile errors with positions, the test source set;
  - Recompile and Build Project;
  - Gradle projects;
  - fallback for Gradle projects with other compilers;
  - plus class-file parsing, the API change log, javac options and Ant patterns.
- `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors.
- `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`.
- `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on.
2026-11-25 20:01:26 +08:00
l0ng-ai e5c5915f2e feat(agents): logos for every agent in the ACP registry (#5884)
Every agent in the ACP registry now shows its own logo instead of the generic agents icon. A provider's logo is looked up by id, with legacy and ACP-adapter ids (claude-acp, codex-acp, kimi-code, opencode-v2) sharing their agent's logo and Hermes profiles using Hermes'. The registry logos are listed in THIRD_PARTY_LICENSES.md.
2026-11-25 19:55:06 +08:00
l0ng-ai ca2bf89f86 feat(agents): drop the leading cd from command titles (#5890)
Command titles drop a leading `cd <dir> &&`; a folder other than the task's shows as a small tag before the command, with the full path on hover. The running-command hint in a grouped run's summary uses the same title.
2026-11-25 19:45:51 +08:00
l0ng-ai 735fe5dd30 feat(agents): show task status marks in a column beside the age (#5885)
The status mark (spinner, usage-limit clock, needs-input warning, ...) moves from right after the title to a fixed slot just before the age, so marks line up across rows regardless of title length. The age gets a minimum width so the column stays put between "now", "3m" and "12d".
2026-11-25 19:37:53 +08:00
l0ng-ai 0cfd17979b fix(agents): use spacing tokens for the session asset pill gaps (#5886)
The three gaps added to Session.module.css were raw 6px values, which the spacing-scale test rejects on main; they now use --space-1-5.
2026-11-25 19:30:01 +08:00
Deng Liuanddengliu 41165bb8c0 fix(ssh): migrate legacy saved credentials at startup (#5786)
Host startup now moves legacy plaintext SSH passwords and key passphrases from
ssh-passwords.json into the OS credential store, without waiting for the next
SSH connection. When the move cannot finish, each workbench shows a sticky
warning with Retry migration and a confirmed Remove plaintext copy, which keeps
credentials already moved. A credential that cannot be saved stays for the
session and the requesting window is warned. An unreadable ssh-passwords.json
is set aside (renamed, never deleted) like the other secret files, so it no
longer blocks saving new credentials.

Co-authored-by: dengliu <[email protected]>
2026-11-25 19:27:09 +08:00
l0ng-ai 91264713e7 fix(linux): use X11 under WSLg (#5748)
Started from a WSL shell, GTK opens WSLg's Wayland display, where Mesa has no usable GPU driver for WebKitGTK and the window stays blank. Under WSL (WSL_DISTRO_NAME or WSL_INTEROP set) with an X display available, OpenIDEA now sets GDK_BACKEND=x11 before GTK starts; an explicit GDK_BACKEND is kept, and nothing changes outside WSL.

Fixes #5178
2026-11-25 18:54:43 +08:00
l0ng-ai 71a4f7cb63 fix(windows): keep the WebView profile and logs in a custom data location (#5838)
With a custom local data directory (Settings > System Settings > Caches), the WebView2 profile and the logs now move there too. On Windows both window builders pass the local data directory, so all windows share one profile; an existing EBWebView profile is moved before the first window opens (rename on the same volume, otherwise a copy that skips browser caches), and a profile already in place is never replaced. Outside macOS logs go to <local data>/logs; OPENIDEA_LOG_DIR still wins.

Fixes #5776
2026-11-25 18:53:59 +08:00
l0ng-aiandenenH dfa632cf18 fix(terminal): bundle the ConPTY runtime on Windows (#5752)
Windows builds embed Microsoft's MIT-licensed ConPTY runtime (Microsoft.Windows.Console.ConPTY 1.25.260930003, pinned and unmodified, checksums tested), because the system ConPTY on Windows 10 19045 drops alternate-screen transitions and full-screen programs leave duplicate rows in scrollback. The runtime is written to a versioned user cache and conpty.dll is preloaded from that absolute path; terminals, Run consoles and debugger launchers share the PTY factory. Older builds or a load failure keep the system ConPTY.

Fixes #2692

Co-authored-by: enenH <[email protected]>
2026-11-25 18:53:47 +08:00
l0ng-ai f1425854fb fix(linux): paste files copied in the file manager into the project view (#5834)
On Linux the project view now reads and writes the clipboard's file list: text/uri-list (Dolphin, Nautilus and most file managers) with a fallback to GNOME's x-special/gnome-copied-files, through the GTK clipboard on X11 and Wayland. Copy offers both lists and the file names as text. file:// URIs are decoded as raw bytes; other hosts and schemes are skipped.

Fixes #5737
2026-11-25 18:53:34 +08:00
l0ng-ai 752650b971 fix(windows): show the WebView2 recovery prompt reliably and let windows close (#5705)
When the WebView2 browser process exits, the recovery prompt is now a native, topmost message box on its own thread with no owner window, so it no longer depends on the main thread or the failed window. Restart falls back to restarting the process itself if the event loop doesn't act within 10 s. Once the browser has failed, closing a window destroys it without asking the page. The log records the failure reason and process description.

Fixes #5369
2026-11-25 18:53:27 +08:00
l0ng-ai d33ee53c92 fix(windows): open a project window no larger than the screen's work area (#5817)
On Windows a project window opened at the configured 1440x900 and Restore Down returned to it, which ran under the taskbar on small or scaled screens (1920x1080 at 150%). The new window's size and minimum size are now shrunk to the primary monitor's work area.

Fixes #5750
2026-11-25 18:53:21 +08:00
l0ng-ai 57eac70018 fix(agents): drop the model settings chip's removed CSS class (#5881)
The composer's dynamic overflow (#5827) removed .modelDetail from Composer.module.css, but the model settings chip still read it, which failed the CSS module check. The chip now uses .chip alone.
2026-11-25 18:52:29 +08:00
l0ng-ai 497948eeff fix(flutter): compile the Flutter tests on Windows (#5880)
The process tests that use FlutterDaemon::with_executable and ToolServer::is_stopped only run on Unix, so on Windows both helpers were dead code and the ide-flutter test build failed under -D warnings. They are now compiled only for Unix tests.
2026-11-25 18:50:59 +08:00
137 changed files with 8154 additions and 339 deletions

No files matched your search

Generated
+4
View File
@@ -4252,16 +4252,20 @@ name = "ide-core"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"encoding_rs",
"libc",
"portable-pty",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"specta-typescript",
"tempfile",
"thiserror 2.0.21",
"tokio-util",
"tracing",
"windows-sys 0.61.2",
]
+18
View File
@@ -6,6 +6,24 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Agent logos
The `src/ui/openidea/agents/` logos of agents listed in the
[ACP agent registry](https://github.com/agentclientprotocol/registry) (`agoragentic-acp`, `amp-acp`,
`antigravity-acp`, `autohand`, `bob`, `cline`, `codebuddy-code`, `cortex-code`, `corust-agent`,
`crow-cli`, `deepagents`, `devin`, `dimcode`, `dirac`, `factory-droid`, `fast-agent`, `glm-acp-agent`,
`grok-build`, `harn`, `junie`, `kilo`, `kimchi`, `minimax-code`, `minion-code`, `muse-code`, `nova`,
`pi-acp`, `poolside`, `sigit`, `stakpak`, `vtcode`) are the registry's icons, with a root `fill`
moved onto a group. The registry is licensed under Apache-2.0; the logos remain trademarks of
their owners.
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
and [package provenance](crates/ide-core/resources/conpty/README.md).
## Project Lombok
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
+16 -5
View File
@@ -2291,14 +2291,25 @@ impl AgentManager {
}
}
/// Stops sending events to UI sinks (project closing).
pub fn detach_sinks(&self) {
self.shared.sinks.write().clear();
}
/// Stops every agent (project closed).
pub fn shutdown(&self) {
for task in self.tasks.read().values() {
task.kill();
// What arrived after the last save (a subagent's late updates).
task.persist();
self.detach_sinks();
let tasks: Vec<_> = self.tasks.read().values().cloned().collect();
for task in tasks {
let was_live = task.kill().is_some();
if was_live {
// Persist late subagent updates and cleared live background state.
task.persist();
} else {
// Flush pending delayed saves without rewriting untouched or archived tasks.
task.save();
}
}
self.shared.sinks.write().clear();
}
}
+41
View File
@@ -1632,6 +1632,47 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
}
/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed.
#[tokio::test]
async fn shutdown_skips_rewriting_untouched_restored_tasks() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let untouched = idle_task(&mgr, "untouched").await;
let archived = idle_task(&mgr, "archived").await;
mgr.archive(&archived.id).unwrap();
let dirty = idle_task(&mgr, "dirty").await;
mgr.shutdown();
let (untouched_path, archived_path, dirty_path) =
(task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id));
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0);
let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0);
let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0);
let dirty_handle = restored.task(&dirty.id).unwrap();
dirty_handle.state.lock().task.title = "updated".into();
dirty_handle.persist_soon();
restored.shutdown();
assert_eq!(
FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0),
before_untouched,
"untouched task should not be rewritten on shutdown"
);
assert_eq!(
FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0),
before_archived,
"archived task should not be rewritten on shutdown"
);
assert!(
FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty,
"pending persist_soon task must still be flushed on shutdown"
);
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
}
/// Archiving saves the task as it is, including changes nobody asked to be saved.
#[tokio::test]
async fn archiving_saves_the_task_before_it_returns() {
+7 -2
View File
@@ -6,7 +6,7 @@ use std::io::Read;
use std::time::SystemTime;
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
type Stamp = (u64, SystemTime, Option<String>);
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchFingerprint {
@@ -182,7 +182,7 @@ fn collect(
}
/// Scans every input, storing project inputs relative to the project.
pub(super) fn scan_all(
pub(crate) fn scan_all(
root: &Path,
inputs: Vec<PathBuf>,
cancel: &CancellationToken,
@@ -282,6 +282,11 @@ pub(super) fn module_fingerprint(
}
impl LaunchFingerprint {
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
LaunchFingerprint { version: 2, parameters, files }
}
/// Folders (relative to the project) of the Maven projects whose POM is an input.
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
self.files
+23 -1
View File
@@ -3,7 +3,7 @@
//! background with cancellation and parses the compiler output into messages
//! for the Build tool window, the Problems view and the editor.
mod fingerprint;
pub(crate) mod fingerprint;
mod launch_resources;
mod modules;
mod parse;
@@ -845,6 +845,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
projects
}
/// A step running Maven, its output parsed as Maven's.
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Maven)
}
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Gradle)
}
/// The linked reactor root building the project at `module` (project-relative).
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
maven_reactor(m, module)
}
/// The projects of the reactor `top`.
pub(crate) fn reactor_projects_of<'a>(
m: &'a maven::MavenModel,
top: &'a maven::MavenProject,
) -> Vec<&'a maven::MavenProject> {
reactor_projects(m, top)
}
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
}
+482
View File
@@ -0,0 +1,482 @@
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
use std::collections::BTreeSet;
/// A class file, as the dependency graph and the API diff see it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClassFile {
/// Internal name (`com/acme/Order$Line`).
pub name: String,
pub super_name: Option<String>,
pub interfaces: Vec<String>,
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
pub refs: BTreeSet<String>,
/// What other classes compile against: non-private, non-synthetic members and their
/// signatures, supertypes, nested classes, permitted subclasses, record components.
pub api: u64,
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
/// copies into the classes that use them: a change can't be traced through references.
pub constants: u64,
}
const ACC_PRIVATE: u16 = 0x0002;
const ACC_SYNTHETIC: u16 = 0x1000;
struct Bytes<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Bytes<'a> {
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let slice = self.data.get(self.pos..end)?;
self.pos = end;
Some(slice)
}
fn u1(&mut self) -> Option<u8> {
Some(self.take(1)?[0])
}
fn u2(&mut self) -> Option<u16> {
let b = self.take(2)?;
Some(u16::from_be_bytes([b[0], b[1]]))
}
fn u4(&mut self) -> Option<u32> {
let b = self.take(4)?;
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
}
#[derive(Clone, Debug)]
enum Entry {
Empty,
Utf8(String),
Class(u16),
String(u16),
/// Integer, float, long, double: the raw bytes.
Number(Vec<u8>),
NameAndType(u16),
MethodType(u16),
Other,
}
struct Pool(Vec<Entry>);
impl Pool {
fn utf8(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Utf8(s) => Some(s),
_ => None,
}
}
fn class(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Class(name) => self.utf8(*name),
_ => None,
}
}
/// A `ConstantValue`'s value, as bytes.
fn constant(&self, index: u16) -> Option<Vec<u8>> {
match self.0.get(index as usize)? {
Entry::Number(bytes) => Some(bytes.clone()),
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
_ => None,
}
}
}
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
#[derive(Clone, Copy)]
struct Fnv(u64);
impl Fnv {
fn new() -> Self {
Fnv(0xcbf2_9ce4_8422_2325)
}
fn bytes(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
}
// A separator, so `ab`+`c` and `a`+`bc` differ.
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
}
fn str(&mut self, s: &str) {
self.bytes(s.as_bytes());
}
fn u16(&mut self, v: u16) {
self.bytes(&v.to_be_bytes());
}
}
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'L'
&& (i == 0
|| matches!(
bytes[i - 1],
b'(' | b')'
| b'['
| b';'
| b'<'
| b'>'
| b'+'
| b'-'
| b':'
| b'*'
| b'I'
| b'J'
| b'Z'
| b'B'
| b'C'
| b'S'
| b'F'
| b'D'
| b'V'
| b'^'
))
{
let start = i + 1;
let mut end = start;
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
end += 1;
}
if end < bytes.len() && end > start {
let name = &text[start..end];
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
out.insert(name.to_owned());
}
}
i = end;
} else {
i += 1;
}
}
}
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
if name.starts_with('[') {
descriptor_refs(name, out);
} else {
out.insert(name.to_owned());
}
}
struct Member {
access: u16,
name: String,
descriptor: String,
/// Fingerprint of the attributes that are part of the API.
extra: u64,
constant: Option<Vec<u8>>,
}
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
let count = r.u2()?;
for _ in 0..count {
let name = pool.utf8(r.u2()?)?.to_owned();
let len = r.u4()? as usize;
let body = r.take(len)?;
on(&name, body);
}
Some(())
}
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
let count = r.u2()?;
let mut out = Vec::with_capacity(count as usize);
for _ in 0..count {
let access = r.u2()?;
let name = pool.utf8(r.u2()?)?.to_owned();
let descriptor = pool.utf8(r.u2()?)?.to_owned();
descriptor_refs(&descriptor, refs);
let mut extra = Fnv::new();
let mut constant = None;
attributes(r, pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, refs);
extra.str("S");
extra.str(sig);
}
}
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
"Exceptions" => {
let mut names: Vec<&str> = Vec::new();
if let Some(n) = b.u2() {
for _ in 0..n {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c);
}
}
}
names.sort_unstable();
extra.str("E");
for n in names {
extra.str(n);
}
}
// An annotation element's default value is compiled into its uses.
"AnnotationDefault" => {
extra.str("D");
element_value(&mut b, pool, refs, &mut extra);
}
_ => {}
}
})?;
out.push(Member { access, name, descriptor, extra: extra.0, constant });
}
Some(out)
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
r.u2()?;
r.u2()?;
let count = r.u2()?;
let mut entries = vec![Entry::Empty];
let mut i = 1;
while i < count {
let tag = r.u1()?;
let entry = match tag {
1 => {
let len = r.u2()? as usize;
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
}
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
7 => Entry::Class(r.u2()?),
8 => Entry::String(r.u2()?),
9..=11 => {
r.take(4)?;
Entry::Other
}
12 => {
r.u2()?;
Entry::NameAndType(r.u2()?)
}
15 => {
r.take(3)?;
Entry::Other
}
16 => Entry::MethodType(r.u2()?),
17 | 18 => {
r.take(4)?;
Entry::Other
}
19 | 20 => {
r.take(2)?;
Entry::Other
}
_ => return None,
};
let wide = matches!(tag, 5 | 6);
entries.push(entry);
i += 1;
if wide {
entries.push(Entry::Empty);
i += 1;
}
}
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
}
_ => {}
}
}
let access = r.u2()?;
let name = pool.class(r.u2()?)?.to_owned();
let super_index = r.u2()?;
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
let mut interfaces = Vec::new();
for _ in 0..r.u2()? {
interfaces.push(pool.class(r.u2()?)?.to_owned());
}
let fields = members(&mut r, &pool, &mut refs)?;
let methods = members(&mut r, &pool, &mut refs)?;
let mut api = Fnv::new();
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
api.str(&name);
api.str(super_name.as_deref().unwrap_or(""));
let mut sorted = interfaces.clone();
sorted.sort();
for i in &sorted {
api.str(i);
}
let mut class_attrs: Vec<(String, u64)> = Vec::new();
attributes(&mut r, &pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
let mut h = Fnv::new();
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, &mut refs);
h.str(sig);
}
}
"PermittedSubclasses" => {
let mut names = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c.to_owned());
}
}
names.sort();
names.iter().for_each(|n| h.str(n));
}
"Record" => {
for _ in 0..b.u2().unwrap_or(0) {
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
else {
break;
};
h.str(n);
h.str(d);
let mut component = |attr: &str, body: &[u8]| {
if attr == "Signature"
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
{
h.str(sig);
}
};
if attributes(&mut b, &pool, &mut component).is_none() {
break;
}
}
}
// Nested classes this class declares, and their access.
"InnerClasses" => {
let mut nested = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
break;
};
let inner = pool.class(inner).unwrap_or("");
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
nested.push(format!("{inner}:{flags}"));
}
}
nested.sort();
nested.iter().for_each(|n| h.str(n));
}
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
// Annotation types are dependencies; their values aren't API.
annotation_types(body, &pool, &mut refs);
return;
}
_ => return,
}
class_attrs.push((attr.to_owned(), h.0));
})?;
class_attrs.sort();
for (attr, h) in &class_attrs {
api.str(attr);
api.bytes(&h.to_be_bytes());
}
let mut constants = Fnv::new();
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
for m in list.iter() {
if kind == 0
&& let Some(value) = &m.constant
{
// Private constants are inlined too, but only in their own class.
if m.access & ACC_PRIVATE == 0 {
constants.str(&m.name);
constants.str(&m.descriptor);
constants.bytes(value);
}
}
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
continue;
}
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
}
}
api_members.sort();
for (kind, name, descriptor, access, extra) in api_members {
api.bytes(&[kind]);
api.str(name);
api.str(descriptor);
api.u16(access);
api.bytes(&extra.to_be_bytes());
}
refs.remove(&name);
refs.retain(|r| !r.starts_with("java/"));
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
}
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
let mut b = Bytes { data: body, pos: 0 };
let Some(count) = b.u2() else { return };
let mut ignored = Fnv::new();
for _ in 0..count {
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
return;
}
}
}
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
for _ in 0..b.u2()? {
h.str(pool.utf8(b.u2()?)?);
element_value(b, pool, refs, h)?;
}
Some(())
}
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
/// constant pool indices) to `h`.
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let tag = b.u1()?;
h.bytes(&[tag]);
match tag {
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
b's' => h.str(pool.utf8(b.u2()?)?),
b'e' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
h.str(pool.utf8(b.u2()?)?);
}
b'c' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
}
b'@' => annotation(b, pool, refs, h)?,
b'[' => {
for _ in 0..b.u2()? {
element_value(b, pool, refs, h)?;
}
}
_ => return None,
}
Some(())
}
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
pub fn simple_name(name: &str) -> &str {
let tail = name.rsplit('/').next().unwrap_or(name);
tail.rsplit('$').next().unwrap_or(tail)
}
@@ -0,0 +1,145 @@
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
// the same model the Maven extension writes (java/java-build, BuildModel).
import groovy.json.JsonOutput
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
def property = { String name -> gradle.startParameter.projectProperties[name] }
def outRoot = property('openidea.build.output')
if (outRoot == null || gradle.parent != null) return
// The project's name in the build: unique, unlike `name`.
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
def outputOf = { Project p, String set ->
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
}
def javaSets = { Project p ->
def sets = p.extensions.findByName('sourceSets')
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
}
gradle.projectsEvaluated {
def root = gradle.rootProject
root.allprojects.each { p ->
javaSets(p).each { ss ->
def out = outputOf(p, ss.name)
ss.java.destinationDirectory.set(out)
ss.output.resourcesDir = out
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
}
}
root.tasks.register('openideaBuildModel') {
// What compiling needs from the same project (generated sources), and the resources.
dependsOn {
root.allprojects.collectMany { p ->
javaSets(p).collectMany { ss ->
def compile = p.tasks.getByName(ss.compileJavaTaskName)
def generators = compile.taskDependencies.getDependencies(compile).findAll {
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
}
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
}
}
}
doLast {
// Project artifacts resolve to the projects' outputs.
def artifacts = [:]
root.allprojects.each { p ->
def main = javaSets(p).find { it.name == 'main' }
if (main == null) return
def jar = p.tasks.findByName('jar')
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
}
def files = { collection ->
def out = []
try {
collection?.files?.each { f ->
def mapped = artifacts[f.canonicalPath] ?: f
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
}
} catch (e) {
out << "!${e.message}".toString()
}
out
}
def included = gradle.includedBuilds.collect { it.name }
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
def others = p.tasks.withType(AbstractCompile).findAll {
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
def setModel = { String name ->
def ss = javaSets(p).find { it.name == name }
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
def o = compile.options
def classpath = files(compile.classpath)
def runtime = files(ss.runtimeClasspath)
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
def processorPath = files(o.annotationProcessorPath)
def processorProblems = processorPath.findAll { it.startsWith('!') }
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
def home = null
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
[
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
output: outputOf(p, name).canonicalPath,
classpath: classpath.findAll { !it.startsWith('!') },
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
compiler: [
compilerId: 'javac',
source: compile.sourceCompatibility,
target: compile.targetCompatibility,
release: o.release.orNull?.toString(),
encoding: o.encoding,
debug: o.debug,
debuglevel: o.debugOptions.debugLevel,
showWarnings: o.warnings,
showDeprecation: o.deprecation,
fork: home != null,
executable: home == null ? null : new File(home, 'bin/javac').path,
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
includes: ss.java.includes as List,
excludes: ss.java.excludes as List,
compilerArgs: o.allCompilerArgs.collect { it.toString() },
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
processorPathError: !processorProblems.isEmpty()
? processorProblems[0].substring(1)
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
],
]
}
def mainModel = setModel('main')
def testModel = setModel('test')
// Gradle compiles tests against the main classes: they're the main output here.
[
dir: p.projectDir.canonicalPath,
groupId: (p.group ?: '').toString(),
artifactId: nameOf(p),
version: p.version.toString(),
packaging: 'jar',
main: mainModel,
test: testModel,
otherCompilers: others,
testGenerators: [],
problems: problems,
gradlePath: p.path,
]
}
def modelFile = property('openidea.build.model')
if (modelFile != null) {
def file = new File(modelFile)
def temporary = new File(file.parentFile, file.name + '.tmp')
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
}
}
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
//! sources, then the sources of classes that refer to a class whose API changed (or to a
//! subclass of one), round after round until no API changes. Sets compiled against this one
//! read its log of API changes; a changed compile-time constant, which javac copies into the
//! classes that use it, recompiles the whole set and every set compiled against it.
use super::*;
use std::collections::BTreeSet;
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ClassRecord {
/// The source javac compiled it from; `None` for classes an annotation processor wrote
/// without naming an originating source.
pub source: Option<PathBuf>,
pub file: PathBuf,
pub super_name: Option<String>,
#[serde(default)]
pub interfaces: Vec<String>,
#[serde(default)]
pub refs: Vec<String>,
pub api: u64,
pub constants: u64,
}
impl ClassRecord {
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
let record = ClassRecord {
source,
file,
super_name: class.super_name,
interfaces: class.interfaces,
refs: class.refs.into_iter().collect(),
api: class.api,
constants: class.constants,
};
(class.name, record)
}
fn has_constants(&self) -> bool {
self.constants != NO_CONSTANTS
}
}
/// The constant fingerprint of a class without compile-time constants.
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
/// The classes whose API one compilation of a set changed.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ApiChange {
/// The set's generation before and after the compilation.
pub since: u64,
pub generation: u64,
pub classes: Vec<String>,
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
pub all: bool,
}
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
/// fell further behind compiles from scratch.
const CHANGE_LOG: usize = 64;
/// The inputs of a source set that, when changed, compile it from scratch.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct SetStamp {
pub options: Vec<String>,
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
/// The reactor outputs on the classpath, in order.
pub reactor: Vec<PathBuf>,
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
pub java_home: PathBuf,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub(super) struct SetState {
pub stamp: SetStamp,
/// The sources as of the last compilation.
pub sources: BTreeMap<PathBuf, FileStamp>,
/// Changes whenever the set's classes do.
pub generation: u64,
/// The generation of each reactor output it was compiled against.
pub upstream: BTreeMap<PathBuf, u64>,
pub classes: BTreeMap<String, ClassRecord>,
/// Sources a failed compilation left uncompiled.
pub dirty: BTreeSet<PathBuf>,
pub changes: Vec<ApiChange>,
/// Sources annotation processors wrote, and other files they wrote without an originating
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
/// compiles the set from scratch.
pub generated: Vec<PathBuf>,
pub unowned: Vec<PathBuf>,
pub success: bool,
}
impl SetState {
/// The classes whose API changed since generation `since`; `None` when unknown (the log
/// doesn't reach back that far) or when everything counts as changed.
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
let mut changed = BTreeSet::new();
let mut at = since;
while at != self.generation {
let change = self.changes.iter().find(|c| c.since == at)?;
if change.all {
return None;
}
changed.extend(change.classes.iter().cloned());
at = change.generation;
}
Some(changed)
}
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
self.changes.push(ApiChange {
since: self.generation,
generation,
classes: classes.into_iter().collect(),
all,
});
if self.changes.len() > CHANGE_LOG {
self.changes.drain(..self.changes.len() - CHANGE_LOG);
}
self.generation = generation;
}
}
pub(super) fn load_state(path: &Path) -> Option<SetState> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
/// a class that inherits a changed member changes for the classes that use it.
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
let mut out = seeds.clone();
loop {
let before = out.len();
for (name, record) in classes {
if !out.contains(name)
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|| record.interfaces.iter().any(|i| out.contains(i)))
{
out.insert(name.clone());
}
}
if out.len() == before {
return out;
}
}
}
/// The sources of the classes that refer to one of `affected`.
pub(super) fn dependent_sources(
classes: &BTreeMap<String, ClassRecord>,
affected: &BTreeSet<String>,
) -> BTreeSet<PathBuf> {
if affected.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// The sources of the classes that refer to a class with the same simple name as one of
/// `added`: a new class can take a simple name over from an on-demand import.
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
if names.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| {
!added.contains(*name)
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
})
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// What one round's classes changed, compared with the classes the round replaced.
#[derive(Debug, Default)]
pub(super) struct RoundDiff {
pub api: BTreeSet<String>,
pub added: BTreeSet<String>,
pub constants: bool,
}
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
let mut out = RoundDiff::default();
for (name, record) in new {
match old.get(name) {
Some(before) => {
if before.api != record.api {
out.api.insert(name.clone());
}
if before.constants != record.constants {
out.constants = true;
}
}
None => {
out.api.insert(name.clone());
out.added.insert(name.clone());
}
}
}
for (name, before) in old {
if !new.contains_key(name) {
out.api.insert(name.clone());
out.constants |= before.has_constants();
}
}
out
}
+263
View File
@@ -0,0 +1,263 @@
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
//! and JVM options, kept warm between builds, compiling one request at a time in process.
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// A message of the server about one request.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
pub enum Reply {
Diagnostic {
severity: String,
path: Option<PathBuf>,
/// 1-based.
line: Option<u32>,
/// 0-based UTF-16.
column: Option<u32>,
end_line: Option<u32>,
end_column: Option<u32>,
code: Option<String>,
message: String,
},
/// A class (or resource) file javac wrote, and the source it came from.
Output {
path: PathBuf,
source: Option<PathBuf>,
},
/// A source file an annotation processor wrote.
Generated {
path: PathBuf,
source: Option<PathBuf>,
},
OutputText {
text: String,
},
Done {
success: bool,
cancelled: bool,
},
}
#[derive(Debug, Serialize)]
struct Request<'a> {
id: u64,
op: &'static str,
options: &'a [String],
sources: &'a [PathBuf],
encoding: Option<&'a str>,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ServerKey {
pub java_home: PathBuf,
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
pub jvm_args: Vec<String>,
}
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
pub struct JavacServer {
child: Mutex<Child>,
stdin: Mutex<ChildStdin>,
pending: Pending,
alive: Arc<AtomicBool>,
next: AtomicU64,
pub version: String,
}
impl JavacServer {
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
let mut cmd = Command::new(&java);
cmd.args(&key.jvm_args)
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
.arg(jar)
.arg("ai.openidea.javac.Server")
.env("JAVA_HOME", &key.java_home)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
ide_core::process::prepare(&mut cmd);
ide_core::process::own_group(&mut cmd);
let mut child =
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let pending: Pending = Arc::default();
let alive = Arc::new(AtomicBool::new(true));
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
{
let (pending, alive) = (pending.clone(), alive.clone());
std::thread::Builder::new()
.name("javac-server".into())
.spawn(move || {
let mut ready = Some(ready_tx);
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
match value.get("kind").and_then(|k| k.as_str()) {
Some("ready") => {
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Ok(version));
}
continue;
}
Some("fatal") => {
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Err(message));
}
continue;
}
_ => {}
}
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
let done = matches!(reply, Reply::Done { .. });
let mut pending = pending.lock().unwrap();
if let Some(tx) = pending.get(&id) {
let _ = tx.send(reply);
}
if done {
pending.remove(&id);
}
}
alive.store(false, Ordering::SeqCst);
// Requests still waiting learn that the server is gone.
for (_, tx) in pending.lock().unwrap().drain() {
let _ = tx.send(Reply::Diagnostic {
severity: "error".into(),
path: None,
line: None,
column: None,
end_line: None,
end_column: None,
code: None,
message: "The javac process exited".into(),
});
let _ = tx.send(Reply::Done { success: false, cancelled: false });
}
if let Some(ready) = ready.take() {
let _ = ready.send(Err("The javac process exited while starting".into()));
}
})
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
Ok(Ok(version)) => version,
Ok(Err(message)) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
}
Err(_) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
}
};
Ok(JavacServer {
child: Mutex::new(child),
stdin: Mutex::new(stdin),
pending,
alive,
next: AtomicU64::new(1),
version,
})
}
fn alive(&self) -> bool {
self.alive.load(Ordering::SeqCst)
}
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
let mut stdin = self.stdin.lock().unwrap();
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
}
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
/// compilation ends. Cancelling stops javac at its next phase.
pub fn compile(
&self,
options: &[String],
sources: &[PathBuf],
encoding: Option<&str>,
cancel: &CancellationToken,
mut on_reply: impl FnMut(&Reply),
) -> IdeResult<bool> {
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = mpsc::channel();
self.pending.lock().unwrap().insert(id, tx);
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
self.pending.lock().unwrap().remove(&id);
return Err(e);
}
let mut cancelled = false;
loop {
match rx.recv_timeout(Duration::from_millis(100)) {
Ok(reply) => {
if let Reply::Done { success, cancelled: stopped } = reply {
if stopped || cancelled {
return Err(IdeError::cancelled());
}
return Ok(success);
}
on_reply(&reply);
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if cancel.is_cancelled() && !cancelled {
cancelled = true;
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err(IdeError::internal("The javac process exited"));
}
}
}
}
}
impl Drop for JavacServer {
fn drop(&mut self) {
let _ = self.send(&serde_json::json!({ "op": "exit" }));
let mut child = self.child.lock().unwrap();
for _ in 0..20 {
if child.try_wait().ok().flatten().is_some() {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
ide_core::process::kill_tree(&mut child);
}
}
/// The resident javac servers of one IDE process.
#[derive(Default)]
pub struct JavacPool {
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
}
impl JavacPool {
/// The running server for `key`, started on first use (or after it died).
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
let mut servers = self.servers.lock().unwrap();
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
return Ok(server.clone());
}
let server = Arc::new(JavacServer::start(jar, key)?);
servers.insert(key.clone(), server.clone());
Ok(server)
}
/// Stops every server (the project closed).
pub fn shutdown(&self) {
self.servers.lock().unwrap().clear();
}
}
File diff suppressed because it is too large. Load diff
+342
View File
@@ -0,0 +1,342 @@
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
use super::*;
use std::fs;
/// `model.json` of the prepare run (see `BuildModel.java`).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactorModel {
pub version: u32,
pub projects: Vec<ProjectModel>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectModel {
/// Absolute project directory.
pub dir: PathBuf,
pub group_id: String,
pub artifact_id: String,
pub version: String,
pub packaging: String,
pub main: SourceSet,
pub test: SourceSet,
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
#[serde(default)]
pub other_compilers: Vec<String>,
/// Test source generators the prepare run doesn't reach.
#[serde(default)]
pub test_generators: Vec<String>,
#[serde(default)]
pub problems: Vec<String>,
/// The Gradle project path (`:`, `:app`); `None` for Maven.
#[serde(default)]
pub gradle_path: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceSet {
pub source_roots: Vec<PathBuf>,
pub output: PathBuf,
pub classpath: Vec<PathBuf>,
pub runtime_classpath: Vec<PathBuf>,
#[serde(default)]
pub resources: Vec<ResourceRoot>,
pub compiler: Option<CompilerConfig>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceRoot {
pub directory: PathBuf,
#[serde(default)]
pub filtering: bool,
pub target_path: Option<String>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
}
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CompilerConfig {
pub compiler_id: Option<String>,
pub source: Option<String>,
pub target: Option<String>,
pub release: Option<String>,
pub encoding: Option<String>,
pub parameters: Option<bool>,
pub debug: Option<bool>,
pub debuglevel: Option<String>,
pub proc: Option<String>,
pub enable_preview: Option<bool>,
pub fork: Option<bool>,
pub executable: Option<String>,
pub skip: Option<bool>,
pub show_warnings: Option<bool>,
pub show_deprecation: Option<bool>,
pub generated_sources_directory: Option<PathBuf>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
pub annotation_processors: Option<Vec<String>>,
#[serde(default)]
pub compiler_args: Vec<String>,
pub compiler_argument: Option<String>,
#[serde(default)]
pub compiler_arguments: BTreeMap<String, Option<String>>,
pub multi_release_output: Option<bool>,
pub processor_path: Option<Vec<PathBuf>>,
pub processor_path_error: Option<String>,
}
impl ProjectModel {
pub fn key(&self) -> String {
format!("{}:{}", self.group_id, self.artifact_id)
}
pub fn set(&self, test: bool) -> &SourceSet {
if test { &self.test } else { &self.main }
}
/// Why the IDE can't compile this project with javac itself, if it can't.
pub fn unsupported(&self, test: bool) -> Option<String> {
// What the build tool couldn't resolve or read: the model would be incomplete.
if let Some(problem) = self.problems.first() {
return Some(format!("{}: {problem}", self.artifact_id));
}
if !self.other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
}
if test && !self.test_generators.is_empty() {
return Some(format!(
"{} generates test sources with {}",
self.artifact_id,
self.test_generators.join(", ")
));
}
for set in [&self.main, &self.test] {
let Some(c) = &set.compiler else { continue };
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
}
if c.multi_release_output == Some(true) {
return Some(format!("{} is a multi-release jar", self.artifact_id));
}
if let Some(error) = &c.processor_path_error {
return Some(format!("{}: {error}", self.artifact_id));
}
}
None
}
}
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
let base = cache.join("java-build");
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
}
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
/// redirects them (`-Dopenidea.build.output=<out>`).
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
reactor_dir(cache, top_dir).join("out")
}
/// What the recorded model was prepared from.
#[derive(Debug, Deserialize, Serialize)]
pub(super) struct PrepareRecord {
pub fingerprint: LaunchFingerprint,
pub model: ReactorModel,
}
const MODEL_VERSION: u32 = 1;
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
pub(super) fn prepare_fingerprint(
root: &Path,
reactor: &[&maven::MavenProject],
step: &BuildStep,
local_repo: Option<PathBuf>,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> {
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
for project in reactor {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = dir.file_name();
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(dir.path());
}
}
}
}
for dir in step.cwd.ancestors() {
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
if dir == root {
break;
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
}
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
(record.model.version == MODEL_VERSION).then_some(record)
}
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
write_json(&dir.join("prepare.json"), record)
}
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
file.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
model.projects.iter().all(|p| {
[&p.main, &p.test].iter().all(|set| {
set.source_roots.iter().all(|root| {
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
})
})
})
}
/// The annotation processors' output folder, which javac writes into and never reads as a root.
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
}
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
pub(super) fn maven_step(
root: &Path,
top: &maven::MavenProject,
jar: &Path,
output_root: &Path,
model_file: Option<&Path>,
extra: &[String],
) -> BuildStep {
let mut step = maven_build_step(
&top.command,
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
&subdir(root, &top.dir),
);
step.args.extend(top.options.iter().cloned());
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
}
step.args.extend(extra.iter().cloned());
step.env = top.env.clone();
step
}
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
/// Writes the init script into the build's state folder, and returns its path.
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
fs::create_dir_all(dir)?;
let path = dir.join("openidea-build.init.gradle");
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
fs::write(&path, GRADLE_INIT_SCRIPT)?;
}
Ok(path)
}
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
pub(super) fn gradle_step(
root: &Path,
g: &crate::GradleModel,
init: &Path,
output_root: &Path,
model_file: Option<&Path>,
tasks: &[String],
) -> BuildStep {
let mut step = gradle_build_step(
&g.command,
// The init script configures the evaluated projects, which a configuration cache skips.
&["--console=plain", "--no-configuration-cache"],
&subdir(root, &g.dir),
);
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Popenidea.build.model={}", file.display()));
}
step.args.extend(tasks.iter().cloned());
step.env = g.env.clone();
step
}
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
pub(super) fn gradle_prepare_fingerprint(
root: &Path,
g: &crate::GradleModel,
step: &BuildStep,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<LaunchFingerprint> {
let mut inputs = crate::gradle::build_files(root, g);
let dir = subdir(root, &g.dir);
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
for project in &g.projects {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = generator.file_name();
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(generator.path());
}
}
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.push(home.join(".gradle/gradle.properties"));
inputs.push(home.join(".gradle/init.d"));
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters =
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
}
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
}
+544
View File
@@ -0,0 +1,544 @@
use super::*;
use crate::BuildModel;
use std::fs;
use std::sync::Mutex as StdMutex;
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
cache: PathBuf,
model: BuildModel,
/// Where the build keeps its state under the cache (`Reactor::key`).
key: &'static str,
service: JavaBuildService,
events: StdMutex<Vec<BuildEvent>>,
}
impl Fixture {
fn new(files: &[(&str, &str)]) -> Option<Self> {
let Some((home, mvn)) = tools() else {
eprintln!("skipped: needs JAVA_HOME and mvn");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for (rel, text) in
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
{
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
for p in &mut model.maven.as_mut().unwrap().projects {
p.command = mvn.to_string_lossy().into_owned();
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
}
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
/// search path).
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
let (Some(home), Some(gradle)) = (home, gradle) else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let build = [
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
(
"build.gradle",
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
),
("lib/build.gradle", ""),
(
"app/build.gradle",
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
),
];
for (rel, text) in build.iter().chain(files) {
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
assert_eq!(model.gradle.len(), 1, "{model:?}");
let g = &mut model.gradle[0];
g.command = gradle.to_string_lossy().into_owned();
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "_gradle",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
fn write(&self, rel: &str, text: &str) {
write(&self.root, rel, text);
}
fn out(&self, rel: &str) -> PathBuf {
model::output_root(&self.cache, self.key).join(rel)
}
/// Builds the launch of `app` (its tests when `test`).
fn launch(&self, test: bool) -> LaunchOutputs {
self.build(Target::Launch { module: &self.root.join("app"), test })
}
fn build(&self, target: Target) -> LaunchOutputs {
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &self.root,
model: &self.model,
cache: &self.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &self.service,
jdk: &jdk,
};
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Err(e) => panic!("{e:?}"),
}
}
/// The steps of the launch builds since the last call.
fn steps(&self) -> Vec<String> {
self.events
.lock()
.unwrap()
.drain(..)
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command),
_ => None,
})
.collect()
}
/// Builds and returns the steps it took, which must succeed.
fn steps_of_launch(&self) -> Vec<String> {
self.steps();
let built = self.launch(false);
assert_eq!(built.failure, None, "{:?}", built.messages);
self.steps()
}
}
#[test]
fn builds_maven_modules_with_javac_and_only_what_changed() {
let Some(f) = Fixture::new(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${project.version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
let first = f.launch(false);
assert_eq!(first.failure, None, "{:?}", first.messages);
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
assert!(f.out("t.app/classes/a/A.class").is_file());
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(!f.root.join("app/target/classes/a/A.class").exists());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
let steps = f.steps();
assert!(steps[0].contains("process-resources"), "{steps:?}");
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
// Nothing changed: no Maven, no javac.
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
// A change inside a method compiles that class only, without Maven.
f.write(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
// A resource change is processed by Maven (it filters), and compiles nothing.
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
assert!(f.out("t.app/classes/a/Gone.class").is_file());
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
assert!(!f.out("t.app/classes/a/Gone.class").exists());
// Compile errors fail the build with positioned messages.
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
let failed = f.launch(false);
let failure = failed.failure.expect("fails");
assert!(failure.contains("incompatible types"), "{failure}");
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
// It compiles again next time, even unchanged.
f.steps();
assert!(f.launch(false).failure.is_some());
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// A test launch compiles the module's tests after its main classes.
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let tests = f.launch(true);
assert_eq!(tests.failure, None, "{:?}", tests.messages);
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// Recompile compiles the file even unchanged.
f.steps();
let file = f.root.join("app/src/main/java/a/A.java");
assert_eq!(f.build(Target::File(&file)).failure, None);
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// Build Project builds every module's main and test classes.
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
assert_eq!(f.build(Target::Project).failure, None);
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
}
#[test]
fn recompiles_the_classes_an_api_change_reaches() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
]) else {
return;
};
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
// A body change: that class only, and nothing downstream.
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
// An API change reaches the classes that use the class or a subclass of it.
f.write(
"lib/src/main/java/l/Base.java",
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
// Across modules: only the classes that use it.
f.write(
"lib/src/main/java/l/Other.java",
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
assert_eq!(
f.steps_of_launch(),
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
);
// A removed method fails the classes that still call it.
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("fails").contains("User.java"));
}
#[test]
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
]) else {
return;
};
assert_eq!(f.launch(false).failure, None);
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
// that calls a method L no longer has.
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
// So does a changed constant: C compiles, then the whole set, where U fails.
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
assert_eq!(f.launch(false).failure, None);
f.write("lib/src/main/java/l/C.java", &c(2, ""));
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
f.steps();
assert_eq!(f.launch(false).failure, None);
let steps = f.steps();
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
}
#[test]
fn reads_what_a_class_file_declares() {
let Some((home, _)) = tools() else { return };
let tmp = tempfile::tempdir().unwrap();
let compile = |text: &str| {
write(tmp.path(), "p/C.java", text);
let status = std::process::Command::new(home.join("bin/javac"))
.args(["-d", "out", "p/C.java"])
.current_dir(tmp.path())
.status()
.unwrap();
assert!(status.success());
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
};
let a = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
.replace("x.Y", "Object")
.as_str(),
);
assert_eq!(a.name, "p/C");
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
// Private members and method bodies aren't API; constants have their own fingerprint.
let b = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
);
assert_eq!((a.api, a.constants), (b.api, b.constants));
let c = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_eq!(a.api, c.api);
assert_ne!(a.constants, c.constants);
let d = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_ne!(a.api, d.api);
}
#[test]
fn follows_api_changes_through_the_log() {
let mut state = SetState { generation: 1, ..Default::default() };
state.log(2, ["a/A".to_owned()].into(), false);
state.log(3, ["a/B".to_owned()].into(), false);
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
// Unknown generations, and a log entry where everything changed, mean everything.
assert_eq!(state.changes_since(0), None);
state.log(4, BTreeSet::new(), true);
assert_eq!(state.changes_since(3), None);
}
#[test]
fn ant_patterns_match_like_maven() {
assert!(ant_match("**/*.java", "a/b/C.java"));
assert!(ant_match("**/*.java", "C.java"));
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
assert!(ant_match("**/generated/", "x/generated/Y.java"));
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
assert!(!ant_match("*.java", "a/B.java"));
}
#[test]
fn javac_options_follow_the_compiler_configuration() {
let set = SourceSet {
output: PathBuf::from("/o"),
compiler: Some(CompilerConfig {
release: Some("17".into()),
source: Some("1.8".into()),
encoding: Some("UTF-8".into()),
parameters: Some(true),
debuglevel: Some("lines,vars".into()),
proc: Some("none".into()),
processor_path: Some(vec![PathBuf::from("/p.jar")]),
annotation_processors: Some(vec!["a.P".into()]),
compiler_args: vec!["-Xlint:unchecked".into()],
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
show_warnings: Some(false),
..Default::default()
}),
..Default::default()
};
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
let joined = args.join(" ");
let separator = if cfg!(windows) { ";" } else { ":" };
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
for expected in [
"-processorpath /p.jar",
"-processor a.P",
"-proc:none",
"-g:lines,vars",
"-parameters",
"-nowarn",
"-encoding UTF-8",
"--release 17",
"-Akey=v",
] {
assert!(joined.contains(expected), "{expected} in {joined}");
}
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
// JDK 8 has no --release: source and target instead.
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
}
#[test]
fn builds_gradle_projects_with_javac_and_only_what_changed() {
let Some(f) = Fixture::gradle(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 3, "{steps:?}");
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(f.out("t.app/classes/a/A.class").is_file());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
// Gradle's own outputs stay untouched.
assert!(!f.root.join("app/build/classes").exists());
let built = f.launch(false);
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
);
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
// Tests compile against the main classes.
f.steps();
let built = f.launch(true);
assert_eq!(built.failure, None, "{:?}", built.messages);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// A changed build script prepares again.
f.write("lib/build.gradle", "// changed\n");
let steps = f.steps_of_launch();
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
// An error is a javac diagnostic on the source.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
let built = f.launch(false);
assert!(built.failure.is_some());
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
}
#[test]
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
let Some(f) = Fixture::gradle(&[
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
]) else {
return;
};
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &f.root,
model: &f.model,
cache: &f.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &f.service,
jdk: &jdk,
};
let target = Target::Launch { module: &f.root.join("app"), test: false };
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
Err(e) => panic!("{e:?}"),
}
}
+1
View File
@@ -9,6 +9,7 @@ pub mod application_update;
pub mod compile;
pub mod gradle;
mod gradle_deps;
pub mod jbuild;
pub mod kotlin_bridge;
pub mod maven;
pub mod pom_edit;
+26 -4
View File
@@ -753,7 +753,26 @@ pub(crate) fn launch_inputs(
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
project_inputs(root, projects, local_repo, true)
}
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
/// on: what Maven's model of them is built from, without their sources.
pub(crate) fn model_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
project_inputs(root, projects, local_repo, false)
}
fn project_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
sources: bool,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
let input =
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
@@ -762,6 +781,7 @@ pub(crate) fn launch_inputs(
|| (parent == "filters" && el.name == "filter");
// Profile activation may depend on the presence of an otherwise unrelated file.
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
let input = input && sources;
if input || activation {
// A source root under Maven's build directory is generated by the build itself.
// Skip it without resolving the property: `<build><directory>` may be custom, and
@@ -787,7 +807,7 @@ pub(crate) fn launch_inputs(
}
}
for child in &el.children {
roots(child, &el.name, dir, out)?;
roots(child, &el.name, dir, sources, out)?;
}
Some(())
}
@@ -796,7 +816,9 @@ pub(crate) fn launch_inputs(
for project in projects {
let dir = root.join(&project.dir);
// Include all conventional language/resource roots, including nonstandard files under src.
out.push(dir.join("src"));
if sources {
out.push(dir.join("src"));
}
let pom = root.join(&project.pom);
resolver.context(&pom, 0);
let mut path = pom;
@@ -808,7 +830,7 @@ pub(crate) fn launch_inputs(
}
out.push(path.clone());
let text = xml::read_text(&path)?;
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
let raw = resolver.pom(&path)?;
let Some(parent) = raw.parent else { break };
path = resolver.parent_path(path.parent()?, &parent)?;
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
version.workspace = true
edition.workspace = true
license.workspace = true
+151 -4
View File
@@ -16,8 +16,12 @@
//! thread: AppKit and WebKit also access the general pasteboard there, and its
//! mutable type cache cannot be protected by a mutex in this crate.
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
//! one URI per line), read and written through the GTK clipboard on X11 and
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
//! fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
@@ -79,6 +83,7 @@ const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
/// Read failures remain errors so callers can retain an internal copy.
/// Empty on Linux, where [`request_files`] reads it.
pub fn files() -> std::io::Result<Vec<PathBuf>> {
imp::files()
}
@@ -101,7 +106,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
/// line. An editor paste inserts names, not the absolute paths the file list
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
/// file name (a root like `C:\`) keeps its whole path.
#[cfg(any(windows, target_os = "macos", test))]
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
fn names_text(paths: &[PathBuf], separator: &str) -> String {
paths
.iter()
@@ -112,6 +117,82 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
.join(separator)
}
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
/// hosts or schemes are skipped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
}
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
/// path; its percent-escapes are raw bytes, as GLib writes them.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_to_path(uri: &str) -> Option<PathBuf> {
use std::os::unix::ffi::OsStringExt;
let rest = uri.strip_prefix("file://")?;
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
let path = path.split(['?', '#']).next()?;
if !path.starts_with('/') {
return None;
}
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
let bytes = path.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let escaped =
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
match escaped {
Some(b) => {
out.push(b);
i += 3;
}
None => {
out.push(bytes[i]);
i += 1;
}
}
}
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
/// percent-escaped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn file_uri(path: &std::path::Path) -> String {
use std::fmt::Write;
use std::os::unix::ffi::OsStrExt;
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
uri.push(b as char);
} else {
let _ = write!(uri, "%{b:02X}");
}
}
uri
}
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
/// then GNOME's list, and calls `done` with the paths (empty without a list).
/// Call on the main thread; `done` runs there later.
#[cfg(target_os = "linux")]
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
fn paths_in(data: &gtk::SelectionData) -> Vec<PathBuf> {
// A failed request has a negative length and no data.
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
}
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
let paths = paths_in(data);
if !paths.is_empty() {
return done(paths);
}
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
});
}
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
/// page survive. Empty paths are skipped.
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
@@ -728,8 +809,25 @@ mod imp {
}
}
#[cfg(target_os = "linux")]
pub const URI_LIST: &str = "text/uri-list";
#[cfg(target_os = "linux")]
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
pub fn has_files() -> bool {
false
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
targets.into_iter().any(|target| {
let name = target.name();
name == URI_LIST || name == GNOME_COPIED
})
})
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn has_image() -> bool {
@@ -747,6 +845,33 @@ mod imp {
Ok(Vec::new())
}
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
/// list (Nautilus, Thunar) and their names as text, rendered on request.
#[cfg(target_os = "linux")]
pub fn set_files(paths: &[PathBuf]) -> bool {
use gtk::{TargetEntry, TargetFlags};
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
let gnome = format!("copy\n{}", uris.join("\n"));
let names = super::names_text(paths, "\n");
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
let targets = [
entry(URI_LIST, 0),
entry(GNOME_COPIED, 1),
entry("UTF8_STRING", 2),
entry("text/plain;charset=utf-8", 2),
entry("text/plain", 2),
];
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
1 => data.set(&data.target(), 8, gnome.as_bytes()),
_ => {
let _ = data.set_text(&names);
}
})
}
#[cfg(not(target_os = "linux"))]
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
@@ -769,6 +894,28 @@ mod tests {
list.iter().map(PathBuf::from).collect()
}
#[cfg(unix)]
#[test]
fn file_manager_uri_lists_become_paths() {
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
// Other hosts and schemes are not local files.
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
}
#[cfg(unix)]
#[test]
fn written_uris_read_back_as_the_same_paths() {
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
+5 -1
View File
@@ -15,12 +15,16 @@ specta.workspace = true
specta-typescript.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
portable-pty.workspace = true
[dev-dependencies]
sha2 = "0.10"
tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation. All rights reserved.
MIT License
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.
@@ -0,0 +1,39 @@
# Bundled Windows console host
Unmodified files from Microsoft's MIT-licensed
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
puts full-screen applications' redraws in normal scrollback. A current console host
preserves those transitions, including while resizing and updating a running TUI.
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
Run and debugger builds work offline and do not depend on another installed IDE.
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
extracts them atomically to a versioned user cache and preloads the DLL's absolute
path before portable-pty initializes.
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
failure is logged and falls back to the system backend. Windows builds before
19041 also retain the system backend.
Source archive:
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
For each architecture, `conpty.dll` comes from
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
| File | SHA-256 |
| --------------------- | ------------------------------------------------------------------ |
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
console application and requires alternate-screen entry and exit to reach the
reader; a system ConPTY that consumes them fails this check.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -25,6 +25,7 @@ pub mod project_dir;
pub mod project_env;
pub mod project_roots;
pub mod proxy_settings;
pub mod pty;
pub mod real_path;
pub mod remote_settings;
pub mod settings;
+254
View File
@@ -0,0 +1,254 @@
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
windows::initialize();
portable_pty::native_pty_system()
}
#[cfg(windows)]
mod windows {
use std::fs;
use std::io::{self, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use windows_sys::Win32::Foundation::FreeLibrary;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
const VERSION: &str = "1.25.260930003";
#[cfg(target_arch = "x86_64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x64",
include_bytes!("../resources/conpty/x64/conpty.dll"),
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
);
#[cfg(target_arch = "aarch64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"arm64",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
);
#[cfg(target_arch = "x86")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x86",
include_bytes!("../resources/conpty/x86/conpty.dll"),
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
);
pub(super) fn initialize() -> bool {
static BUNDLED: OnceLock<bool> = OnceLock::new();
*BUNDLED.get_or_init(|| {
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
return false;
}
match load() {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
false
}
}
})
}
fn load() -> io::Result<()> {
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
fs::create_dir_all(&directory)?;
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
let library = directory.join("conpty.dll");
install(&library, RUNTIME.1)?;
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
// Windows reuses this module, without adding the project directory to DLL search.
// SAFETY: the path is terminated and the module is retained for the process lifetime.
let module = unsafe {
LoadLibraryExW(
wide.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
if module.is_null() {
return Err(io::Error::last_os_error());
}
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
// SAFETY: `module` is loaded and each name is a terminated export name.
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
// SAFETY: no PTY uses this rejected module yet; release our load reference.
unsafe { FreeLibrary(module) };
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
}
}
// Keep this reference for the process lifetime, including between PTY sessions.
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
Ok(())
}
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
if fs::read(path).is_ok_and(|existing| existing == data) {
return Ok(());
}
static NEXT: AtomicU64 = AtomicU64::new(0);
let pending =
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let result = (|| {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
match fs::rename(&pending, path) {
Ok(()) => Ok(()),
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
Err(error) => Err(error),
}
})();
let _ = fs::remove_file(pending);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installs_atomically_and_repairs_incomplete_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("conpty.dll");
fs::write(&path, b"partial").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
let path = &path;
scope.spawn(move || install(path, b"complete runtime").unwrap());
}
});
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn loads_the_bundled_backend() {
assert!(initialize());
}
#[test]
fn conpty_output_child() {
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
return;
}
use windows_sys::Win32::System::Console::{
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
};
// SAFETY: the inherited console output handle and a local writable mode word.
unsafe {
let output = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode = 0;
assert_ne!(GetConsoleMode(output, &mut mode), 0);
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
}
std::io::stdout()
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
.unwrap();
std::io::stdout().flush().unwrap();
}
#[test]
fn conpty_preserves_alternate_screen_transitions() {
use std::io::Read;
use std::sync::mpsc;
use std::time::{Duration, Instant};
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
let mut reader = pair.master.try_clone_reader().unwrap();
let mut writer = pair.master.take_writer().unwrap();
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
let mut child = pair.slave.spawn_command(command).unwrap();
drop(pair.slave);
let (tx, rx) = mpsc::channel();
let reading = std::thread::spawn(move || {
let mut bytes = [0; 4096];
while let Ok(count) = reader.read(&mut bytes) {
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(10);
let mut output = Vec::new();
let mut cursor_replied = false;
while Instant::now() < deadline {
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
output.extend_from_slice(&bytes);
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
writer.write_all(b"\x1b[1;1R").unwrap();
cursor_replied = true;
}
if output.windows(7).any(|s| s == b"VT_DONE") {
break;
}
}
}
let _ = child.kill();
let _ = child.wait();
drop(writer);
drop(pair.master);
reading.join().unwrap();
let output = String::from_utf8_lossy(&output);
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
}
}
}
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
#[cfg(test)]
mod checksums {
use sha2::{Digest, Sha256};
const FILES: [(&str, &[u8], &str); 6] = [
(
"arm64/conpty.dll",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
),
(
"arm64/OpenConsole.exe",
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
),
(
"x64/conpty.dll",
include_bytes!("../resources/conpty/x64/conpty.dll"),
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
),
(
"x64/OpenConsole.exe",
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
),
(
"x86/conpty.dll",
include_bytes!("../resources/conpty/x86/conpty.dll"),
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
),
(
"x86/OpenConsole.exe",
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
),
];
#[test]
fn embedded_runtime_matches_the_pinned_package() {
for (name, bytes, expected) in FILES {
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(actual, expected, "{name}");
}
}
}
+2 -1
View File
@@ -1061,7 +1061,8 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
/// starts a launcher that gives the program its terminal, and the program reads input only from
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use ide_core::pty::native_pty_system;
use portable_pty::{CommandBuilder, PtySize};
let argv: Vec<String> = args
.get("args")
.and_then(Value::as_array)
+4 -3
View File
@@ -658,8 +658,7 @@ impl DbManager {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
self.ssh.set_secret(&c, secret, save);
return Ok(());
return self.ssh.set_secret(&c, secret, save);
}
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
}
@@ -760,7 +759,9 @@ impl DbManager {
} else {
if let Some(s) = ssh_secret {
let save = self.ssh.config(config)?.save_secret;
self.ssh.set_secret(config, Some(s), save);
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
tracing::warn!("could not save the SSH credential: {}", e.message);
}
}
self.ssh.session(config).await?
})
+1 -1
View File
@@ -213,7 +213,7 @@ impl FlutterDaemon {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
#[cfg(test)]
#[cfg(all(test, unix))]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self::new(root, sink, Box::new(move || executable.clone()))
}
+1 -1
View File
@@ -146,7 +146,7 @@ impl ToolServer {
self.0.changed.notify_all();
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) fn is_stopped(&self) -> bool {
matches!(self.0.state.lock().status, Status::Stopped)
}
+121 -9
View File
@@ -27,17 +27,21 @@ pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
}
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
/// `logs` in the local data directory elsewhere (Tauri's `app_log_dir`), so a custom location
/// from Settings › System Settings › Caches moves the logs too.
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
let os = if cfg!(target_os = "macos") {
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
} else {
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
};
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
None => os.ok_or_else(|| "cannot find the log directory".into()),
if let Some(var) = std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
return resolve_env(LOG_ENV, Some(var), None, identifier);
}
if cfg!(target_os = "macos") {
return dirs::home_dir()
.map(|home| home.join("Library/Logs").join(identifier))
.ok_or_else(|| "cannot find the log directory".into());
}
startup_local_data_dir(identifier)
.or_else(|_| local_data_dir(identifier))
.map(|dir| dir.join("logs"))
.map_err(|_| "cannot find the log directory".into())
}
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
@@ -217,6 +221,74 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
}
}
/// WebView2's profile (localStorage, IndexedDB, cookies) inside the directory the windows
/// are given, which on Windows is the local data directory.
pub const WEBVIEW_PROFILE: &str = "EBWebView";
/// Browser caches in a WebView2 profile: rebuilt on demand, so not copied across volumes.
const WEBVIEW_CACHES: [&str; 6] = ["Cache", "Code Cache", "GPUCache", "DawnCache", "GrShaderCache", "ShaderCache"];
/// Brings WebView2's profile into `local` before the first window opens: from a scheduled
/// move's source (Settings › System Settings › Caches), else from the default directory, where
/// windows kept it before they followed a custom location. Runs synchronously, as a window
/// started meanwhile would create an empty profile; a profile already in `local` is never
/// merged into or replaced, and a failed move leaves the old one in place.
pub fn adopt_webview_profile(identifier: &str, local: &Path) {
let scheduled = migration_path(identifier)
.and_then(|path| fs::read(path).ok())
.and_then(|bytes| serde_json::from_slice::<CustomMigration>(&bytes).ok())
.filter(|job| job.to == local)
.map(|job| job.from);
adopt_webview_profile_from(scheduled.into_iter().chain(local_data_dir(identifier).ok()), local);
}
fn adopt_webview_profile_from(sources: impl IntoIterator<Item = PathBuf>, local: &Path) {
let target = local.join(WEBVIEW_PROFILE);
if target.try_exists().unwrap_or(true) {
return;
}
let Some(source) = sources
.into_iter()
.filter(|dir| dir != local)
.map(|dir| dir.join(WEBVIEW_PROFILE))
.find(|profile| fs::symlink_metadata(profile).is_ok_and(|m| m.is_dir()))
else {
return;
};
let result = fs::create_dir_all(local).and_then(|()| match rename_missing(&source, &target) {
Err(error) if rename_failure(&error) == RenameFailure::Copy => {
let staging = local.join(format!(".migration-{}", uuid::Uuid::new_v4()));
let copied = copy_profile(&source, &staging).and_then(|()| rename_missing(&staging, &target));
if staging.exists() {
let _ = remove_entry(&staging);
}
copied.and_then(|()| remove_entry(&source))
}
other => other,
});
match result {
Ok(()) => tracing::info!(?source, ?target, "moved the WebView profile to the local data directory"),
Err(error) => tracing::warn!(?source, ?target, %error, "cannot move the WebView profile; starting a new one"),
}
}
/// [`copy_tree`] without the profile's browser caches.
fn copy_profile(source: &Path, target: &Path) -> io::Result<()> {
let metadata = fs::symlink_metadata(source)?;
if !metadata.is_dir() {
return copy_tree(source, target);
}
fs::create_dir(target)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
if WEBVIEW_CACHES.iter().any(|name| entry.file_name() == *name) {
continue;
}
copy_profile(&entry.path(), &target.join(entry.file_name()))?;
}
Ok(())
}
/// Entries of a local-data tree that move to a newly chosen directory.
/// Non-relocatable tool installs (virtual environments with absolute interpreter
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
@@ -552,6 +624,46 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
mod tests {
use super::*;
#[test]
fn the_webview_profile_moves_into_a_custom_local_directory_once() {
let tmp = tempfile::tempdir().unwrap();
let (default, custom) = (tmp.path().join("default"), tmp.path().join("custom"));
let storage = default.join(WEBVIEW_PROFILE).join("Default/Local Storage");
fs::create_dir_all(&storage).unwrap();
fs::write(storage.join("leveldb"), "history").unwrap();
adopt_webview_profile_from([default.clone()], &custom);
let moved = custom.join(WEBVIEW_PROFILE).join("Default/Local Storage/leveldb");
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
assert!(!default.join(WEBVIEW_PROFILE).exists());
// A profile already in place is never replaced by an older one.
fs::create_dir_all(default.join(WEBVIEW_PROFILE)).unwrap();
adopt_webview_profile_from([default.clone()], &custom);
assert!(default.join(WEBVIEW_PROFILE).exists());
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
}
#[test]
fn the_default_directory_keeps_its_own_profile() {
let tmp = tempfile::tempdir().unwrap();
let profile = tmp.path().join(WEBVIEW_PROFILE);
fs::create_dir_all(&profile).unwrap();
adopt_webview_profile_from([tmp.path().to_path_buf()], tmp.path());
assert!(profile.is_dir());
}
#[test]
fn a_copied_profile_leaves_the_browser_caches_behind() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
fs::create_dir_all(source.join("Default/Cache/Cache_Data")).unwrap();
fs::create_dir_all(source.join("Default/IndexedDB")).unwrap();
fs::write(source.join("Default/Cache/Cache_Data/f_1"), "x").unwrap();
fs::write(source.join("Default/IndexedDB/db"), "kept").unwrap();
copy_profile(&source, &tmp.path().join("copy")).unwrap();
assert_eq!(fs::read_to_string(tmp.path().join("copy/Default/IndexedDB/db")).unwrap(), "kept");
assert!(!tmp.path().join("copy/Default/Cache").exists());
}
#[test]
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
let os = Some(PathBuf::from("/os"));
+115 -48
View File
@@ -118,6 +118,8 @@ pub struct Host {
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
pub(crate) heap_requests: ops::heap::HeapRequests,
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -144,11 +146,31 @@ pub struct Host {
requests: requests::Requests,
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
/// Shutdowns of projects closed with [`Host::close_project_detached`].
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
closing: parking_lot::Mutex<Vec<DetachedClose>>,
/// One open at a time per window (see [`Host::opening`]).
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
}
struct DetachedClose {
root: Option<std::path::PathBuf>,
handle: std::thread::JoinHandle<()>,
}
struct ShutdownWork {
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
agents: Vec<Arc<ide_agent::AgentManager>>,
terminals: Option<ide_terminal::DetachedTerminals>,
processes: Option<ide_run::DetachedProcessKills>,
retired: Option<Arc<Project>>,
}
fn roots_overlap(a: &std::path::Path, b: &std::path::Path) -> bool {
a == b || a.starts_with(b) || b.starts_with(a)
}
/// How long exit waits for project shutdown before giving up.
const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
@@ -190,6 +212,8 @@ impl Host {
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
let global_settings = SettingsStore::load(&config_dir, None);
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
@@ -225,6 +249,7 @@ impl Host {
heap_windows: Mutex::default(),
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
languages,
syntax,
config_dir,
@@ -331,7 +356,7 @@ impl Host {
/// [`Self::close_project_detached`] there.
pub fn close_project(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
self.wait_blocking(shutdown);
self.wait_blocking(shutdown.handle);
}
}
@@ -341,15 +366,15 @@ impl Host {
pub fn close_project_detached(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
let mut closing = self.closing.lock();
closing.retain(|handle| !handle.is_finished());
closing.retain(|entry| !entry.handle.is_finished());
closing.push(shutdown);
}
}
/// Detaches the project from `window` and stops what it started, synchronously,
/// so the window can open another project at once. Returns the thread that
/// finishes shutting down its workers.
fn begin_close(&self, window: &str) -> Option<std::thread::JoinHandle<()>> {
/// Detaches the project from `window` synchronously so the caller (including the UI
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
/// background handle that stops its workers, agents, terminals and processes.
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
self.mcp_agent_runs.forget_window(window);
@@ -396,78 +421,115 @@ impl Host {
phpstan.stop();
}
project.documents.clear_workspace_edit_history();
project.agents.shutdown();
project.agents.detach_sinks();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
project.notebooks.stop_admission();
// What the closing window started goes with it — the builds and searches it
// asked for, its runs, its shells and its debug sessions — and its language
// servers shut down.
self.processes.kill_project(&project.root);
self.terminals.kill_key(self.owner_window(window));
Some(self.spawn_project_shutdown(
vec![project.notebooks.clone()],
project.kotlin_bridge.iter().cloned().collect(),
Some(project.lsp.clone()),
// Detach runs and terminals synchronously so a new project opened in the same window
// never collides with them, then terminate them and shut down agents on the background thread.
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
Some(project),
))
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
terminals: Some(terminals),
processes: Some(processes),
retired: Some(project),
});
Some(DetachedClose { root, handle })
}
/// Project/window destruction must finish owned kernel cleanup, not enqueue
/// Project/window destruction must finish owned kernel and agent cleanup, not enqueue
/// work which can be lost as the desktop runtime exits: the returned thread is
/// joined by the closer or, for a detached close, before exit.
fn spawn_project_shutdown(
&self,
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
retired: Option<Arc<Project>>,
) -> std::thread::JoinHandle<()> {
for bridge in &bridges {
fn spawn_project_shutdown(&self, work: ShutdownWork) -> std::thread::JoinHandle<()> {
for bridge in &work.bridges {
bridge.stop();
}
for service in &notebooks {
for service in &work.notebooks {
service.stop_admission();
}
let runtime = self.runtime.clone();
std::thread::spawn(move || {
if let Some(processes) = work.processes {
processes.kill();
}
if let Some(terminals) = work.terminals {
terminals.terminate();
}
let agents = (!work.agents.is_empty()).then(|| {
let agents = work.agents;
std::thread::spawn(move || {
for manager in agents {
manager.shutdown();
}
})
});
// Dropping the project stops its file watcher and index worker, which first finish the
// batch they are applying (many file events while a build writes its output), so it
// isn't done on the closing caller's thread (the UI thread for a window close).
let retired = retired.map(|project| std::thread::spawn(move || drop(project)));
let retired = work.retired.map(|project| std::thread::spawn(move || drop(project)));
runtime.block_on(async move {
for bridge in bridges {
for bridge in work.bridges {
bridge.shutdown().await;
}
for service in notebooks {
for service in work.notebooks {
service.shutdown().await;
}
if let Some(lsp) = lsp {
if let Some(lsp) = work.lsp {
lsp.shutdown_all().await;
}
if let Some((debug, key, root)) = debug {
if let Some((debug, key, root)) = work.debug {
debug.stop_key(&key).await;
if let Some(root) = root {
debug.stop_under(&root).await;
}
}
});
if let Some(agents) = agents {
let _ = agents.join();
}
if let Some(retired) = retired {
let _ = retired.join();
}
})
}
/// Waits for detached closes, so a project opened next never races the
/// language servers of one still shutting down (e.g. over a shared workspace).
/// Waits for every detached close to finish.
#[cfg(test)]
pub(crate) fn wait_detached_closes(&self) {
let pending: Vec<_> = self.closing.lock().drain(..).collect();
for shutdown in pending {
self.wait_blocking(shutdown);
self.wait_blocking(shutdown.handle);
}
}
/// Waits only for detached closes whose root overlaps `root`, so opening an unrelated project
/// never blocks on another project's background shutdown.
pub(crate) fn wait_detached_closes_for(&self, root: &std::path::Path) {
let matching = {
let mut closing = self.closing.lock();
closing.retain(|entry| !entry.handle.is_finished());
let mut wait = Vec::new();
let mut keep = Vec::new();
for entry in closing.drain(..) {
if entry.root.as_deref().is_some_and(|other| roots_overlap(other, root)) {
wait.push(entry.handle);
} else {
keep.push(entry);
}
}
*closing = keep;
wait
};
for handle in matching {
self.wait_blocking(handle);
}
}
@@ -493,18 +555,23 @@ impl Host {
/// Called before the desktop runtime exits, including update/restart exits, on
/// the event-loop thread: waits for detached closes and the open projects'
/// kernels, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// stuck on the event loop cannot keep the process from exiting.
pub fn shutdown_notebooks_on_exit(&self) {
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).collect();
pending.push(self.spawn_project_shutdown(
projects.iter().map(|project| project.notebooks.clone()).collect(),
projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
None,
None,
None,
));
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
pending.push(self.spawn_project_shutdown(ShutdownWork {
notebooks: projects.iter().map(|project| project.notebooks.clone()).collect(),
bridges: projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
lsp: None,
debug: None,
agents: projects.iter().map(|project| project.agents.clone()).collect(),
terminals: None,
processes: None,
retired: None,
}));
}
let deadline = std::time::Instant::now() + EXIT_SHUTDOWN_WAIT;
while pending.iter().any(|handle| !handle.is_finished()) {
if std::time::Instant::now() >= deadline {
+1
View File
@@ -513,6 +513,7 @@ async fn resolve_jvm_application(
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
false,
policy,
&cancel,
None,
+97 -4
View File
@@ -9,6 +9,7 @@ use crate::{Host, Project};
use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::jbuild::Target;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
@@ -975,11 +976,38 @@ pub async fn build_run(
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
// A Maven or Gradle project builds with the IDE's Java build (#4078), unless its
// settings ask for the build tool, or it can't.
if single {
let model = with_profiles(load(&root, &cache, &settings), &cache);
let served = match file.as_deref() {
Some(module) => super::java::served_by_service(&root, &model, &settings, module),
None => super::java::project_served_by_service(&model, &settings),
};
if served {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &root,
cache: &cache,
settings: &settings,
model: &model,
};
let target = match file.as_deref() {
Some(file) => Target::Module(file),
None => Target::Project,
};
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
// are still accurate.
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
if single && kind == BuildKind::Build {
let model = with_profiles(load(&root, &cache, &settings), &cache);
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
@@ -1102,13 +1130,59 @@ pub async fn build_run(
let outcome = result?;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk.
if outcome.system == ide_build::compile::BuildSystem::Maven {
// still needs this: the classes can already be on disk. The IDE's Java build
// generates them with Maven too.
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds.
/// Diagnostics of `clear` are cleared once the service builds; its messages are published.
#[allow(clippy::too_many_arguments)]
fn service_build_result(
service: &super::java::ServiceBuild,
target: Target,
kind: BuildKind,
clear: &[std::path::PathBuf],
sink: &ide_core::SharedSink,
token: &CancellationToken,
on_event: &Channel<BuildEvent>,
) -> IdeResult<Option<BuildResult>> {
let started = std::time::Instant::now();
let title = std::sync::Mutex::new(String::new());
let forward = |event: BuildEvent| {
if let BuildEvent::Started { title: t, .. } = &event {
*title.lock().unwrap() = t.clone();
}
let _ = on_event.send(event);
};
let built = service.build(target, kind, token, &forward)?;
let Some(outputs) = built else { return Ok(None) };
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.clone().into(),
source: compile::DIAGNOSTICS_SOURCE.into(),
items: Vec::new(),
});
}
for (path, items) in compile::diagnostics(&outputs.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
let count =
|severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32;
Ok(Some(BuildResult {
system: compile::BuildSystem::Javac,
title: title.into_inner().unwrap(),
success: outputs.failure.is_none(),
errors: count(ide_core::Severity::Error),
warnings: count(ide_core::Severity::Warning),
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
messages: outputs.messages,
}))
}
fn plan_compile_file(
root: &Path,
cache: &Path,
@@ -1167,7 +1241,26 @@ pub async fn build_compile_file(
};
let sink = project.sink.clone();
let token = host.begin_project_request(window, request);
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
{
let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache);
if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &scope.root,
cache: &scope.cache,
settings: &scope.settings,
model: &model,
};
let target = Target::File(&file);
let kind = BuildKind::Build;
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
@@ -1190,7 +1283,7 @@ pub async fn build_compile_file(
.await;
host.end_request(request);
let outcome = result?;
if outcome.system == ide_build::compile::BuildSystem::Maven {
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
project.lsp.sync_maven_generated_sources(&scope_root).await;
}
Ok(outcome)
+231 -12
View File
@@ -9,6 +9,7 @@ use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile::{self, BuildEvent};
use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target};
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -22,12 +23,16 @@ use std::path::{Path, PathBuf};
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
/// whose build another launch's build joins receives that build's events.
/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language
/// server serves: java-debug's HotSwap reloads the classes the language server compiles.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
@@ -39,16 +44,18 @@ pub async fn java_resolve_launch(
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await;
host.end_request(request);
result
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
@@ -73,13 +80,12 @@ pub(crate) async fn resolve_launch(
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, is_maven) = {
let (model, external, mut delegated, is_maven, non_java, served) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
@@ -89,6 +95,7 @@ pub(crate) async fn resolve_launch(
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let served = served_by_service(root, &model, &scope.settings, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
@@ -98,11 +105,65 @@ pub(crate) async fn resolve_launch(
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, is_maven)
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
};
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
// either way.
if served && !non_java && !debug {
let built = {
let (service, data_dir, scope, model, module, cancel, events) = (
host.java_build.clone(),
host.local_data_dir.clone(),
scope.clone(),
model.clone(),
module.clone(),
cancel.clone(),
events.clone(),
);
tokio::task::spawn_blocking(move || {
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let kind = build.then_some(build_kind);
build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if let Some(outputs) = built {
progress("Resolving the classpath");
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
return tokio::task::spawn_blocking(move || {
// javac's verdict replaces JDT's, as a Maven build's does.
if build {
apply_external_build_result(&mut info, outputs.failure, true);
}
info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test);
finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
tracing::info!(
total_ms = started.elapsed().as_millis(),
"Java launch resolved with the IDE's Java build"
);
Ok(info)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
}
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
@@ -124,7 +185,6 @@ pub(crate) async fn resolve_launch(
drop_processor_recreate_errors(&mut info);
}
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
@@ -217,6 +277,104 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident
/// process with the configuration Maven gives the compiler, into outputs in the project cache
/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs
/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs.
/// Without `kind` (no build before launch), the outputs of its last build, if any.
#[allow(clippy::too_many_arguments)]
fn build_with_service(
service: &JavaBuildService,
data_dir: &Path,
scope: &workspace::Scope,
model: &BuildModel,
module: &Path,
test: bool,
kind: Option<compile::BuildKind>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let service =
ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model };
match kind {
Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event),
// No build: the outputs of the last one, when there was one.
None => Ok(service
.with(module, |build| build.recorded_launch(module, test))
.flatten()
.map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })),
}
}
/// A build of the IDE's Java build service in one project (or workspace member).
pub(crate) struct ServiceBuild<'a> {
pub service: &'a JavaBuildService,
pub data_dir: &'a Path,
pub root: &'a Path,
pub cache: &'a Path,
pub settings: &'a Settings,
pub model: &'a BuildModel,
}
impl ServiceBuild<'_> {
/// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar
/// can't be installed.
fn with<R>(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option<R> {
let jar = ide_sdk::java::java_build_jar(self.data_dir)?;
let (root, settings) = (self.root, self.settings);
let jdk = |release: Option<u32>| {
ide_sdk::apply::module_jdk(root, module, settings)
.or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned())
.map(|jdk| jdk.home)
};
let version = ide_sdk::java::java_build_version();
let build = JavaBuild {
root,
model: self.model,
cache: self.cache,
jar: &jar,
jar_version: &version,
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
service: self.service,
jdk: &jdk,
};
Some(f(&build))
}
/// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed).
pub fn build(
&self,
target: Target,
kind: compile::BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let module = match target {
Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module,
Target::Project => self.root,
};
let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else {
return Ok(None);
};
match built {
Ok(Built::Done(outputs)) => Ok(Some(outputs)),
Ok(Built::Unsupported(reason)) => {
tracing::info!(module = %module.display(), reason, "Building with the build tool");
Ok(None)
}
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
Err(e) => {
tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message);
on_event(BuildEvent::Output {
text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message),
stderr: true,
});
Ok(None)
}
}
}
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
@@ -225,6 +383,39 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
/// when Settings › Gradle › Build and run using asks for the IDE.
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
// The deepest module holding it; Maven's when both build the folder.
let module = maven
.chain(gradle)
.filter(|(dir, _)| path.starts_with(dir))
.max_by_key(|(dir, maven)| (dir.components().count(), *maven));
match module {
Some((_, true)) => !settings.languages.java.maven.delegate_build,
Some((_, false)) => gradle_served(settings),
None => false,
}
}
/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and
/// builds them all.
pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool {
let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build);
let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings));
match (maven, gradle) {
(None, None) => false,
(maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true),
}
}
fn gradle_served(settings: &Settings) -> bool {
settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
#[allow(clippy::too_many_arguments)]
@@ -241,8 +432,9 @@ async fn resolve_launch_without_jdtls(
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (model, built, by_service) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
@@ -250,12 +442,33 @@ async fn resolve_launch_without_jdtls(
events(event);
}
};
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
};
(model, built)
if policy == BuildPolicy::NoBuild {
return (model, None, false);
}
if served_by_service(&scope.root, &model, &scope.settings, &module)
&& !compile::launch_has_non_java_sources(&scope.root, &model, &module, test)
{
match build_with_service(
&service,
&data_dir,
&scope,
&model,
&module,
test,
Some(kind),
&cancel,
&on_event,
) {
Ok(Some(outputs)) => {
let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure };
return (model, Some(Ok(built)), true);
}
Ok(None) => {}
Err(e) => return (model, Some(Err(e)), false),
}
}
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
(model, Some(built), false)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -294,6 +507,12 @@ async fn resolve_launch_without_jdtls(
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
+21 -3
View File
@@ -4,8 +4,10 @@
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_core::event::NotifyLevel;
use ide_core::remote_settings::SshConfiguration;
use ide_core::{IdeError, IdeEvent, IdeResult};
use ide_ssh::secrets::LegacyPasswordAction;
/// Test Connection: connects with `config` as edited (not necessarily saved).
#[command(trust = always)]
@@ -15,8 +17,23 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
#[command(trust = always)]
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
host.ssh.set_secret(&id, secret, save);
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
host.window_sink(window).emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Could not save credential".into(),
body: Some(e.message),
});
}
}
/// `Some` means legacy credentials remain in plaintext on this host.
#[command(trust = always)]
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
let ssh = host.ssh.clone();
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Whether a password is saved under `key` (an FTP deployment server's).
@@ -52,6 +69,7 @@ ide_command::domain!(
ssh:
ssh_connected,
ssh_disconnect,
ssh_legacy_passwords,
ssh_needs_secret,
ssh_password_saved,
ssh_set_secret,
+6 -4
View File
@@ -125,8 +125,8 @@ impl Host {
// A window takes the root over from the MCP server's background project, whose
// shutdown the wait below sits out; none opens until this open is over.
let _claim = (!crate::mcp::BackgroundProjects::is_key(window)).then(|| self.mcp_background.claim(self, &root));
self.close_project(window);
self.wait_detached_closes();
self.close_project_detached(window);
self.wait_detached_closes_for(&root);
let sink: SharedSink = (self.sink_for)(window);
// Before anything the project starts: its children get the project's environment.
let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?));
@@ -867,8 +867,10 @@ impl Host {
}
return Ok(current);
}
self.close_project(window);
self.wait_detached_closes();
self.close_project_detached(window);
if let Some(dir) = watch_dir {
self.wait_detached_closes_for(dir);
}
let sink: SharedSink = (self.sink_for)(window);
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
let effective = settings.effective();
+20
View File
@@ -2,6 +2,26 @@ mod common;
use ide_host::{Host, HostConfig, ops};
#[tokio::test]
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(&config.data_dir).unwrap();
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
let host = Host::new(config);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("startup migration");
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
let tmp = tempfile::tempdir().unwrap();
+215
View File
@@ -0,0 +1,215 @@
mod common;
use ide_build::compile::BuildEvent;
use ide_core::RequestId;
use ide_host::{Host, ops};
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::fs;
use std::path::Path;
use std::sync::{Arc, Mutex};
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn maven_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
eprintln!("skipped: needs JAVA_HOME and mvn");
return;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(
&root,
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
);
write(
&root,
"lib/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
// No language server: the build tool compiles the launch.
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/target/classes").exists());
// Build › Build Project compiles with it too, and reports javac's errors.
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert!(!built.success);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
assert!(!root.join("lib/target/classes").exists());
host.shutdown().await;
}
/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile
/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`).
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gradle_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else {
eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE");
return;
};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n");
write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n");
write(&root, "lib/build.gradle", "");
write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n");
write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display()));
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap();
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/build/classes").exists());
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
host.shutdown().await;
}
+2 -1
View File
@@ -136,7 +136,8 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
save_secret: true,
..Default::default()
}]);
ssh.set_secret("local-test", Some("secret".into()), true);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
ssh.trust_host("local-test").await.unwrap();
ssh.session("local-test").await.unwrap()
+26 -1
View File
@@ -10,6 +10,30 @@ use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
#[tokio::test]
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
let (tx, rx) = mpsc::channel();
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| {
let tx = tx.clone();
Arc::new(move |e| tx.send(e).unwrap())
}),
..config
});
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
let warning = rx.try_iter().find_map(|e| match e {
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
_ => None,
});
let warning = warning.expect("the window should be told saving failed");
assert!(warning.contains("session only"));
assert!(!warning.contains("test-value"));
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
}
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
let mut all = String::new();
while !all.contains(needle) {
@@ -38,7 +62,8 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
save_secret: true,
..Default::default()
}]);
ssh.set_secret("box", Some("secret".into()), true);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("box", Some("secret".into()), true).unwrap();
assert!(ssh.session("box").await.is_err(), "unknown host key first");
ssh.trust_host("box").await.unwrap();
+1 -1
View File
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
auth: SshAuth::Password,
..Default::default()
}]);
ssh.set_secret("selected-host", Some("secret".into()), false);
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
assert!(ssh.session("selected-host").await.is_err());
ssh.trust_host("selected-host").await.unwrap();
+15 -5
View File
@@ -88,10 +88,18 @@ done
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
let info =
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
.await
.unwrap();
let info = ops::java::java_resolve_launch(
&host,
"main",
module,
test,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
// The build streams its command and progress while it runs.
use ide_build::compile::BuildEvent;
let events = events.lock().unwrap();
@@ -110,7 +118,9 @@ done
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
// This Maven records no build model for the IDE's Java build, so Maven builds the module.
assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}");
assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
}
+104
View File
@@ -1188,3 +1188,107 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}");
mgr.shutdown_all().await;
}
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
/// its build is what reports an API change in one Maven module in the files of the modules
/// that use it, open or not. With `java.autobuild.enabled: false` (and
/// `validateAllOpenBuffersOnChanges`), neither updates.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"]
async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap().join("project");
let write = |rel: &str, text: &str| {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
};
let parent = r#"<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>"#;
write(
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>app</module></modules><properties><maven.compiler.release>11</maven.compiler.release></properties></project>"#,
);
write(
"lib/pom.xml",
&format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>lib</artifactId></project>"),
);
write(
"app/pom.xml",
&format!(
"<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"
),
);
let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n";
let app_source = "package a;\npublic class A { String s = l.L.name(); }\n";
let lib = write("lib/src/main/java/l/L.java", lib_source);
let app = write("app/src/main/java/a/A.java", app_source);
let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n");
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
java.language_servers.retain(|s| s.name == "jdtls");
let server = &mut java.language_servers[0];
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
server.command = bin;
}
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
let (lib_doc, app_doc) = (DocId::next(), DocId::next());
mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source);
mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source);
let errors = |path: &Path| {
events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some(
items
.iter()
.filter(|d| d.severity == ide_core::Severity::Error)
.map(|d| d.message.clone())
.collect::<Vec<_>>(),
),
_ => None,
})
};
// The import resolves `lib` from source: the open editor of `app` has no errors.
retry("app imported", Duration::from_secs(300), || {
let status = last_status(&events, "jdtls");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
panic!("jdtls failed: {message:?}");
}
let clean = errors(&app).is_some_and(|e| e.is_empty());
let mgr = mgr.clone();
let app = app.clone();
async move {
let cp =
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default()))
.await
.ok()?
.ok()?;
(clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(())
}
})
.await;
// Rename the method in the editor of `lib`, and save.
let renamed = lib_source.replace("name()", "title()");
let line = lib_source.lines().nth(1).unwrap();
mgr.did_change(
lib_doc,
2,
&[AppliedChange {
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
text: renamed.lines().nth(1).unwrap().to_owned(),
}],
&|| renamed.clone(),
);
std::fs::write(&lib, &renamed).unwrap();
mgr.did_save(lib_doc, &renamed);
retry("the open editor of app reports the removed method", Duration::from_secs(120), || {
let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
retry("the closed file of app reports it too", Duration::from_secs(60), || {
let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
+1 -1
View File
@@ -21,7 +21,7 @@ mod utf8;
pub mod wrap;
pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake};
pub use process::{ProcessManager, StartOptions};
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
use ide_core::{IdeResult, RunId};
use serde::{Deserialize, Serialize};
+28 -4
View File
@@ -3,9 +3,10 @@
use crate::utf8::OutputDecoder;
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
use ide_core::pty::native_pty_system;
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use parking_lot::Mutex;
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use portable_pty::{CommandBuilder, MasterPty, PtySize};
use std::collections::{BTreeMap, VecDeque};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
@@ -887,15 +888,25 @@ impl ProcessManager {
}
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
/// Collects every running process tree for `root` and marks it stopping so the actual
/// termination can run on a background thread without blocking the UI thread or racing
/// processes started later.
pub fn detach_project_kills(&self, root: &Path) -> DetachedProcessKills {
let mut targets = Vec::new();
for entry in self.runs.lock().values().filter(|e| e.project_root == root) {
if !entry.exited.load(Ordering::Acquire)
&& let Some(pid) = *entry.pid.lock()
{
kill_tree(entry, pid, true);
entry.stopping.store(true, Ordering::Release);
targets.push((entry.clone(), pid));
}
}
DetachedProcessKills(targets)
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
self.detach_project_kills(root).kill();
}
pub fn kill_all(&self) {
@@ -938,6 +949,19 @@ impl ProcessManager {
}
}
/// Running process trees snapshotted from [`ProcessManager`] to be killed off the caller's thread.
pub struct DetachedProcessKills(Vec<(Arc<Entry>, u32)>);
impl DetachedProcessKills {
pub fn kill(self) {
for (entry, pid) in self.0 {
if !entry.exited.load(Ordering::Acquire) {
kill_tree(&entry, pid, true);
}
}
}
}
impl Drop for ProcessManager {
fn drop(&mut self) {
self.kill_all();
+17
View File
@@ -1654,6 +1654,23 @@ pub fn junit_runner_jar(data_dir: &Path) -> Option<PathBuf> {
)
}
/// The IDE's Java build (`java/java-build`): the resident javac server and the Maven
/// extension that records the build model.
const JAVA_BUILD: &[u8] = include_bytes!("../../../java/java-build/openidea-java-build.jar");
/// Extracts the Java build jar into the application's data directory.
pub fn java_build_jar(data_dir: &Path) -> Option<PathBuf> {
install_bundle(data_dir, "java-build", "1.0.0", JAVA_BUILD)
}
/// Changes whenever the embedded Java build jar does (FNV-1a of its bytes), so build models
/// recorded by an older extension are prepared again.
pub fn java_build_version() -> String {
let hash =
JAVA_BUILD.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3));
format!("{hash:016x}")
}
/// The JUnit Platform launcher a test classpath needs to start the runner.
#[derive(Debug, PartialEq)]
pub enum JunitLauncher {
+4 -3
View File
@@ -11,7 +11,7 @@ use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::time::Duration;
fn fake_venv(root: &Path, name: &str) -> std::path::PathBuf {
@@ -2103,8 +2103,9 @@ fn the_flutter_sdk_setting_picks_flutter_and_dart_for_server_and_run_configurati
// Saved configurations keep the bare name.
assert_eq!(crate::apply::without_derived(&configs[0], tmp.path(), &s).command, "flutter");
// An explicit tool path still wins.
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: "/opt/dart/bin/dart".into() });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(PathBuf::from("/opt/dart/bin/dart")));
let explicit = tmp.path().join("opt").join("dart");
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: explicit.to_string_lossy().into_owned() });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(explicit));
}
#[test]
+24 -8
View File
@@ -1,7 +1,7 @@
//! App-wide SSH connections, one per SSH configuration, shared by every
//! feature that works on that host (deployment, run targets, data sources).
use crate::secrets::SecretFile;
use crate::secrets::{LegacyPasswordAction, SecretFile};
use crate::session::{ConnectError, Session, UnknownHostKey};
use crate::target::{SshFiles, SshTarget};
use ide_core::remote_settings::{SshAuth, SshConfiguration};
@@ -14,6 +14,7 @@ use std::sync::Arc;
pub struct SshManager {
files: SshFiles,
saved: SecretFile,
startup_migration: std::sync::Once,
/// Secrets entered this session (not saved, or not yet), by configuration id.
entered: Mutex<HashMap<String, String>>,
configs: RwLock<Vec<SshConfiguration>>,
@@ -34,7 +35,8 @@ impl SshManager {
pub fn with_files(secrets: PathBuf, files: SshFiles) -> Self {
Self {
files,
saved: SecretFile::new(secrets),
saved: SecretFile::ssh_passwords(secrets),
startup_migration: std::sync::Once::new(),
entered: Mutex::default(),
configs: RwLock::default(),
sessions: Mutex::default(),
@@ -47,6 +49,19 @@ impl SshManager {
&self.files
}
pub fn start_password_migration(&self) {
self.startup_migration.call_once(|| match self.saved.resolve_legacy(LegacyPasswordAction::Retry) {
Ok(None) => {}
Ok(Some(why)) => tracing::warn!("ssh-passwords.json still contains legacy plaintext credentials: {why}"),
Err(e) => tracing::warn!("could not check ssh-passwords.json: {}", e.message),
});
}
pub fn resolve_legacy_passwords(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
self.start_password_migration();
self.saved.resolve_legacy(action)
}
/// Replaces the configurations (Settings › SSH Configurations); sessions of
/// changed or removed ones are closed, secrets of removed ones forgotten.
pub fn set_configs(&self, configs: Vec<SshConfiguration>) {
@@ -86,7 +101,7 @@ impl SshManager {
/// Remembers the password / passphrase of configuration `id` for the session,
/// and in the saved passwords with `save` (`None` forgets it).
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) {
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
match &secret {
Some(s) => {
self.entered.lock().insert(id.to_owned(), s.clone());
@@ -96,12 +111,13 @@ impl SshManager {
}
}
match (secret, save) {
(Some(s), true) => {
if let Err(e) = self.saved.set(id, &s) {
tracing::warn!("could not save the SSH password: {}", e.message);
}
(Some(s), true) => self.saved.set(id, &s).map_err(|e| {
IdeError::unavailable(format!("The credential was kept for this session only. {}", e.message))
}),
_ => {
self.saved.delete(id);
Ok(())
}
_ => self.saved.delete(id),
}
}
+162 -15
View File
@@ -25,6 +25,14 @@ static LOCK: Mutex<()> = Mutex::new(());
/// Reads the secrets of an older version's file, by key (`None`: not that format).
pub type Legacy = fn(serde_json::Value) -> Option<BTreeMap<String, String>>;
#[derive(Clone, Copy, Deserialize, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum LegacyPasswordAction {
Check,
Retry,
RemovePlaintext,
}
/// Where the secrets are kept: the default credential store, or a stand-in in tests.
pub trait Vault: Send + Sync {
fn available(&self) -> bool;
@@ -77,6 +85,7 @@ pub struct SecretFile {
path: PathBuf,
legacy: Legacy,
vault: Arc<dyn Vault>,
keep_legacy_until_moved: bool,
}
/// The file's contents. `id` keeps the credentials of different data directories
@@ -87,6 +96,11 @@ struct Index {
keys: BTreeSet<String>,
}
enum Stored {
Index(Index),
Legacy(BTreeMap<String, String>),
}
enum Contents {
Index(Index),
/// An older version's file that could not be moved, and why.
@@ -122,12 +136,17 @@ impl SecretFile {
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
}
/// For the startup migration with a user-visible choice to retry or discard.
pub(crate) fn ssh_passwords(path: PathBuf) -> Self {
Self { keep_legacy_until_moved: true, ..Self::new(path) }
}
pub fn with_legacy(path: PathBuf, legacy: Legacy) -> Self {
Self::with_vault(path, legacy, Arc::new(DefaultStore))
}
pub fn with_vault(path: PathBuf, legacy: Legacy, vault: Arc<dyn Vault>) -> Self {
Self { path, legacy, vault }
Self { path, legacy, vault, keep_legacy_until_moved: false }
}
pub fn get(&self, key: &str) -> Option<String> {
@@ -222,23 +241,75 @@ impl SecretFile {
})
}
fn load(&self) -> Contents {
let value = match std::fs::read(&self.path) {
Err(_) => return Contents::Index(Index { id: new_id(), keys: BTreeSet::new() }),
Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(v) => v,
Err(e) => return self.set_aside(&e.to_string()),
},
fn read(&self) -> std::io::Result<Stored> {
use std::io::{Error, ErrorKind};
let bytes = match std::fs::read(&self.path) {
Err(e) if e.kind() == ErrorKind::NotFound => {
return Ok(Stored::Index(Index { id: new_id(), keys: BTreeSet::new() }));
}
other => other?,
};
let value = serde_json::from_slice::<serde_json::Value>(&bytes)
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid JSON"))?;
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
return Contents::Index(index);
return Ok(Stored::Index(index));
}
match (self.legacy)(value) {
Some(old) => self.migrate(old),
None => self.set_aside("unknown format"),
(self.legacy)(value).map(Stored::Legacy).ok_or_else(|| Error::new(ErrorKind::InvalidData, "unknown format"))
}
fn load(&self) -> Contents {
match self.read() {
Ok(Stored::Index(index)) => Contents::Index(index),
Ok(Stored::Legacy(old)) => self.migrate(old),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => self.set_aside(&e.to_string()),
Err(e) => Contents::Plaintext(BTreeMap::new(), format!("{}: {e}", self.path.display())),
}
}
/// `Some` means plaintext remains. Never overwrite an index that another window
/// already migrated; an unreadable file is set aside, as on any other access.
pub(crate) fn resolve_legacy(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
off_runtime(|| {
let _g = LOCK.lock();
let old = match self.read() {
Ok(Stored::Legacy(old)) => old,
Ok(Stored::Index(_)) => return Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
return match self.set_aside(&e.to_string()) {
Contents::Index(_) => Ok(None),
Contents::Plaintext(_, why) => Err(unavailable(&why)),
};
}
Err(e) => return Err(unavailable(&format!("{}: {e}", self.path.display()))),
};
if matches!(action, LegacyPasswordAction::Check) && !old.is_empty() {
return Ok(Some("Migration is incomplete.".into()));
}
if matches!(action, LegacyPasswordAction::RemovePlaintext) || old.is_empty() {
// A partial move may already have secured some keys. Preserve their
// namespace without needing the vault to be unlocked to remove plaintext.
let pending = self.pending_path();
let index = match std::fs::read_to_string(&pending) {
Ok(id) if !id.trim().is_empty() => Index { id: id.trim().into(), keys: old.into_keys().collect() },
Ok(_) => return Err(unavailable("empty migration id")),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Index { id: new_id(), keys: BTreeSet::new() },
Err(e) => return Err(unavailable(&format!("{}: {e}", pending.display()))),
};
self.write(&index)?;
if let Err(e) = std::fs::remove_file(&pending)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("saved passwords: could not remove {}: {e}", pending.display());
}
return Ok(None);
}
Ok(match self.migrate(old) {
Contents::Index(_) => None,
Contents::Plaintext(_, why) => Some(why),
})
})
}
/// An unreadable file is renamed rather than overwritten (it may index
/// credentials, or hold secrets); the store starts over.
fn set_aside(&self, why: &str) -> Contents {
@@ -262,8 +333,8 @@ impl SecretFile {
}
/// Moves an older version's secrets to the credential store, key by key; a secret
/// the store refuses for good (too long, say) is forgotten, and the user is asked
/// for it again. The old file is replaced only when everything else was moved.
/// the store refuses for good (too long, say) is forgotten unless the caller
/// offers explicit recovery. The old file is replaced only when everything else was moved.
/// Until then the id waits in `<file>.migrating`, so a retry after a failure or a
/// crash overwrites the same credentials instead of copying them again.
fn migrate(&self, old: BTreeMap<String, String>) -> Contents {
@@ -287,7 +358,7 @@ impl SecretFile {
Ok(()) => {
index.keys.insert(key.clone());
}
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) => {
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) if !self.keep_legacy_until_moved => {
tracing::warn!("saved passwords: {key} does not fit the credential store and is forgotten: {e}");
}
Err(e) => {
@@ -425,6 +496,82 @@ mod tests {
const OLD: &str = r#"{"https://a.example": "me\nold-a", "https://b.example": "me\nold-b"}"#;
#[test]
fn a_pending_plaintext_migration_can_be_retried_or_explicitly_discarded() {
use LegacyPasswordAction::{Check, RemovePlaintext, Retry};
for discard in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = with_fake(&path, &vault);
assert!(file.resolve_legacy(Check).unwrap().is_none());
assert!(!path.exists());
std::fs::write(&path, OLD).unwrap();
vault.fail("https://b.example", platform);
assert!(file.resolve_legacy(Retry).unwrap().is_some());
assert!(file.resolve_legacy(Check).unwrap().is_some());
assert_eq!(std::fs::read_to_string(&path).unwrap(), OLD);
if discard {
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
}
vault.heal();
assert!(file.resolve_legacy(Retry).unwrap().is_none());
// A stale action from another window cannot erase a migrated index.
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
assert_eq!(files_containing(tmp.path(), "old-"), Vec::<PathBuf>::new());
assert_eq!(file.get("https://a.example").as_deref(), Some("me\nold-a"));
assert_eq!(file.get("https://b.example").as_deref(), (!discard).then_some("me\nold-b"));
}
}
#[test]
fn removing_plaintext_needs_no_vault_and_sets_an_unknown_format_aside() {
use LegacyPasswordAction::{RemovePlaintext, Retry};
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault { absent: true, ..Default::default() });
let file = with_fake(&path, &vault);
std::fs::write(&path, OLD).unwrap();
assert!(file.resolve_legacy(Retry).unwrap().is_some());
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
assert!(files_containing(tmp.path(), "old-").is_empty());
assert!(file.keys().is_empty());
std::fs::write(&path, "unknown-format").unwrap();
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
let aside = files_containing(tmp.path(), "unknown-format");
assert_eq!(aside.len(), 1);
assert_ne!(aside[0], path);
}
#[test]
fn ssh_keeps_the_only_copy_until_the_user_can_choose_what_to_do() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
vault.fail("box", || StoreError::TooLong("password".into(), 2560));
std::fs::write(&path, r#"{"box":"legacy-value"}"#).unwrap();
assert!(file.resolve_legacy(LegacyPasswordAction::Retry).unwrap().is_some());
assert_eq!(file.get("box").as_deref(), Some("legacy-value"));
assert_eq!(files_containing(tmp.path(), "legacy-value"), std::slice::from_ref(&path));
}
#[test]
fn a_malformed_ssh_file_is_set_aside_instead_of_blocking_new_saves() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
std::fs::write(&path, "{ malformed").unwrap();
assert!(file.resolve_legacy(LegacyPasswordAction::Check).unwrap().is_none());
let aside = files_containing(tmp.path(), "{ malformed");
assert_eq!(aside.len(), 1);
assert_ne!(aside[0], path);
file.set("box", "new-value").unwrap();
assert_eq!(file.get("box").as_deref(), Some("new-value"));
assert!(files_containing(tmp.path(), "new-value").is_empty());
}
#[test]
fn saved_secrets_never_reach_disk() {
use_memory_store();
+22 -6
View File
@@ -4,10 +4,11 @@
mod integration;
mod scrollback;
use ide_core::pty::native_pty_system;
use ide_core::utf8::Utf8Decoder;
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
use parking_lot::{Condvar, Mutex};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashMap};
@@ -509,13 +510,17 @@ impl TerminalManager {
}
}
/// Detaches every terminal opened by `key` so it can be terminated on a background thread
/// without blocking the caller or racing a new project opened in the same window.
pub fn detach_key(&self, key: &str) -> DetachedTerminals {
let mut sessions = self.sessions.lock();
let ids: Vec<TerminalId> = sessions.iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect();
DetachedTerminals(ids.into_iter().filter_map(|id| sessions.remove(&id)).collect())
}
/// Closes the terminals `key` opened: the project of that window is closing.
pub fn kill_key(&self, key: &str) {
let ids: Vec<TerminalId> =
self.sessions.lock().iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect();
for id in ids {
let _ = self.kill(id);
}
self.detach_key(key).terminate();
}
pub fn kill(&self, id: TerminalId) -> IdeResult<()> {
@@ -732,6 +737,17 @@ mod win {
}
}
/// Terminal sessions detached from [`TerminalManager`] to be terminated off the caller's thread.
pub struct DetachedTerminals(Vec<Arc<Session>>);
impl DetachedTerminals {
pub fn terminate(self) {
for session in self.0 {
terminate(&session);
}
}
}
/// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers.
fn terminate(session: &Session) {
let (writer, killer) = match &session.io {
+5
View File
@@ -46,6 +46,11 @@ through the app-wide SSH configurations.
Saved passwords and passphrases go to the macOS Keychain, Windows Credential Manager or the Secret Service on Linux,
never to a settings file. The **+**, **−** and copy buttons above the list add, remove and duplicate configurations.
Older versions stored saved credentials in plaintext in `ssh-passwords.json`. On startup, OpenIDEA moves them into
the OS credential store. If the file still contains passwords, unlock the store and choose **Retry migration**, or
choose **Remove plaintext copy** and re-enter any credentials that were not migrated. New credentials that cannot
be saved are kept only for the session. Migration does not change old backups: rotate any exposed password.
### `~/.ssh/config` support
OpenIDEA has its own SSH client and reads `~/.ssh/config` itself. It understands `Host`, `Match`, `Include`,
+4
View File
@@ -38,6 +38,10 @@ OpenIDEA 通过 SSH 连接;在 Windows 上也可以直接连入 WSL 发行版
保存的密码和密码短语存放在 macOS 钥匙串、Windows 凭据管理器或 Linux 的 Secret Service 中,不会写进设置文件。列表上方的
**+**、**−** 和复制按钮用于添加、移除和复制配置。
旧版本会在 `ssh-passwords.json` 中明文保存凭据。OpenIDEA 会在启动时将它们迁移到系统凭据库。
如果文件中仍有密码,可以解锁凭据库后选择**重试迁移**,也可以选择**移除明文副本**,并在下次使用时重新输入未迁移的凭据。
无法保存的新凭据仅在当前会话中有效。迁移不会更改旧备份;如果备份中的密码已泄露,请更换密码。
### `~/.ssh/config` 支持
OpenIDEA 自带 SSH 客户端,自行读取 `~/.ssh/config`,支持 `Host`、`Match`、`Include`、`HostName`、`User`、`Port`、
+3
View File
@@ -44,6 +44,9 @@ async function requestClose(
idlePolicy: { overrideSeconds },
});
window.__ipc.handlers.window_close_context = () => ({ windows, quitting });
window.__ipc.handlers.window_begin_prompt = () => true;
window.__ipc.handlers.window_end_prompt = () => null;
window.__ipc.handlers.window_ready_to_close = () => true;
window.__ipc.handlers.close_project = () => null;
window.__ipc.handlers.remote_invoke = ({ cmd }) => {
if (cmd === "remote_idle_timeout_minutes") {
+40
View File
@@ -0,0 +1,40 @@
# Java build
The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar holds two parts:
- `ai.openidea.javac.Server` (`src/`): a resident javac. OpenIDEA starts one per JDK (and
`.mvn/jvm.config`) as `java -cp openidea-java-build.jar ai.openidea.javac.Server` and keeps it
running between builds. It reads one JSON request per line on stdin and answers on stdout:
| Request | Meaning |
| ------------------------------------------------------------------------ | ----------------------------------------------- |
| `{"id":1,"op":"compile","options":[…],"sources":[…],"encoding":"UTF-8"}` | Compile with javac (`ToolProvider`), in process |
| `{"op":"cancel","id":1}` | Stop that compilation at javac's next phase |
| `{"op":"exit"}` | Finish the queued requests, then exit |
Replies carry the request's `id`: `diagnostic` (1-based line, 0-based UTF-16 column),
`output` (a class file and the source it came from), `generated` (a source an annotation
processor wrote), `output-text`, then `done`. `ready` and `fatal` concern the server.
- `ai.openidea.javac.maven.BuildModel` (`maven/`): a Maven core extension, loaded with
`-Dmaven.ext.class.path`. With `-Dopenidea.build.output=<dir>` it redirects every project's
output to `<dir>/<groupId>.<artifactId>/classes|test-classes`, and resolves reactor
projects to those folders. With `-Dopenidea.build.model=<file>` it writes, after the build,
each project's source roots, classpaths, resources and the configuration maven-compiler-plugin's
mojos get (including the resolved `annotationProcessorPaths`), as JSON.
OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs,
settings or generator inputs change, then compiles the launch's modules with the server.
Gradle builds get the same model from an init script instead
(`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with
`-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run
using is set to the IDE.
The jar is committed and embedded by `ide-sdk` (`java_build_jar`). It is built with `--release 8`
against Maven 3.9.11, whose files `build-dependencies.sha256` pins. Rebuild it after changing
the source:
```sh
JAVA_HOME=<JDK 11+> python3 build.py <apache-maven-3.9.11 folder>
```
+52
View File
@@ -0,0 +1,52 @@
0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08 maven/aopalliance-1.0.jar
876eab6a83daecad5ca67eb9fcabb063c97b5aeb8cf1fca7a989ecde17522051 maven/asm-9.8.jar
d3d530d0f28fd0fbbffe2b0b338f70e8cb96f1605579e2e3abd4db29cac24e69 maven/commons-cli-1.9.0.jar
ba005f304cef92a3dede24a38ad5ac9b8afccf0d8f75839d6c1338634cf7f6e4 maven/commons-codec-1.18.0.jar
6661d5335090a5fc61dd869d2095bc6c1e2156e3aa47a6e4ababdf64c99a7889 maven/error_prone_annotations-2.38.0.jar
cbfc3906b19b8f55dd7cfd6dfe0aa4532e834250d7f080bd8d211a3e246b59cb maven/failureaccess-1.0.3.jar
94855942d4992f112946d3de1c334e709237b8126d8130bf07807c018a4a2120 maven/gson-2.13.1.jar
f3d7f57f67fd622f4d468dfdd692b3a5e3909246c28017ac3263405f0fe617ed maven/guava-33.4.8-jre.jar
142ad4475e19524d2fe3ac995b3f7cbc962fc726f2edb9dbdccc61feab9b2bf9 maven/guice-5.1.0-classes.jar
c8bc7e1c51a6d4ce72f40d2ebbabf1c4b68bfe76e732104b04381b493478e9d6 maven/httpclient-4.5.14.jar
6c9b3dd142a09dc468e23ad39aad6f75a0f2b85125104469f026e52a474e464f maven/httpcore-4.4.16.jar
0b7b8b003a90ea491579b62f5118828e45112914c65589b00faa49d6ec785839 maven/jansi-2.4.2.jar
e04ba5195bcd555dc95650f7cc614d151e4bcd52d29a10b8aa2197f3ab89ab9b maven/javax.annotation-api-1.3.2.jar
91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff maven/javax.inject-1.jar
ab57ca8fd223772c17365d121f59e94ecbf0ae59d08c03a3cb5b81071c019195 maven/jcl-over-slf4j-1.7.36.jar
1fad6e6be7557781e4d33729d49ae1cdc8fdda6fe477bb0cc68ce351eafdfbab maven/jspecify-1.0.0.jar
0bfd1c121f907642344311d81e4dfd93eba6c24dc712cc0aeae273eb22833022 maven/maven-artifact-3.9.11.jar
5b1de1560ec19c4c69a655f986455888f3a0bcc3c160cac1f1edb87de3825f77 maven/maven-builder-support-3.9.11.jar
b0e2865fc808fd9fb3bee95bf37c0609eeb20c59bf1e6b958b37b365ee11f52e maven/maven-compat-3.9.11.jar
93d3c0523dda6c86c6620d9e692e7df39d0e2e4e4cd860061a8c0d274c2ad185 maven/maven-core-3.9.11.jar
7e15e05035331d0a7e0fe56d7354b2b30e15c0a8c60863cbf28df25190e197db maven/maven-embedder-3.9.11.jar
163aa596f976264384efeb50b4cb8a806086fd64a9b755ad1f69195fed3998ad maven/maven-model-3.9.11.jar
c4c72accdcd848332c1a37995610a6a369d49fdaabc43e85f0022a5b77de3ba7 maven/maven-model-builder-3.9.11.jar
8e985a56412564cf687040efed8bcd3a63eac2202a824bb01e1d5ece2b87458f maven/maven-plugin-api-3.9.11.jar
f8655f5f0060e0032944f2a23688d186e140d2184749bcfa1927f83cd6a8b1a2 maven/maven-repository-metadata-3.9.11.jar
c0ce14849298720dcf3b09fe9e263b3c576d2d6cd43c61f8aa9d6117e04e5e47 maven/maven-resolver-api-1.9.24.jar
18b7d557c41379db8b157ba95263c676f52c293f5416b67bd1db083e99b30383 maven/maven-resolver-connector-basic-1.9.24.jar
3cd88edda00c46242cdbe57aefb47703519d176d9e8a500333de15faf41b0e1d maven/maven-resolver-impl-1.9.24.jar
a222b0a5ca4c145e8e0f45207a23bcce18bdbe1f1c980e4e9fb332591ee8c91a maven/maven-resolver-named-locks-1.9.24.jar
b5d6e52ae1ecf1cb62ede2234234ba3093149524066488e84415187ce478c582 maven/maven-resolver-provider-3.9.11.jar
e3153906e93333c106ee18babb72ba7984ccb15e9116ea08f88c71b8d9387e01 maven/maven-resolver-spi-1.9.24.jar
b09268d41e1dfcae15a829d45a512ca29d62b727421d3bd6383ac6252e5e960f maven/maven-resolver-transport-file-1.9.24.jar
a0de339a8dd3473d9abaa1cf974507f38783e26af31d36a90c1e59cc8714ded0 maven/maven-resolver-transport-http-1.9.24.jar
78ed57fa2123a2d84fad7a0b15ca73b89df47c10294d02d6f8121c4d0e5050cb maven/maven-resolver-transport-wagon-1.9.24.jar
aeb7e776a8c47b1c317a2581f299e2525b044cb8abde31164e970bbbefab12b1 maven/maven-resolver-util-1.9.24.jar
026718d47d19e360d978857bc63d3dc065884fc2c801563d8a2a77b5ab74ccf8 maven/maven-settings-3.9.11.jar
33c96e4ca5a15b7c93180f6b2f8deb15f511dfc15dda0d2b671c968b22108972 maven/maven-settings-builder-3.9.11.jar
b613357e1bad4dfc1dead801691c9460f9585fe7c6b466bc25186212d7d18487 maven/maven-shared-utils-3.4.2.jar
76d9fa894fa61d1492877ca599cb5ab28ca4573d5f389d6c12a8233b995335f9 maven/maven-slf4j-provider-3.9.11.jar
1cbd7a965a5e2a9ea823bab311962a4e5aa5c240705bdbad5a52b40ffdfa1004 maven/org.eclipse.sisu.inject-0.9.0.M4.jar
b90579bc652eac7331436e0a25533fce14130b9c6e015f2dd3a3d4bb07e942b7 maven/org.eclipse.sisu.plexus-0.9.0.M4.jar
9a7f1b5c5a9effd61eadfd8731452a2f76a8e79111fac391ef75ea801bea203a maven/plexus-cipher-2.0.jar
50edb93c73786e62822b4fe1336e22880fdf147191373cf5c911370e16748fcf maven/plexus-component-annotations-2.2.0.jar
ab2a8715570438a2e4164d85ad3e8d489eabc38ea5093c2eb8ab7f58403535b5 maven/plexus-interpolation-1.28.jar
873139960c4c780176dda580b003a2c4bf82188bdce5bb99234e224ef7acfceb maven/plexus-sec-dispatcher-2.0.jar
27ef130e32c236090e408fb5498d94cb9ea26d14070fb1c8985d607b62d098d1 maven/plexus-utils-3.6.0.jar
d3ef575e3e4979678dc01bf1dcce51021493b4d11fb7f1be8ad982877c16a1c0 maven/slf4j-api-1.7.36.jar
afc9216fa97b78dad227b4a8d4d67b9897bf113a57f80598d62993841113e103 maven/wagon-file-3.5.3.jar
d2b6e48c9fcbe579e1858c622d14464011ff265fa6e28e794004a6882154a509 maven/wagon-http-3.5.3.jar
8e7da766f55164fde8779aaaa125832506c2848cab4876b5305138873e28037f maven/wagon-http-shared-3.5.3.jar
5e72000338945ed3e96f8e4f578d1d0672e1af7e19c0e9014197ae5b31af3ef4 maven/wagon-provider-api-3.5.3.jar
1ad3292cd563381e3fd632f3fded1988f9e9b2be7a9f3db63ff4c4cedba13fa5 maven/plexus-classworlds-2.9.0.jar
+38
View File
@@ -0,0 +1,38 @@
"""Build the committed jar: python3 build.py /path/to/apache-maven-3.9.11 [--record-dependencies].
One jar, two parts, Java 8 bytecode:
- `src`: the resident javac server (`ai.openidea.javac.Server`), JDK classes only.
- `maven`: the prepare run's Maven extension (`ai.openidea.javac.maven.BuildModel`), compiled
against Maven 3.9.11's API jars, pinned by build-dependencies.sha256.
Archive order and timestamps are deterministic. Use a JDK that still compiles `--release 8`."""
import hashlib
import os
import pathlib
import subprocess
import sys
import tempfile
import zipfile
root = pathlib.Path(__file__).resolve().parent
maven = pathlib.Path(sys.argv[1]).resolve()
jars = sorted((maven / 'lib').glob('*.jar')) + sorted((maven / 'boot').glob('*.jar'))
actual = ''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()} maven/{p.name}\n' for p in jars)
if '--record-dependencies' in sys.argv:
(root / 'build-dependencies.sha256').write_text(actual)
if (root / 'build-dependencies.sha256').read_text() != actual:
sys.exit('Build dependencies differ from build-dependencies.sha256')
java_home = os.environ.get('JAVA_HOME')
javac = str(pathlib.Path(java_home) / 'bin' / 'javac') if java_home else 'javac'
with tempfile.TemporaryDirectory() as output:
for source, classpath in [('src', []), ('maven', jars)]:
subprocess.run([javac, '--release', '8', '-Xlint:-options', '-proc:none', '-encoding', 'UTF-8', '-g',
'-classpath', os.pathsep.join(map(str, classpath)), '-d', output,
*map(str, sorted((root / source).rglob('*.java')))], check=True)
files = {p.relative_to(output).as_posix(): p.read_bytes() for p in pathlib.Path(output).rglob('*.class')}
files['META-INF/sisu/javax.inject.Named'] = b'ai.openidea.javac.maven.BuildModel\n'
files['META-INF/MANIFEST.MF'] = b'Manifest-Version: 1.0\nMain-Class: ai.openidea.javac.Server\n\n'
staged = root / 'openidea-java-build.jar.pending'
with zipfile.ZipFile(staged, 'w', zipfile.ZIP_DEFLATED) as jar:
for name, data in sorted(files.items()):
jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
staged.replace(root / 'openidea-java-build.jar')
@@ -0,0 +1,501 @@
package ai.openidea.javac.maven;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutor;
import org.apache.maven.lifecycle.MavenExecutionPlan;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MavenPluginManager;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.DefaultDependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectDependenciesResolver;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.Exclusion;
import org.eclipse.aether.repository.WorkspaceReader;
import org.eclipse.aether.repository.WorkspaceRepository;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResult;
/**
* Records how each project of the session compiles, for the IDE's own Java build. Loaded only
* by the IDE's prepare run ({@code -Dmaven.ext.class.path=<jar> -Dopenidea.build.model=<file>
* process-resources resources:testResources}): generated sources exist and resources are
* processed, and nothing is compiled. Test source generators run after {@code compile} in
* Maven's lifecycle, so they don't run; the source roots build-helper adds are read from its
* configuration, and any other generator is listed so the IDE leaves those tests to Maven.
*
* <p>Per project and source set (main, test): the source roots (including the ones generated
* sources added), the output directory, the compile classpath with reactor projects as their
* output directories (never their jars), the runtime classpath, the compiler plugin's resolved
* configuration (release, encoding, arguments, annotation processor path) and the resources.
* Executions bound to the compile phases that are not javac (Kotlin, AspectJ, bytecode
* enhancers) are listed, so the IDE leaves such projects to Maven.
*/
@Named("openidea-build-model")
@Singleton
public final class BuildModel extends AbstractMavenLifecycleParticipant {
private static final String COMPILER = "org.apache.maven.plugins:maven-compiler-plugin";
/** Test phases before test-compile, which the prepare run doesn't reach. */
private static final Set<String> TEST_GENERATE_PHASES = new HashSet<>(Arrays.asList(
"generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources"));
/** Phases whose executions change what the compile phases produce. */
private static final Set<String> COMPILE_PHASES =
new HashSet<>(Arrays.asList("compile", "process-classes", "test-compile", "process-test-classes"));
/** Executions in those phases that don't change the classes the IDE compiles. */
private static final Set<String> HARMLESS = new HashSet<>(Arrays.asList(
"org.jacoco:jacoco-maven-plugin", "org.apache.maven.plugins:maven-enforcer-plugin",
"org.codehaus.mojo:animal-sniffer-maven-plugin", "org.apache.maven.plugins:maven-checkstyle-plugin",
"com.github.spotbugs:spotbugs-maven-plugin", "org.apache.maven.plugins:maven-pmd-plugin",
"com.diffplug.spotless:spotless-maven-plugin", "org.apache.maven.plugins:maven-dependency-plugin",
"org.apache.maven.plugins:maven-resources-plugin", "org.codehaus.mojo:build-helper-maven-plugin",
"pl.project13.maven:git-commit-id-plugin", "io.github.git-commit-id:git-commit-id-maven-plugin"));
private final LifecycleExecutor lifecycle;
private final MavenPluginManager plugins;
private final BuildPluginManager buildPlugins;
private final ProjectDependenciesResolver dependencies;
private final RepositorySystem repositories;
@Inject
public BuildModel(LifecycleExecutor lifecycle, MavenPluginManager plugins, BuildPluginManager buildPlugins,
ProjectDependenciesResolver dependencies, RepositorySystem repositories) {
this.lifecycle = lifecycle;
this.plugins = plugins;
this.buildPlugins = buildPlugins;
this.dependencies = dependencies;
this.repositories = repositories;
}
/**
* With {@code -Dopenidea.build.output=<dir>}, every project's classes and resources go to
* {@code <dir>/<groupId>.<artifactId>/classes} (and {@code test-classes}): the IDE's outputs,
* apart from what a terminal build or the language server writes to {@code target}.
*/
@Override public void afterProjectsRead(MavenSession session) {
String output = session.getUserProperties().getProperty("openidea.build.output");
if (output == null) return;
for (MavenProject project : session.getProjects()) {
File dir = new File(output, project.getGroupId() + "." + project.getArtifactId());
project.getBuild().setOutputDirectory(new File(dir, "classes").getAbsolutePath());
project.getBuild().setTestOutputDirectory(new File(dir, "test-classes").getAbsolutePath());
}
}
@Override public void afterSessionEnd(MavenSession session) throws MavenExecutionException {
String destination = session.getUserProperties().getProperty("openidea.build.model");
if (destination == null) return;
StringBuilder json = new StringBuilder("{\"version\":1,\"projects\":[");
boolean first = true;
MavenProject current = session.getCurrentProject();
try {
for (MavenProject project : session.getProjects()) {
if (!first) json.append(',');
first = false;
project(json, session, project);
}
} finally {
session.setCurrentProject(current);
}
json.append("]}");
File target = new File(destination);
try {
File parent = target.getAbsoluteFile().getParentFile();
parent.mkdirs();
File temp = File.createTempFile("build-model", ".json", parent);
try (Writer out = new OutputStreamWriter(Files.newOutputStream(temp.toPath()), StandardCharsets.UTF_8)) {
out.write(json.toString());
}
Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
throw new MavenExecutionException("Cannot write the IDE build model: " + e.getMessage(), e);
}
}
private void project(StringBuilder json, MavenSession session, MavenProject project) {
session.setCurrentProject(project);
json.append("{\"dir\":").append(q(project.getBasedir().getAbsolutePath()))
.append(",\"groupId\":").append(q(project.getGroupId()))
.append(",\"artifactId\":").append(q(project.getArtifactId()))
.append(",\"version\":").append(q(project.getVersion()))
.append(",\"packaging\":").append(q(project.getPackaging()));
List<String> problems = new ArrayList<>();
Map<String, Mojo> compilers = new HashMap<>();
List<MojoExecution> configured = new ArrayList<>();
List<String> others = new ArrayList<>();
List<String> testGenerators = new ArrayList<>();
List<String> testRoots = new ArrayList<>(project.getTestCompileSourceRoots());
try {
MavenExecutionPlan plan = lifecycle.calculateExecutionPlan(session, true, "test-compile");
for (MojoExecution execution : plan.getMojoExecutions()) {
String plugin = execution.getGroupId() + ":" + execution.getArtifactId();
String phase = execution.getLifecyclePhase();
if (COMPILER.equals(plugin) && ("compile".equals(execution.getGoal()) || "testCompile".equals(execution.getGoal()))) {
if (compilers.containsKey(execution.getGoal())) {
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
continue;
}
try {
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
compilers.put(execution.getGoal(), mojo);
configured.add(execution);
} catch (Exception e) {
problems.add("Cannot read the " + execution.getGoal() + " configuration: " + e);
}
} else if (phase != null && COMPILE_PHASES.contains(phase) && !HARMLESS.contains(plugin)) {
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
} else if (phase != null && TEST_GENERATE_PHASES.contains(phase)) {
String goal = plugin + ":" + execution.getGoal();
if (goal.equals("org.apache.maven.plugins:maven-resources-plugin:testResources")) continue;
if (goal.equals("org.codehaus.mojo:build-helper-maven-plugin:add-test-source")) {
try {
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
Object sources = get(mojo, "sources");
if (sources instanceof File[])
for (File f : (File[]) sources) testRoots.add(f.getAbsolutePath());
plugins.releaseMojo(mojo, execution);
continue;
} catch (Exception e) {
problems.add("Cannot read build-helper's test sources: " + e);
}
}
testGenerators.add(goal + "@" + execution.getExecutionId());
}
}
} catch (Exception e) {
problems.add("Cannot plan the build: " + e);
}
Set<String> reactor = new HashSet<>();
for (MavenProject p : session.getProjects()) reactor.add(p.getGroupId() + ":" + p.getArtifactId());
RepositorySystemSession repo = reactorSession(session);
List<String> compile = new ArrayList<>();
List<String> runtime = new ArrayList<>();
List<String> test = new ArrayList<>();
try {
DependencyResolutionResult result =
dependencies.resolve(new DefaultDependencyResolutionRequest(project, repo));
classpaths(result.getDependencyGraph(), compile, runtime, test);
for (Exception e : result.getCollectionErrors()) problems.add(e.getMessage());
} catch (Exception e) {
problems.add("Cannot resolve the dependencies: " + rootMessage(e));
org.apache.maven.project.DependencyResolutionException failure = cause(e);
if (failure != null && failure.getResult() != null && failure.getResult().getDependencyGraph() != null)
classpaths(failure.getResult().getDependencyGraph(), compile, runtime, test);
}
json.append(",\"main\":");
sourceSet(json, session, project, compilers.get("compile"), null, compile, runtime, problems);
json.append(",\"test\":");
List<String> testClasspath = new ArrayList<>();
testClasspath.add(project.getBuild().getOutputDirectory());
testClasspath.addAll(test);
sourceSet(json, session, project, compilers.get("testCompile"), testRoots, testClasspath, testClasspath, problems);
json.append(",\"otherCompilers\":").append(strings(others));
json.append(",\"testGenerators\":").append(strings(testGenerators));
json.append(",\"problems\":").append(strings(problems)).append('}');
for (int i = 0; i < configured.size(); i++) {
Mojo mojo = compilers.get(configured.get(i).getGoal());
if (mojo != null) plugins.releaseMojo(mojo, configured.get(i));
}
}
/** `testRoots`: the test source roots, `null` for the main source set. */
private void sourceSet(StringBuilder json, MavenSession session, MavenProject project, Mojo compiler,
List<String> testRoots, List<String> classpath, List<String> runtime, List<String> problems) {
boolean test = testRoots != null;
List<String> roots = test ? testRoots : project.getCompileSourceRoots();
String output = test ? project.getBuild().getTestOutputDirectory() : project.getBuild().getOutputDirectory();
json.append("{\"sourceRoots\":").append(strings(roots))
.append(",\"output\":").append(q(output))
.append(",\"classpath\":").append(strings(classpath))
.append(",\"runtimeClasspath\":").append(strings(runtime))
.append(",\"resources\":");
List<Resource> resources = test ? project.getTestResources() : project.getResources();
json.append('[');
for (int i = 0; i < resources.size(); i++) {
Resource r = resources.get(i);
if (i > 0) json.append(',');
json.append("{\"directory\":").append(q(new File(project.getBasedir(), r.getDirectory()).isAbsolute()
? r.getDirectory() : new File(project.getBasedir(), r.getDirectory()).getAbsolutePath()))
.append(",\"filtering\":").append(r.isFiltering())
.append(",\"targetPath\":").append(q(r.getTargetPath()))
.append(",\"includes\":").append(strings(r.getIncludes()))
.append(",\"excludes\":").append(strings(r.getExcludes())).append('}');
}
json.append(']');
json.append(",\"compiler\":");
if (compiler == null) {
json.append("null}");
return;
}
json.append('{');
String goal = test ? "testCompile" : "compile";
field(json, "compilerId", get(compiler, "compilerId"));
field(json, "source", get(compiler, test ? "testSource" : "source", "source"));
field(json, "target", get(compiler, test ? "testTarget" : "target", "target"));
field(json, "release", get(compiler, test ? "testRelease" : "release", "release"));
field(json, "encoding", get(compiler, "encoding"));
field(json, "parameters", get(compiler, "parameters"));
field(json, "debug", get(compiler, "debug"));
field(json, "debuglevel", get(compiler, "debuglevel"));
field(json, "proc", get(compiler, "proc"));
field(json, "enablePreview", get(compiler, "enablePreview"));
field(json, "fork", get(compiler, "fork"));
field(json, "executable", get(compiler, "executable"));
field(json, "skip", get(compiler, test ? "skip" : "skipMain"));
field(json, "showWarnings", get(compiler, "showWarnings"));
field(json, "showDeprecation", get(compiler, "showDeprecation"));
field(json, "generatedSourcesDirectory",
get(compiler, test ? "generatedTestSourcesDirectory" : "generatedSourcesDirectory"));
field(json, "includes", get(compiler, test ? "testIncludes" : "includes"));
field(json, "excludes", get(compiler, test ? "testExcludes" : "excludes"));
field(json, "annotationProcessors", get(compiler, "annotationProcessors"));
field(json, "compilerArgs", get(compiler, "compilerArgs"));
field(json, "compilerArgument", get(compiler, "compilerArgument"));
field(json, "compilerArguments", get(compiler, "compilerArguments"));
field(json, "multiReleaseOutput", get(compiler, "multiReleaseOutput"));
Object paths = get(compiler, "annotationProcessorPaths");
if (paths instanceof Collection && !((Collection<?>) paths).isEmpty()) {
try {
Object useDepMgmt = get(compiler, "annotationProcessorPathsUseDepMgmt");
field(json, "processorPath", processorPath(session, project, (Collection<?>) paths,
Boolean.TRUE.equals(useDepMgmt)));
} catch (Exception e) {
problems.add("Cannot resolve the annotation processor path of " + goal + ": " + rootMessage(e));
field(json, "processorPathError", rootMessage(e));
}
}
if (json.charAt(json.length() - 1) == ',') json.setLength(json.length() - 1);
json.append("}}");
}
/** The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. */
private static void classpaths(DependencyNode root, List<String> compile, List<String> runtime, List<String> test) {
List<DependencyNode> nodes = new ArrayList<>();
collect(root, nodes, new HashSet<>());
for (DependencyNode node : nodes) {
if (node.getDependency() == null || node.getArtifact() == null) continue;
File file = node.getArtifact().getFile();
if (file == null) continue;
String scope = node.getDependency().getScope();
String path = file.getAbsolutePath();
if (!"test".equals(scope) && !"runtime".equals(scope)) compile.add(path);
if (!"test".equals(scope) && !"provided".equals(scope) && !"system".equals(scope)) runtime.add(path);
test.add(path);
}
}
/** Pre-order, as Maven lists `project.getArtifacts()` for classpaths. */
private static void collect(DependencyNode node, List<DependencyNode> out, Set<String> seen) {
for (DependencyNode child : node.getChildren()) {
Artifact a = child.getArtifact();
String key = a == null ? String.valueOf(System.identityHashCode(child))
: a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getExtension() + ":" + a.getClassifier();
if (seen.add(key)) out.add(child);
}
for (DependencyNode child : node.getChildren()) collect(child, out, seen);
}
/**
* A repository session that resolves reactor projects to their output directories, as the
* IDE compiles against them: before (and without) any packaging, and even before they exist.
*/
private static RepositorySystemSession reactorSession(MavenSession session) {
final Map<String, MavenProject> byKey = new HashMap<>();
for (MavenProject p : session.getProjects())
byKey.put(p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(), p);
final WorkspaceReader fallback = session.getRepositorySession().getWorkspaceReader();
final WorkspaceRepository repository = new WorkspaceRepository("openidea-reactor");
WorkspaceReader reader = new WorkspaceReader() {
@Override public WorkspaceRepository getRepository() {
return repository;
}
@Override public File findArtifact(Artifact artifact) {
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
if (p == null) return fallback == null ? null : fallback.findArtifact(artifact);
if ("pom".equals(artifact.getExtension())) return p.getFile();
boolean tests = "tests".equals(artifact.getClassifier()) || "test-jar".equals(artifact.getProperty("type", ""));
File dir = new File(tests ? p.getBuild().getTestOutputDirectory() : p.getBuild().getOutputDirectory());
dir.mkdirs();
return dir;
}
@Override public List<String> findVersions(Artifact artifact) {
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
if (p != null) return java.util.Collections.singletonList(p.getVersion());
return fallback == null ? java.util.Collections.<String>emptyList() : fallback.findVersions(artifact);
}
};
DefaultRepositorySystemSession copy = new DefaultRepositorySystemSession(session.getRepositorySession());
copy.setWorkspaceReader(reader);
return copy;
}
/** maven-compiler-plugin's `annotationProcessorPaths`, resolved with their dependencies as the plugin does. */
private List<String> processorPath(MavenSession session, MavenProject project, Collection<?> coordinates,
boolean useDepMgmt) throws Exception {
Map<String, String> managed = new HashMap<>();
if (project.getDependencyManagement() != null)
for (Dependency d : project.getDependencyManagement().getDependencies())
managed.put(d.getGroupId() + ":" + d.getArtifactId(), d.getVersion());
CollectRequest request = new CollectRequest();
request.setRepositories(project.getRemoteProjectRepositories());
for (Object c : coordinates) {
String group = (String) get(c, "groupId");
String artifact = (String) get(c, "artifactId");
String version = (String) get(c, "version");
if (version == null) version = managed.get(group + ":" + artifact);
if (version == null) throw new IllegalStateException("No version for " + group + ":" + artifact);
String classifier = (String) get(c, "classifier");
String type = (String) get(c, "type");
List<Exclusion> exclusions = new ArrayList<>();
Object declared = get(c, "exclusions");
if (declared instanceof Collection)
for (Object e : (Collection<?>) declared)
exclusions.add(new Exclusion((String) get(e, "groupId"), (String) get(e, "artifactId"), "*", "*"));
DefaultArtifact a = new DefaultArtifact(group, artifact, classifier == null ? "" : classifier,
type == null || "jar".equals(type) ? "jar" : type, version);
request.addDependency(new org.eclipse.aether.graph.Dependency(a, "runtime", false, exclusions));
}
if (useDepMgmt && project.getDependencyManagement() != null) {
for (Dependency d : project.getDependencyManagement().getDependencies()) {
request.addManagedDependency(new org.eclipse.aether.graph.Dependency(new DefaultArtifact(d.getGroupId(),
d.getArtifactId(), d.getClassifier() == null ? "" : d.getClassifier(),
d.getType() == null ? "jar" : d.getType(), d.getVersion()), d.getScope()));
}
}
DependencyResult result =
repositories.resolveDependencies(reactorSession(session), new DependencyRequest(request, null));
Set<String> out = new LinkedHashSet<>();
for (ArtifactResult r : result.getArtifactResults())
if (r.getArtifact() != null && r.getArtifact().getFile() != null) out.add(r.getArtifact().getFile().getAbsolutePath());
return new ArrayList<>(out);
}
private static org.apache.maven.project.DependencyResolutionException cause(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause())
if (t instanceof org.apache.maven.project.DependencyResolutionException)
return (org.apache.maven.project.DependencyResolutionException) t;
return null;
}
private static String rootMessage(Throwable e) {
Throwable t = e;
while (t.getCause() != null && t.getCause() != t) t = t.getCause();
return t.getMessage() == null ? t.toString() : t.getMessage();
}
/** The first of `names` that a field of the mojo (or its superclasses) has, read reflectively. */
private static Object get(Object target, String... names) {
for (String name : names) {
for (Class<?> c = target.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
try {
Field f = c.getDeclaredField(name);
f.setAccessible(true);
Object value = f.get(target);
if (value != null || names.length == 1) return value;
break;
} catch (NoSuchFieldException e) {
// Try the superclass.
} catch (IllegalAccessException | RuntimeException e) {
return null;
}
}
}
return null;
}
private static void field(StringBuilder json, String name, Object value) {
if (value == null) return;
json.append(q(name)).append(':').append(value(value)).append(',');
}
private static String value(Object value) {
if (value == null) return "null";
if (value instanceof Boolean || value instanceof Number) return value.toString();
if (value instanceof File) return q(((File) value).getAbsolutePath());
if (value instanceof Collection) {
StringBuilder b = new StringBuilder("[");
for (Object o : (Collection<?>) value) {
if (b.length() > 1) b.append(',');
b.append(value(o));
}
return b.append(']').toString();
}
if (value instanceof Object[]) return value(Arrays.asList((Object[]) value));
if (value instanceof Map) {
StringBuilder b = new StringBuilder("{");
for (Map.Entry<?, ?> e : new LinkedHashMap<>((Map<?, ?>) value).entrySet()) {
if (b.length() > 1) b.append(',');
b.append(q(String.valueOf(e.getKey()))).append(':').append(q(e.getValue() == null ? null : String.valueOf(e.getValue())));
}
return b.append('}').toString();
}
return q(value.toString());
}
private static String strings(Collection<String> values) {
StringBuilder b = new StringBuilder("[");
if (values != null) {
for (String s : values) {
if (b.length() > 1) b.append(',');
b.append(q(s));
}
}
return b.append(']').toString();
}
static String q(String s) {
if (s == null) return "null";
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': b.append("\\\""); break;
case '\\': b.append("\\\\"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
return b.append('"').toString();
}
}
Binary file not shown.
@@ -0,0 +1,459 @@
package ai.openidea.javac;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
/**
* A resident javac for the IDE's Java build: one JVM per JDK, compiling requests one at a
* time with the JDK's own compiler, in process, annotation processors included.
*
* <p>Protocol: one JSON object per line. Requests on stdin:
* {@code {"id":1,"op":"compile","options":[...],"sources":[...],"encoding":"UTF-8"}},
* {@code {"op":"cancel","id":1}}, {@code {"op":"exit"}}. Replies on stdout, all carrying the
* request {@code id}: {@code diagnostic} (severity, path, 1-based line, UTF-16 column and end,
* code, message), {@code output} (a class or resource file written, with the source it came
* from), {@code generated} (a source an annotation processor wrote), {@code output-text}
* (javac's own printed text), then one {@code done} (success, cancelled).
*/
public final class Server {
private static final Object OUT_LOCK = new Object();
private static PrintWriter out;
public static void main(String[] args) throws IOException {
out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), false);
// Anything else printing to stdout would break the protocol.
System.setOut(System.err);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("This Java runtime has no compiler (a JRE, not a JDK)") + "}");
System.exit(2);
}
send("{\"kind\":\"ready\",\"version\":" + Json.quote(System.getProperty("java.version")) + "}");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
final AtomicReference<Request> running = new AtomicReference<>();
final java.util.concurrent.BlockingQueue<Request> queue = new java.util.concurrent.LinkedBlockingQueue<>();
Thread worker = new Thread(() -> {
while (true) {
Request request;
try {
request = queue.take();
} catch (InterruptedException e) {
return;
}
if (request.exit) return;
running.set(request);
try {
compile(compiler, request);
} catch (Throwable t) {
StringWriter trace = new StringWriter();
t.printStackTrace(new PrintWriter(trace));
send("{\"id\":" + request.id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
+ Json.quote("javac crashed: " + trace) + "}");
send("{\"id\":" + request.id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":false}");
} finally {
running.set(null);
}
}
}, "javac");
worker.start();
String line;
while ((line = in.readLine()) != null) {
if (line.trim().isEmpty()) continue;
Map<String, Object> message;
try {
message = Json.parseObject(line);
} catch (RuntimeException e) {
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("Bad request: " + e.getMessage()) + "}");
continue;
}
String op = (String) message.get("op");
if ("cancel".equals(op)) {
Request current = running.get();
long id = ((Number) message.get("id")).longValue();
if (current != null && current.id == id) current.cancelled = true;
for (Request queued : queue) if (queued.id == id) queued.cancelled = true;
} else if ("exit".equals(op)) {
break;
} else if ("compile".equals(op)) {
queue.add(Request.of(message));
}
}
Request exit = new Request();
exit.exit = true;
// Requests already sent finish first; the host cancels the ones it no longer wants.
queue.add(exit);
try {
worker.join();
} catch (InterruptedException ignored) {
}
System.exit(0);
}
static void send(String json) {
synchronized (OUT_LOCK) {
out.print(json);
out.print('\n');
out.flush();
}
}
static final class Request {
long id;
List<String> options = new ArrayList<>();
List<String> sources = new ArrayList<>();
String encoding;
volatile boolean cancelled;
boolean exit;
@SuppressWarnings("unchecked")
static Request of(Map<String, Object> message) {
Request r = new Request();
r.id = ((Number) message.get("id")).longValue();
Object options = message.get("options");
if (options != null) for (Object o : (List<Object>) options) r.options.add((String) o);
Object sources = message.get("sources");
if (sources != null) for (Object o : (List<Object>) sources) r.sources.add((String) o);
r.encoding = (String) message.get("encoding");
return r;
}
}
/** Thrown from the task listener to stop a cancelled compilation. */
static final class Cancelled extends RuntimeException {
private static final long serialVersionUID = 1L;
Cancelled() {
super("cancelled", null, false, false);
}
}
private static void compile(JavaCompiler compiler, final Request request) throws IOException {
final long id = request.id;
if (request.cancelled) {
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":true}");
return;
}
Charset charset = request.encoding == null ? StandardCharsets.UTF_8 : Charset.forName(request.encoding);
final int[] errors = {0};
DiagnosticListener<JavaFileObject> diagnostics = d -> {
if (d.getKind() == Diagnostic.Kind.ERROR) errors[0]++;
send(diagnostic(id, d));
};
StandardJavaFileManager standard = compiler.getStandardFileManager(diagnostics, Locale.ROOT, charset);
JavaFileManager manager = new Recording(standard, id);
List<File> files = new ArrayList<>();
for (String source : request.sources) files.add(new File(source));
Iterable<? extends JavaFileObject> units = standard.getJavaFileObjectsFromFiles(files);
StringWriter printed = new StringWriter();
boolean success = false;
boolean cancelled = false;
try {
JavaCompiler.CompilationTask task =
compiler.getTask(printed, manager, diagnostics, request.options, null, units);
stopWhenCancelled(task, request);
success = Boolean.TRUE.equals(task.call()) && errors[0] == 0;
} catch (RuntimeException e) {
if (isCancelled(e)) {
cancelled = true;
} else if (e instanceof IllegalArgumentException) {
// An option javac doesn't know (a newer --release than this JDK has).
send("{\"id\":" + id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
+ Json.quote(e.getMessage()) + "}");
} else {
throw e;
}
} finally {
try {
manager.close();
} catch (IOException ignored) {
}
}
String text = printed.toString();
if (!text.isEmpty()) send("{\"id\":" + id + ",\"kind\":\"output-text\",\"text\":" + Json.quote(text) + "}");
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":" + success + ",\"cancelled\":" + cancelled + "}");
}
/**
* Stops the compilation at its next phase once {@code request} is cancelled, through
* {@code com.sun.source.util.TaskListener} (reflectively: Java 8's {@code --release} API has no
* {@code jdk.compiler}).
*/
private static void stopWhenCancelled(JavaCompiler.CompilationTask task, final Request request) {
try {
Class<?> listener = Class.forName("com.sun.source.util.TaskListener", false, task.getClass().getClassLoader());
Object proxy = java.lang.reflect.Proxy.newProxyInstance(listener.getClassLoader(), new Class<?>[] {listener},
(self, method, args) -> {
if (method.getDeclaringClass() == Object.class) {
switch (method.getName()) {
case "hashCode": return System.identityHashCode(self);
case "equals": return self == args[0];
default: return "cancellation listener";
}
}
if (request.cancelled) throw new Cancelled();
return null;
});
task.getClass().getMethod("addTaskListener", listener).invoke(task, proxy);
} catch (ReflectiveOperationException | RuntimeException e) {
// Not javac's task: cancellation then waits for the compilation to end.
}
}
private static boolean isCancelled(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause()) if (t instanceof Cancelled) return true;
return false;
}
private static String diagnostic(long id, Diagnostic<? extends JavaFileObject> d) {
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":\"diagnostic\",\"severity\":");
String severity;
switch (d.getKind()) {
case ERROR: severity = "error"; break;
case WARNING:
case MANDATORY_WARNING: severity = "warning"; break;
default: severity = "info";
}
json.append(Json.quote(severity));
JavaFileObject source = d.getSource();
if (source != null) {
json.append(",\"path\":").append(Json.quote(path(source.toUri())));
long start = d.getStartPosition();
long end = d.getEndPosition();
int[] startCol = start >= 0 ? lineColumn(source, start) : null;
int[] endCol = end >= 0 ? lineColumn(source, end) : null;
if (startCol != null) json.append(",\"line\":").append(startCol[0]).append(",\"column\":").append(startCol[1]);
else if (d.getLineNumber() > 0) json.append(",\"line\":").append(d.getLineNumber());
if (endCol != null) json.append(",\"endLine\":").append(endCol[0]).append(",\"endColumn\":").append(endCol[1]);
}
if (d.getCode() != null) json.append(",\"code\":").append(Json.quote(d.getCode()));
json.append(",\"message\":").append(Json.quote(d.getMessage(Locale.ROOT)));
return json.append('}').toString();
}
/** 1-based line and 0-based UTF-16 column of a char offset (Java chars are UTF-16 units). */
private static int[] lineColumn(JavaFileObject source, long offset) {
CharSequence text;
try {
text = source.getCharContent(true);
} catch (IOException | RuntimeException e) {
return null;
}
if (offset > text.length()) return null;
int line = 1;
int lineStart = 0;
for (int i = 0; i < offset; i++) {
char c = text.charAt(i);
if (c == '\n' || (c == '\r' && (i + 1 >= text.length() || text.charAt(i + 1) != '\n'))) {
line++;
lineStart = i + 1;
}
}
return new int[] {line, (int) offset - lineStart};
}
static String path(URI uri) {
if ("file".equals(uri.getScheme())) return new File(uri).getPath();
return uri.toString();
}
/** Reports every file the compiler writes and the source it came from. */
static final class Recording extends ForwardingJavaFileManager<JavaFileManager> {
private final long id;
Recording(JavaFileManager manager, long id) {
super(manager);
this.id = id;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind,
FileObject sibling) throws IOException {
JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
report(location, file, sibling, kind == JavaFileObject.Kind.SOURCE);
return file;
}
@Override
public FileObject getFileForOutput(Location location, String packageName, String relativeName,
FileObject sibling) throws IOException {
FileObject file = super.getFileForOutput(location, packageName, relativeName, sibling);
report(location, file, sibling, location == StandardLocation.SOURCE_OUTPUT);
return file;
}
private void report(Location location, FileObject file, FileObject sibling, boolean generatedSource) {
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":")
.append(Json.quote(generatedSource ? "generated" : "output"))
.append(",\"path\":").append(Json.quote(path(file.toUri())));
if (sibling != null && sibling.toUri().getScheme() != null)
json.append(",\"source\":").append(Json.quote(path(sibling.toUri())));
json.append(",\"location\":").append(Json.quote(location.getName()));
send(json.append('}').toString());
}
}
/** Just enough JSON for the protocol: objects, arrays, strings, numbers, booleans, null. */
static final class Json {
private final String text;
private int at;
private Json(String text) {
this.text = text;
}
@SuppressWarnings("unchecked")
static Map<String, Object> parseObject(String text) {
Json json = new Json(text);
Object value = json.value();
json.space();
if (!(value instanceof Map) || json.at != text.length()) throw new IllegalArgumentException("not one JSON object");
return (Map<String, Object>) value;
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': b.append("\\\""); break;
case '\\': b.append("\\\\"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
return b.append('"').toString();
}
private void space() {
while (at < text.length() && Character.isWhitespace(text.charAt(at))) at++;
}
private char peek() {
space();
if (at >= text.length()) throw new IllegalArgumentException("unexpected end");
return text.charAt(at);
}
private void expect(char c) {
if (peek() != c) throw new IllegalArgumentException("expected '" + c + "' at " + at);
at++;
}
private Object value() {
char c = peek();
if (c == '{') {
at++;
Map<String, Object> map = new java.util.LinkedHashMap<>();
if (peek() == '}') {
at++;
return map;
}
while (true) {
String key = string();
expect(':');
map.put(key, value());
if (peek() == ',') {
at++;
continue;
}
expect('}');
return map;
}
}
if (c == '[') {
at++;
List<Object> list = new ArrayList<>();
if (peek() == ']') {
at++;
return list;
}
while (true) {
list.add(value());
if (peek() == ',') {
at++;
continue;
}
expect(']');
return list;
}
}
if (c == '"') return string();
if (text.startsWith("true", at)) {
at += 4;
return Boolean.TRUE;
}
if (text.startsWith("false", at)) {
at += 5;
return Boolean.FALSE;
}
if (text.startsWith("null", at)) {
at += 4;
return null;
}
int start = at;
while (at < text.length() && "+-0123456789.eE".indexOf(text.charAt(at)) >= 0) at++;
if (start == at) throw new IllegalArgumentException("unexpected '" + c + "' at " + at);
String number = text.substring(start, at);
return number.contains(".") || number.contains("e") || number.contains("E")
? (Object) Double.parseDouble(number) : (Object) Long.parseLong(number);
}
private String string() {
expect('"');
StringBuilder b = new StringBuilder();
while (true) {
if (at >= text.length()) throw new IllegalArgumentException("unterminated string");
char c = text.charAt(at++);
if (c == '"') return b.toString();
if (c != '\\') {
b.append(c);
continue;
}
char e = text.charAt(at++);
switch (e) {
case 'n': b.append('\n'); break;
case 'r': b.append('\r'); break;
case 't': b.append('\t'); break;
case 'b': b.append('\b'); break;
case 'f': b.append('\f'); break;
case 'u':
b.append((char) Integer.parseInt(text.substring(at, at + 4), 16));
at += 4;
break;
default: b.append(e);
}
}
}
}
private Server() {
}
}
+16 -2
View File
@@ -1,4 +1,4 @@
//! The OS clipboard's file list, so the project view and Explorer exchange files.
//! The OS clipboard's file list, so the project view and the file manager exchange files.
use ide_command::desktop_command;
#[cfg(any(target_os = "macos", target_os = "linux"))]
@@ -83,7 +83,21 @@ pub async fn clipboard_text(app: AppHandle) -> IdeResult<Option<String>> {
#[tauri::command]
#[specta::specta]
pub async fn clipboard_file_list(app: AppHandle) -> IdeResult<Vec<String>> {
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
#[cfg(target_os = "linux")]
{
let (tx, rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread(move || {
ide_clipboard::request_files(move |paths| {
let _ = tx.send(paths);
})
})
.map_err(|error| IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}")))?;
Ok(rx.await.unwrap_or_default().iter().map(|p| slash(p)).collect())
}
#[cfg(not(target_os = "linux"))]
{
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
}
}
/// Whether the clipboard holds files: cheap, for the Paste item's enabled state.
+43 -4
View File
@@ -334,6 +334,10 @@ pub struct CloseContext {
pub quitting: bool,
/// Number of open project windows (settings windows excluded), including the caller.
pub windows: u32,
/// Whether this window currently has auxiliary document windows that must settle first.
pub has_document_windows: bool,
/// Whether this close runs alongside other windows or on a background tab (prompts serialize and raise).
pub batch: bool,
}
#[desktop_command(trust = always)]
@@ -350,10 +354,40 @@ pub fn window_close_context(app: AppHandle, window: Window, windows: State<'_, W
Some(keeper) if pending.len() > 1 && keeper == window.label() => all.len() - pending.len() + 1,
_ => all.len(),
};
CloseContext { quitting: windows.quitting(), windows: count as u32 }
let quitting = windows.quitting();
let has_document_windows = !windows::document_windows(&app, window.label()).is_empty();
let hidden_tab = windows.groups.lock().group(window.label()).is_some_and(|g| g.selected != window.label());
let batch = quitting || pending.len() > 1 || windows.in_tab_close_batch(window.label()) || hidden_tab;
CloseContext { quitting, windows: count as u32, has_document_windows, batch }
}
/// Quits: closes every window, each of which runs its own unsaved-changes check.
/// Acquires the interactive prompt turn for a batch close and brings this window forward.
/// Returns `false` if the batch was cancelled while waiting.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_begin_prompt(app: AppHandle, window: WebviewWindow) -> bool {
crate::window_groups::begin_prompt(&app, &window).await
}
/// Releases the interactive prompt turn held by this window.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_end_prompt(app: AppHandle, window: Window) {
crate::window_groups::end_prompt(&app, window.label());
}
/// Signals that this window passed its close checks and waits for peers closing in the same
/// batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_ready_to_close(app: AppHandle, window: WebviewWindow) -> bool {
crate::window_groups::ready_to_close(&app, &window).await
}
/// Quits: closes every window in parallel, each of which runs its own unsaved-changes check.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
@@ -362,15 +396,17 @@ pub fn app_quit(app: AppHandle, windows: State<'_, WindowsState>) {
return;
}
windows.set_quitting(true);
windows::continue_quit(&app, None);
windows::start_quit(&app);
}
/// A window vetoed the quit (user cancelled its unsaved-changes prompt).
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) {
pub fn app_cancel_quit(app: AppHandle, window: Window, windows: State<'_, WindowsState>) {
windows.set_quitting(false);
windows.abort_all_closing(Some(window.label()));
windows.close_settled(window.label());
tauri::async_runtime::spawn(async move {
let _ = crate::window_groups::persist(&app).await;
});
@@ -926,9 +962,11 @@ ide_command::desktop_domain!(
menu_model,
menu_refresh,
menu_set_disabled,
window_begin_prompt,
window_close_context,
window_complete_launch,
window_cycle,
window_end_prompt,
window_flash_taskbar,
window_is_fullscreen,
window_new,
@@ -942,6 +980,7 @@ ide_command::desktop_domain!(
window_open_projects,
window_open_remote,
window_open_settings,
window_ready_to_close,
window_set_smooth_scrolling,
window_set_titlebar_height,
window_take_launch,
-1
View File
@@ -49,7 +49,6 @@ pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeRes
#[tauri::command]
#[specta::specta]
pub fn window_group_close(window: WebviewWindow, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
window
.app_handle()
.get_webview_window(&label)
+6
View File
@@ -275,6 +275,12 @@ pub fn run() {
})
.on_window_event(|window, event| match event {
tauri::WindowEvent::CloseRequested { .. } => {
// A dead web engine never answers the page's close handler: close the window here.
#[cfg(windows)]
if windows_webview_recovery::browser_failed(window.app_handle()) {
let _ = window.destroy();
return;
}
#[cfg(target_os = "linux")]
linux_window_state::save_before_close(window.app_handle());
if let Some(w) = window.try_state::<WindowsState>() {
+24
View File
@@ -13,6 +13,10 @@
//! inside the window, so with several monitors its candidate window opens on the wrong
//! one. Through the compositor (Mutter hands text-input to Fcitx's IBus frontend) it
//! follows the caret, so GNOME Wayland sessions drop `GTK_IM_MODULE=fcitx`.
//!
//! WSLg's Wayland compositor has no usable GPU path for WebKitGTK (Mesa reports an
//! incompatible driver and the window stays blank); its X server works, so WSL uses X11
//! unless `GDK_BACKEND` is set.
const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
const DISABLE_EXPLICIT_SYNC: &str = "__NV_DISABLE_EXPLICIT_SYNC";
@@ -21,6 +25,10 @@ const IM_MODULE: &str = "GTK_IM_MODULE";
/// Run before other threads start (`set_var`).
#[cfg(target_os = "linux")]
pub fn configure() {
if use_x11_on_wsl(|k| std::env::var(k).ok()) {
tracing::info!("WSLg: GDK_BACKEND=x11");
unsafe { std::env::set_var("GDK_BACKEND", "x11") };
}
let nvidia = ["/proc/driver/nvidia/version", "/sys/module/nvidia"].iter().any(|p| std::path::Path::new(p).exists());
if disable_explicit_sync(|k| std::env::var(k).ok(), nvidia) {
tracing::info!("Wayland with the NVIDIA driver: {DISABLE_EXPLICIT_SYNC}=1");
@@ -43,6 +51,12 @@ fn drop_fcitx_module(var: impl Fn(&str) -> Option<String>) -> bool {
gnome && var(IM_MODULE).is_some_and(|m| matches!(m.trim(), "fcitx" | "fcitx5")) && gdk_wayland(&var)
}
/// Under WSL with WSLg's X server available, unless the user chose a GDK backend.
fn use_x11_on_wsl(var: impl Fn(&str) -> Option<String>) -> bool {
let set = |k: &str| var(k).is_some_and(|v| !v.is_empty());
(set("WSL_DISTRO_NAME") || set("WSL_INTEROP")) && set("DISPLAY") && !set("GDK_BACKEND")
}
/// GTK 3's IBus input method module (`ibus-gtk3`), wherever the distribution keeps it.
#[cfg(target_os = "linux")]
fn gtk_ibus_module_installed() -> bool {
@@ -163,6 +177,16 @@ mod tests {
assert!(!drop_fcitx_module(env(&[gnome[0], gnome[1], (IM_MODULE, "ibus")])));
}
#[test]
fn wsl_uses_x11_unless_a_backend_is_chosen() {
let wslg = [("WSL_DISTRO_NAME", "Ubuntu-24.04"), ("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
assert!(use_x11_on_wsl(env(&wslg)));
assert!(use_x11_on_wsl(env(&[("WSL_INTEROP", "/run/WSL/1_interop"), ("DISPLAY", ":0")])));
assert!(!use_x11_on_wsl(env(&[wslg[0], wslg[1], wslg[2], ("GDK_BACKEND", "wayland")])));
assert!(!use_x11_on_wsl(env(&[wslg[0], wslg[1]])), "no X server");
assert!(!use_x11_on_wsl(env(&[wslg[1], wslg[2]])), "not WSL");
}
#[test]
fn keeps_the_users_input_method_module() {
let vars = [("WAYLAND_DISPLAY", "wayland-0"), ("XMODIFIERS", "@im=ibus"), (IM_MODULE, "wayland")];
+20
View File
@@ -126,6 +126,26 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
})
}
/// Hides `windows` together in a single main-thread turn so a closing window or tab group
/// disappears at once instead of flipping through remaining tabs while webviews tear down.
/// Native fullscreen windows are left for AppKit's own Space close transition.
pub fn hide_windows(windows: Vec<WebviewWindow>) {
if windows.is_empty() {
return;
}
let first = windows[0].clone();
let _ = on_main(&first, move || {
for window in &windows {
if window.is_fullscreen().unwrap_or(false) {
continue;
}
if let Some(native) = native(window) {
native.orderOut(None);
}
}
});
}
fn has_tab_bar(view: &objc2_app_kit::NSView) -> bool {
let class = view.class().name().to_string_lossy();
class.contains("TabBar") || view.subviews().iter().any(|v| has_tab_bar(&v))
+4
View File
@@ -76,6 +76,10 @@ impl AppState {
// Caches: the previous tree moves first, so a pending invalidation still
// wipes what was just moved.
let identifier = app.config().identifier.clone();
// Windows: the WebView2 profile follows the local data directory too, and must be in
// place before the first window opens (the scheduled move below runs before them too).
#[cfg(windows)]
ide_host::data_dirs::adopt_webview_profile(&identifier, &local_data_dir);
ide_host::data_dirs::apply_custom_migration(&identifier, &local_data_dir);
// File › Invalidate Caches… requested at the last run.
let removed = ide_workspace::caches::apply_pending(&data_dir, &local_data_dir);
+254 -50
View File
@@ -6,7 +6,7 @@ use crate::{
use ide_core::{IdeError, IdeEvent, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::VecDeque;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use tauri::{AppHandle, Manager, WebviewWindow};
@@ -169,35 +169,59 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
pub fn destroyed(app: &AppHandle, caller: &str) {
let Some(state) = app.try_state::<WindowsState>() else { return };
let next = state.groups.lock().detach(caller);
let batch_done_keep = {
let mut batch = state.tab_closes.lock();
if let Some(b) = batch.as_mut()
&& b.pending.remove(caller)
&& b.pending.is_empty()
{
Some(batch.take().unwrap().keep)
} else {
None
}
};
let next_closing = next.as_deref().is_some_and(|label| state.is_closing(label));
let more_closing = state.has_other_pending_closes(caller);
if !state.quitting() {
if let Some(window) = next.and_then(|label| app.get_webview_window(&label)) {
if let Some(keep) = batch_done_keep {
if let Some(window) = app.get_webview_window(&keep)
&& !window.is_focused().unwrap_or(false)
{
windows::focus(&window);
}
} else if !next_closing && let Some(window) = next.as_deref().and_then(|label| app.get_webview_window(label)) {
windows::focus(&window);
}
let app = app.clone();
tauri::async_runtime::spawn(async move {
let _ = persist(&app).await;
});
}
changed(app);
let advance = state.tab_closes.lock().as_mut().is_some_and(|batch| {
let closing = batch.pending.front().is_some_and(|l| l == caller);
if closing {
batch.pending.pop_front();
if !more_closing {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let _ = persist(&app).await;
});
}
closing
});
if advance {
close_next(app);
}
if !next_closing || !more_closing {
changed(app);
}
}
/// Tabs left to close; the first one is closing now.
/// Tabs closing together in a batch (Close Other / Left / Right Tabs), keeping `keep`.
pub struct TabCloses {
keep: String,
pending: VecDeque<String>,
pub(crate) keep: String,
pub(crate) pending: HashSet<String>,
}
/// Closes `labels` one at a time so each project's unsaved-changes prompt is shown in turn, then selects `keep`.
impl TabCloses {
pub(crate) fn contains(&self, label: &str) -> bool {
self.pending.contains(label)
}
pub(crate) fn has_other(&self, exclude: &str) -> bool {
self.pending.iter().any(|l| l != exclude)
}
}
/// Closes `labels` in parallel without flipping tabs; any tab that needs a confirmation prompt
/// acquires the prompt turn and raises itself, and `keep` stays selected when the batch finishes.
pub fn close_tabs(app: &AppHandle, caller: &str, keep: &str, labels: Vec<String>) -> IdeResult<()> {
let state = app.state::<WindowsState>();
let members = state
@@ -209,55 +233,235 @@ pub fn close_tabs(app: &AppHandle, caller: &str, keep: &str, labels: Vec<String>
if !members.iter().any(|m| m == keep) {
return Err(IdeError::invalid("The window is not in this group"));
}
let pending = members.into_iter().filter(|m| m != keep && labels.contains(m)).collect();
let targets: Vec<String> = members.into_iter().filter(|m| m != keep && labels.contains(m)).collect();
if targets.is_empty() {
return Ok(());
}
let pending: HashSet<String> = targets.iter().cloned().collect();
*state.tab_closes.lock() = Some(TabCloses { keep: keep.to_owned(), pending });
close_next(app);
// Pre-register every target before invoking `close()` so early responders see the full cohort.
for label in &targets {
state.close_requested(label);
}
let mut any_sent = false;
for label in targets {
if let Some(window) = app.get_webview_window(&label)
&& window.close().is_ok()
{
any_sent = true;
continue;
}
if let Some(b) = state.tab_closes.lock().as_mut() {
b.pending.remove(&label);
}
state.close_settled(&label);
}
if !any_sent {
*state.tab_closes.lock() = None;
if let Some(window) = app.get_webview_window(keep) {
windows::focus(&window);
}
}
Ok(())
}
/// The closing tab's project vetoed (its unsaved-changes prompt was cancelled): leave the rest open.
/// The closing tab stayed open (either its prompt was cancelled or it returned to Welcome).
pub fn cancel_close(app: &AppHandle, caller: &str) {
let state = app.state::<WindowsState>();
let cancelled_batch = {
let mut batch = state.tab_closes.lock();
if batch.as_ref().is_some_and(|b| b.pending.contains(caller)) { batch.take() } else { None }
};
if let Some(batch) = cancelled_batch {
// A vetoed Close Other/Left/Right Tabs leaves the remaining tabs open too.
state.abort_batch(batch.pending.into_iter().filter(|l| l != caller));
state.close_settled(caller);
return;
}
state.close_settled(caller);
let mut batch = state.tab_closes.lock();
if batch.as_ref().is_some_and(|b| b.pending.front().is_some_and(|l| l == caller)) {
*batch = None;
// For a red-button group close where this tab stayed open (e.g. returned to Welcome),
// select it so closing siblings disappear behind it without flashing.
if state.groups.lock().group(caller).is_some()
&& let Some(window) = app.get_webview_window(caller)
{
windows::focus(&window);
}
if !state.has_other_pending_closes(caller) && !state.quitting() {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let _ = persist(&app).await;
});
}
}
fn close_next(app: &AppHandle) {
/// Waits for the caller's interactive prompt turn in a parallel batch close and brings it forward.
/// Returns `false` if the batch was cancelled while waiting (the caller should stay open quietly).
pub async fn begin_prompt(app: &AppHandle, window: &WebviewWindow) -> bool {
let label = window.label();
let state = app.state::<WindowsState>();
loop {
let next = {
let mut batch = state.tab_closes.lock();
let Some(b) = batch.as_mut() else { return };
match b.pending.front() {
Some(label) => Ok(label.clone()),
None => Err(batch.take().unwrap().keep),
let notified = state.close_notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
match state.try_acquire_prompt(label) {
Ok(true) => {
windows::focus(window);
return true;
}
};
match next {
Ok(label) => {
if let Some(window) = app.get_webview_window(&label) {
windows::focus(&window);
if window.close().is_ok() {
return;
}
}
if let Some(b) = state.tab_closes.lock().as_mut() {
b.pending.pop_front();
}
Ok(false) => {
notified.await;
}
Err(keep) => {
if let Some(window) = app.get_webview_window(&keep) {
windows::focus(&window);
}
return;
Err(()) => {
state.take_aborted(label);
return false;
}
}
}
}
pub fn end_prompt(app: &AppHandle, caller: &str) {
app.state::<WindowsState>().release_prompt(caller);
}
/// Coordinates the final hide/destroy step across windows closing together.
/// Returns `false` if the batch was cancelled while waiting (the caller must stay open).
pub async fn ready_to_close(app: &AppHandle, window: &WebviewWindow) -> bool {
let label = window.label();
let state = app.state::<WindowsState>();
if !state.mark_ready(label) {
return false;
}
const BARRIER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
const POLL_STEP: std::time::Duration = std::time::Duration::from_millis(250);
let mut waited_idle = std::time::Duration::ZERO;
let mut last_tick = std::time::Instant::now();
loop {
let notified = state.close_notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if state.take_aborted(label) {
return false;
}
let (cohort, keep_label) = close_cohort(app, &state, label);
let any_undecided =
cohort.iter().any(|peer| peer != label && app.get_webview_window(peer).is_some() && !state.is_ready(peer));
if !any_undecided {
finish_cohort_visuals(app, &state, label, &cohort, keep_label.as_deref());
state.close_notify.notify_waiters();
return true;
}
match tokio::time::timeout(POLL_STEP, notified).await {
Ok(()) => {
waited_idle = std::time::Duration::ZERO;
last_tick = std::time::Instant::now();
}
Err(_) => {
// Never time out while another tab is waiting on the user's answer to a dialog.
if state.has_prompt_holder() {
waited_idle = std::time::Duration::ZERO;
} else {
waited_idle += last_tick.elapsed();
if waited_idle >= BARRIER_TIMEOUT {
let single = vec![label.to_owned()];
if !state.claim_hide(&single).is_empty() && state.groups.lock().group(label).is_none() {
windows::hide_windows(vec![window.clone()]);
}
return true;
}
}
last_tick = std::time::Instant::now();
}
}
}
}
fn close_cohort(app: &AppHandle, state: &WindowsState, label: &str) -> (Vec<String>, Option<String>) {
if state.quitting() {
let pending = state.pending_closes();
let mut cohort: Vec<String> = windows::project_window_labels(app)
.into_iter()
.filter(|l| l == label || pending.iter().any(|p| p == l))
.collect();
if !cohort.iter().any(|l| l == label) {
cohort.push(label.to_owned());
}
return (cohort, None);
}
if let Some((keep, pending)) = state
.tab_closes
.lock()
.as_ref()
.filter(|b| b.pending.contains(label))
.map(|b| (b.keep.clone(), b.pending.iter().cloned().collect::<Vec<_>>()))
{
return (pending, Some(keep));
}
let pending = state.pending_closes();
let group_members = state.groups.lock().group(label).map(|g| g.members.clone());
if let Some(members) = group_members {
let mut cohort: Vec<String> =
members.into_iter().filter(|m| m == label || pending.iter().any(|p| p == m)).collect();
if !cohort.iter().any(|l| l == label) {
cohort.push(label.to_owned());
}
return (cohort, None);
}
(vec![label.to_owned()], None)
}
/// Applies the visual transition once every peer in `cohort` is ready to close:
/// - Whole closing window or whole closing tab group (or quit): hide all of them in a single frame.
/// - Partial tab group close (Close Other Tabs, single tab close, or keeper returning to Welcome):
/// ensure a surviving tab is selected so the closing tabs tear down invisibly behind it.
fn finish_cohort_visuals(
app: &AppHandle,
state: &WindowsState,
label: &str,
cohort: &[String],
keep_label: Option<&str>,
) {
if state.quitting() {
let to_hide = state.claim_hide(cohort);
let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.get_webview_window(&l)).collect();
windows::hide_windows(windows);
return;
}
let group_snapshot = state.groups.lock().group(label).cloned();
if let Some(group) = group_snapshot {
let cohort_set: HashSet<&str> = cohort.iter().map(String::as_str).collect();
let all_closing = group.members.iter().all(|m| cohort_set.contains(m.as_str()));
if all_closing {
let to_hide = state.claim_hide(&group.members);
let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.get_webview_window(&l)).collect();
windows::hide_windows(windows);
} else {
let survivor = keep_label
.filter(|k| !cohort_set.contains(*k))
.map(str::to_owned)
.or_else(|| group.members.iter().find(|m| !cohort_set.contains(m.as_str())).cloned());
// Only switch tabs if the currently visible tab is one of the closing ones.
if cohort_set.contains(group.selected.as_str())
&& let Some(survivor) = survivor
&& !state.claim_hide(cohort).is_empty()
&& let Some(window) = app.get_webview_window(&survivor)
{
windows::focus(&window);
}
}
} else {
let to_hide = state.claim_hide(cohort);
let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.get_webview_window(&l)).collect();
windows::hide_windows(windows);
}
}
/// Window labels in creation order: `main`, then `project-1`, `project-2`, ….
fn labels_in_order(app: &AppHandle) -> Vec<String> {
let mut labels: Vec<String> = app.webview_windows().into_keys().collect();
+319 -25
View File
@@ -24,8 +24,9 @@ use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tauri::utils::config::{Color, WindowConfig};
use tauri::{AppHandle, Emitter, Manager, Theme, WebviewWindow, WebviewWindowBuilder};
@@ -320,15 +321,16 @@ pub struct WindowsState {
cli: Mutex<cli::Queue>,
/// Most recently focused window label (menu events go there).
last_focused: Mutex<Option<String>>,
/// Set by Quit while windows close one by one.
/// Set by Quit while windows close in parallel.
quitting: AtomicBool,
/// The last closed project opted out of Welcome; macOS keeps its app in the Dock.
#[cfg(target_os = "macos")]
pub keep_alive: AtomicBool,
/// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at
/// once, so its members ask together.
close_requests: Mutex<Vec<String>>,
/// Project tabs closing one by one (Close Other Tabs and friends).
/// Coordinates parallel window/tab-group closes so clean tabs hide together in one frame
/// and interactive prompts still run one at a time.
close: Mutex<CloseState>,
pub close_notify: Arc<tokio::sync::Notify>,
/// Project tabs closing in parallel (Close Other Tabs and friends).
pub tab_closes: Mutex<Option<crate::window_groups::TabCloses>>,
/// Relaunch once the quit completes (after installing an update).
restart: AtomicBool,
@@ -355,20 +357,180 @@ pub(crate) struct AuxGeometry {
pub maximized: bool,
}
#[derive(Default)]
struct CloseState {
/// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at
/// once, so its members ask together; Quit and Close Other Tabs also close members in parallel.
pending: Vec<String>,
/// Members that passed their close guard and are waiting at the batch barrier before destroying.
ready: HashSet<String>,
/// Members whose batch was cancelled while they waited; they stay open.
aborted: HashSet<String>,
/// Windows already hidden as part of their closing cohort so hiding only runs once per batch.
hidden: HashSet<String>,
/// Window currently showing an interactive close dialog (at most one across a batch).
prompt_holder: Option<String>,
}
impl WindowsState {
pub fn close_requested(&self, label: &str) {
let mut requests = self.close_requests.lock();
if !requests.iter().any(|l| l == label) {
requests.push(label.to_owned());
let mut close = self.close.lock();
close.aborted.remove(label);
close.ready.remove(label);
close.hidden.remove(label);
if !close.pending.iter().any(|l| l == label) {
close.pending.push(label.to_owned());
}
}
pub fn close_settled(&self, label: &str) {
self.close_requests.lock().retain(|l| l != label);
{
let mut close = self.close.lock();
close.pending.retain(|l| l != label);
close.ready.remove(label);
close.aborted.remove(label);
close.hidden.remove(label);
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
}
}
self.close_notify.notify_waiters();
}
pub fn pending_closes(&self) -> Vec<String> {
self.close_requests.lock().clone()
self.close.lock().pending.clone()
}
pub fn is_closing(&self, label: &str) -> bool {
let in_close = {
let close = self.close.lock();
close.pending.iter().any(|l| l == label) || close.ready.contains(label)
};
in_close || self.in_tab_close_batch(label)
}
pub fn has_other_pending_closes(&self, exclude: &str) -> bool {
let other_pending = self.close.lock().pending.iter().any(|l| l != exclude);
other_pending || self.tab_closes.lock().as_ref().is_some_and(|b| b.has_other(exclude))
}
pub fn in_tab_close_batch(&self, label: &str) -> bool {
self.tab_closes.lock().as_ref().is_some_and(|b| b.contains(label))
}
/// Marks `label` ready to destroy. Returns `false` if its batch was already cancelled.
pub fn mark_ready(&self, label: &str) -> bool {
let ok = {
let mut close = self.close.lock();
if close.aborted.remove(label) {
close.pending.retain(|l| l != label);
close.ready.remove(label);
close.hidden.remove(label);
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
}
false
} else {
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
}
close.ready.insert(label.to_owned());
true
}
};
self.close_notify.notify_waiters();
ok
}
pub fn is_ready(&self, label: &str) -> bool {
self.close.lock().ready.contains(label)
}
pub fn take_aborted(&self, label: &str) -> bool {
let mut close = self.close.lock();
if close.aborted.remove(label) {
close.pending.retain(|l| l != label);
close.ready.remove(label);
close.hidden.remove(label);
true
} else {
false
}
}
/// Marks `labels` as hidden once and returns those newly claimed for hiding.
pub fn claim_hide(&self, labels: &[String]) -> Vec<String> {
let mut close = self.close.lock();
labels.iter().filter(|l| close.hidden.insert((*l).clone())).cloned().collect()
}
/// Marks `labels` as aborted so peers waiting at the close barrier or prompt turn stay open.
pub fn abort_batch(&self, labels: impl IntoIterator<Item = String>) {
{
let mut close = self.close.lock();
for label in labels {
close.ready.remove(&label);
close.hidden.remove(&label);
close.pending.retain(|l| l != &label);
close.aborted.insert(label);
}
close.prompt_holder = None;
}
self.close_notify.notify_waiters();
}
/// Aborts every in-flight close except `initiator` (used when cancelling Quit).
pub fn abort_all_closing(&self, initiator: Option<&str>) {
{
let mut close = self.close.lock();
let mut targets: Vec<String> = std::mem::take(&mut close.pending);
for label in close.ready.drain() {
if !targets.iter().any(|l| l == &label) {
targets.push(label);
}
}
close.hidden.clear();
close.prompt_holder = None;
for label in targets {
if initiator != Some(label.as_str()) {
close.aborted.insert(label);
}
}
}
self.close_notify.notify_waiters();
}
/// Tries to acquire the interactive prompt turn. `Err(())` means this close was aborted.
pub fn try_acquire_prompt(&self, label: &str) -> Result<bool, ()> {
let mut close = self.close.lock();
if close.aborted.contains(label) {
return Err(());
}
if close.prompt_holder.is_none() || close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = Some(label.to_owned());
Ok(true)
} else {
Ok(false)
}
}
pub fn release_prompt(&self, label: &str) {
let released = {
let mut close = self.close.lock();
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
true
} else {
false
}
};
if released {
self.close_notify.notify_waiters();
}
}
pub fn has_prompt_holder(&self) -> bool {
self.close.lock().prompt_holder.is_some()
}
pub fn set_launch(&self, label: &str, launch: Launch) {
@@ -747,22 +909,68 @@ pub fn focus(window: &WebviewWindow) {
let _ = window.set_focus();
}
/// Present one project's save prompt at a time, including hidden group members.
pub fn continue_quit(app: &AppHandle, closed: Option<&str>) {
if !app.state::<WindowsState>().quitting() {
pub fn hide_windows(windows: Vec<WebviewWindow>) {
#[cfg(target_os = "macos")]
crate::macos::hide_windows(windows);
#[cfg(not(target_os = "macos"))]
for window in windows {
let _ = window.hide();
}
}
/// Closes every project window in parallel without flipping focus across clean tabs.
/// Windows that need user confirmation acquire the prompt turn one at a time via `begin_prompt`.
pub fn start_quit(app: &AppHandle) {
let state = app.state::<WindowsState>();
let labels = project_window_labels(app);
if labels.is_empty() {
app.exit(0);
return;
}
let next = project_window_labels(app)
.into_iter()
.filter(|label| Some(label.as_str()) != closed)
.find_map(|label| app.get_webview_window(&label));
if let Some(window) = next {
focus(&window);
if window.close().is_err() {
app.state::<WindowsState>().set_quitting(false);
for label in &labels {
state.close_requested(label);
}
let mut any_sent = false;
for label in labels {
if let Some(window) = app.get_webview_window(&label)
&& window.close().is_ok()
{
any_sent = true;
continue;
}
} else {
state.close_settled(&label);
}
if !any_sent {
if project_window_labels(app).is_empty() {
app.exit(0);
} else {
state.set_quitting(false);
}
}
}
/// Exits once every project window has finished closing during Quit.
pub fn continue_quit(app: &AppHandle, closed: Option<&str>) {
let state = app.state::<WindowsState>();
if !state.quitting() {
return;
}
let remaining: Vec<String> =
project_window_labels(app).into_iter().filter(|label| Some(label.as_str()) != closed).collect();
if remaining.is_empty() {
app.exit(0);
return;
}
// Close any window that appeared after Quit began and was not yet asked to close.
for label in remaining {
if !state.is_closing(&label)
&& let Some(window) = app.get_webview_window(&label)
{
state.close_requested(&label);
if window.close().is_err() {
state.close_settled(&label);
}
}
}
}
@@ -850,8 +1058,18 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
}
#[cfg(target_os = "linux")]
let show_after_build = crate::linux_window_state::prepare(app, &mut config);
// Windows opens a project window at the configured size (window-state restores only the
// maximized flag there), which Restore Down returns to.
#[cfg(windows)]
if let Ok(Some(monitor)) = app.primary_monitor() {
let area = monitor.work_area().size.to_logical::<f64>(monitor.scale_factor());
let min = (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0));
let (size, min) = fit_new_window((config.width, config.height), min, (area.width, area.height));
(config.width, config.height) = size;
(config.min_width, config.min_height) = (Some(min.0), Some(min.1));
}
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| dev_font_preferences(b).on_new_window(open_popup_in_browser).build())
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
#[cfg(target_os = "linux")]
decorate_csd(&window);
@@ -1689,7 +1907,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
// display's Space, so macOS keeps it too.
#[cfg(target_os = "linux")]
let builder = builder.and_then(|b| b.parent(&parent));
let window = builder.and_then(|b| dev_font_preferences(b).build()).map_err(|e| {
let window = builder.and_then(|b| dev_font_preferences(webview_profile(app, b)).build()).map_err(|e| {
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
@@ -2104,6 +2322,18 @@ fn fit_over_parent(
rx.recv_timeout(FIT_ON_MAIN_TIMEOUT).map_err(|_| tauri::Error::FailedToReceiveMessage)
}
/// A new window's size and minimum size (logical pixels) shrunk to fit `area`, the work area of
/// the monitor it opens on: the default 1440×900 is taller than a 1920×1080 laptop screen at
/// 150 % scaling once the taskbar is taken off.
#[cfg_attr(not(windows), allow(dead_code))]
fn fit_new_window(size: (f64, f64), min: (f64, f64), area: (f64, f64)) -> ((f64, f64), (f64, f64)) {
if area.0 <= 0.0 || area.1 <= 0.0 {
return (size, min);
}
let size = (size.0.min(area.0), size.1.min(area.1));
(size, (min.0.min(size.0), min.1.min(size.1)))
}
/// Centres the settings window over its owner, inside the owner's monitor work area. The window
/// may still be on another display with a different scale, so its size is converted with its own
/// scale and its position is given in physical pixels.
@@ -2196,6 +2426,23 @@ fn open_popup_in_browser<R: tauri::Runtime>(
tauri::webview::NewWindowResponse::Deny
}
/// On Windows every window keeps WebView2's profile (localStorage, IndexedDB) in the local
/// data directory, so a custom location from Settings › System Settings › Caches holds it too;
/// Tauri would always use the default one. All windows share it: one WebView2 browser process
/// serves a single profile folder.
fn webview_profile<'a>(
app: &AppHandle,
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
#[cfg(windows)]
if let Some(state) = app.try_state::<AppState>() {
return builder.data_directory(state.host.local_data_dir.clone());
}
#[cfg(not(windows))]
let _ = app;
builder
}
/// Reproduce WKWebView's user-font restriction before WKWebView creation. The
/// private selector and environment override are absent from release builds.
#[cfg(all(debug_assertions, target_os = "macos"))]
@@ -2926,6 +3173,19 @@ mod tests {
}
}
#[test]
fn a_new_window_fits_the_work_area() {
// 1920×1080 at 150 % with a 48-pixel taskbar (#5750).
let area = (1280.0, 1032.0 / 1.5);
assert_eq!(fit_new_window((1440.0, 900.0), (400.0, 500.0), area), ((1280.0, 688.0), (400.0, 500.0)));
// A minimum larger than the screen gives way too.
assert_eq!(fit_new_window((1440.0, 900.0), (400.0, 800.0), area).1, (400.0, 688.0));
// A large screen keeps the configured size; an unknown work area changes nothing.
let big = ((1440.0, 900.0), (400.0, 500.0));
assert_eq!(fit_new_window(big.0, big.1, (2560.0, 1400.0)), big);
assert_eq!(fit_new_window(big.0, big.1, (0.0, 0.0)), big);
}
#[test]
fn settings_bounds_fit_current_work_area() {
for (parent, size, work, expected) in [
@@ -3054,4 +3314,38 @@ mod tests {
assert_eq!(menu_settings_launch("main", true, true, "file.settings", None), None);
assert_eq!(menu_settings_launch("main", false, true, "file.openProject", None), None);
}
#[test]
fn parallel_close_coordination_tracks_ready_prompt_and_abort() {
let st = WindowsState::default();
st.close_requested("main");
st.close_requested("project-1");
assert!(st.is_closing("main"));
assert!(st.has_other_pending_closes("main"));
// Prompt turn allows only one holder at a time.
assert_eq!(st.try_acquire_prompt("main"), Ok(true));
assert_eq!(st.try_acquire_prompt("project-1"), Ok(false));
assert!(st.has_prompt_holder());
// Marking ready releases the prompt turn.
assert!(st.mark_ready("main"));
assert!(!st.has_prompt_holder());
assert_eq!(st.try_acquire_prompt("project-1"), Ok(true));
// Cancelling the batch aborts waiting ready peers and clears the prompt holder.
st.abort_all_closing(Some("project-1"));
assert!(!st.has_prompt_holder());
assert!(st.take_aborted("main"));
assert!(!st.is_closing("main"));
assert!(!st.take_aborted("project-1"));
// A fresh close clears any stale aborted state and claims hide once per cohort.
st.close_requested("main");
assert_eq!(
st.claim_hide(&["main".into(), "project-1".into()]),
vec!["main".to_string(), "project-1".to_string()]
);
assert!(st.claim_hide(&["main".into(), "project-1".into()]).is_empty());
}
}
+78 -34
View File
@@ -1,29 +1,45 @@
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI.
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI:
//! not the prompt, not the title bar's close button (the window draws its own), and it never
//! answers a close request. So the prompt is a native message box on its own thread, and the
//! windows close without asking the page.
use parking_lot::Mutex;
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tauri::{AppHandle, Manager, Webview, Wry, plugin};
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
use webview2_com::{
Microsoft::Web::WebView2::Win32::{
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED, ICoreWebView2,
ICoreWebView2ProcessFailedEventArgs2,
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED,
COREWEBVIEW2_PROCESS_FAILED_REASON, ICoreWebView2, ICoreWebView2ProcessFailedEventArgs2,
},
ProcessFailedEventHandler,
};
use windows::core::Interface;
/// How long Restart waits for the event loop to restart the app before restarting the process
/// itself (a main thread stuck in a call to the dead browser never handles the request).
const RESTART_GRACE: Duration = Duration::from_secs(10);
#[derive(Default)]
struct Recovery {
announced_browsers: Mutex<HashSet<u32>>,
/// A browser process exited: the pages can't answer close requests any more.
failed: AtomicBool,
}
impl Recovery {
fn announce(&self, browser_pid: u32) -> bool {
self.failed.store(true, Ordering::SeqCst);
self.announced_browsers.lock().insert(browser_pid)
}
}
/// Whether the web engine has failed, so a window must close without asking its page.
pub fn browser_failed(app: &AppHandle) -> bool {
app.try_state::<Recovery>().is_some_and(|r| r.failed.load(Ordering::SeqCst))
}
pub fn init() -> plugin::TauriPlugin<Wry> {
plugin::Builder::new("webview-recovery")
.setup(|app, _| {
@@ -62,21 +78,38 @@ fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core:
{
return Ok(());
}
let exit_code = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok().and_then(|args| {
let details = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok();
// SAFETY (all three): queried from the live callback arguments on this thread.
let exit_code = details.as_ref().and_then(|args| {
let mut code = 0;
// SAFETY: queried from the live callback arguments on this thread.
unsafe { args.ExitCode(&mut code) }.ok().map(|()| code)
});
tracing::error!(window = %label, browser_pid, ?exit_code, "WebView2 browser process exited unexpectedly");
// Dispatch from a worker so Wry queues the prompt instead of running it
// inline inside WebView2's STA callback.
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || {
let handle = app.clone();
if let Err(error) = app.run_on_main_thread(move || show_recovery(handle)) {
tracing::error!(%error, "cannot show WebView2 recovery prompt");
}
let reason = details.as_ref().and_then(|args| {
let mut reason = COREWEBVIEW2_PROCESS_FAILED_REASON::default();
unsafe { args.Reason(&mut reason) }.ok().map(|()| reason.0)
});
let description = details.as_ref().and_then(|args| {
let mut description = Default::default();
unsafe { args.ProcessDescription(&mut description) }.ok().map(|()| webview2_com::take_pwstr(description))
});
tracing::error!(
window = %label,
browser_pid,
?exit_code,
?reason,
?description,
"WebView2 browser process exited unexpectedly"
);
// Not through the main thread: it may be stuck in a call to the dead browser, and the
// prompt must not run inline inside WebView2's STA callback either.
let app = app.clone();
if let Err(error) = std::thread::Builder::new().name("webview-recovery".into()).spawn(move || {
if ask_restart() {
restart(&app);
}
}) {
tracing::error!(%error, "cannot show WebView2 recovery prompt");
}
Ok(())
}));
let mut token = 0;
@@ -84,26 +117,37 @@ fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core:
unsafe { core.add_ProcessFailed(&handler, &mut token) }
}
fn show_recovery(app: AppHandle) {
let mut dialog = app
.dialog()
.message(
"The Windows web engine stopped unexpectedly. Restart OpenIDEA to recover the interface. \
This restarts all OpenIDEA windows. Unsaved edits may be lost.",
/// A native message box, on top of every window: true for Restart (OK).
fn ask_restart() -> bool {
use windows_sys::Win32::UI::WindowsAndMessaging::{
IDOK, MB_ICONERROR, MB_OKCANCEL, MB_SETFOREGROUND, MB_TOPMOST, MessageBoxW,
};
let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
let text = wide(
"The Windows web engine stopped unexpectedly, so OpenIDEA's windows can no longer respond.\n\n\
Choose OK to restart OpenIDEA and recover the interface. This restarts all OpenIDEA windows; \
unsaved edits may be lost.",
);
let title = wide("OpenIDEA");
// SAFETY: both strings are NUL-terminated and outlive the call; no owner window.
let answer = unsafe {
MessageBoxW(
std::ptr::null_mut(),
text.as_ptr(),
title.as_ptr(),
MB_OKCANCEL | MB_ICONERROR | MB_TOPMOST | MB_SETFOREGROUND,
)
.title("OpenIDEA")
.kind(MessageDialogKind::Error)
.buttons(MessageDialogButtons::OkCancelCustom("Restart OpenIDEA".into(), "Cancel".into()));
if let Some(window) = crate::windows::target_window(&app).filter(|w| w.is_visible().unwrap_or(false)) {
dialog = dialog.parent(&window);
}
dialog.show(move |restart| {
if restart {
// The normal quit waits for a response from each webview. The failed browser
// cannot answer, so restart through Tauri's native exit path.
app.request_restart();
}
});
};
answer == IDOK
}
fn restart(app: &AppHandle) {
// The normal quit waits for a response from each webview. The failed browser cannot
// answer, so restart through Tauri's native exit path.
app.request_restart();
std::thread::sleep(RESTART_GRACE);
tracing::error!("the event loop did not restart OpenIDEA; restarting the process");
tauri::process::restart(&app.env());
}
#[cfg(test)]
+4
View File
@@ -650,6 +650,7 @@ spring_route_sources trusted desktop bin
ssh_askpass_answer always desktop bindings sync
ssh_connected always project_host bindings sync
ssh_disconnect always project_host bindings sync
ssh_legacy_passwords always project_host bindings async
ssh_needs_secret always project_host bindings sync
ssh_open_terminal always desktop bindings async
ssh_password_saved always project_host bindings sync
@@ -829,10 +830,12 @@ web_open always desktop bin
web_serves_page trusted desktop bindings async
web_unresolved_references always project_host bindings async
web_url always project_host bindings async
window_begin_prompt always desktop bindings async
window_close_context always desktop bindings sync
window_complete_launch always desktop bindings sync
window_cycle always desktop bindings sync
window_drag_files always desktop bindings async
window_end_prompt always desktop bindings sync
window_flash_taskbar always desktop bindings sync
window_group_cancel_close always desktop bindings sync
window_group_close always desktop bindings sync
@@ -856,6 +859,7 @@ window_open_project always desktop bin
window_open_projects always desktop bindings sync
window_open_remote always desktop bindings async
window_open_settings always desktop bindings async
window_ready_to_close always desktop bindings async
window_set_smooth_scrolling always desktop bindings sync
window_set_titlebar_height always desktop bindings sync
window_start_drag always desktop bindings sync
+24 -2
View File
@@ -218,7 +218,7 @@ export const commands = {
* Async: the process walk runs on the blocking pool, not the main thread.
*/
appMetrics: () => typedError<AppMetrics, IdeError>(__TAURI_INVOKE("app_metrics")),
/** Quits: closes every window, each of which runs its own unsaved-changes check. */
/** Quits: closes every window in parallel, each of which runs its own unsaved-changes check. */
appQuit: () => __TAURI_INVOKE<void>("app_quit"),
/**
* Release notes of `version` from the update manifest (`latest.json`), read
@@ -858,8 +858,10 @@ export const commands = {
* A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
* The build streams its console, messages and progress on `on_event` while it runs; a launch
* whose build another launch's build joins receives that build's events.
* A Maven module is built by the IDE's Java build, except for a `debug` launch the language
* server serves: java-debug's HotSwap reloads the classes the language server compiles.
*/
javaResolveLaunch: (module: string, test: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, policy, request, onEvent })),
javaResolveLaunch: (module: string, test: boolean, debug: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, debug, policy, request, onEvent })),
/**
* Downloads the latest `vendor` JDK of Java `version` into `location` (default:
* [`jdk_download_location`]), streaming progress through `on_event`; cancellable
@@ -1878,6 +1880,8 @@ export const commands = {
/** Ids of the configurations with an open connection. */
sshConnected: () => __TAURI_INVOKE<string[]>("ssh_connected"),
sshDisconnect: (id: string) => __TAURI_INVOKE<void>("ssh_disconnect", { id }),
/** `Some` means legacy credentials remain in plaintext on this host. */
sshLegacyPasswords: (action: LegacyPasswordAction) => typedError<string | null, IdeError>(__TAURI_INVOKE("ssh_legacy_passwords", { action })),
/** Whether connecting with configuration `id` needs a password first. */
sshNeedsSecret: (id: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("ssh_needs_secret", { id })),
/**
@@ -2279,6 +2283,11 @@ export const commands = {
* HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
*/
webUrl: (path: IpcPath) => typedError<string, IdeError>(__TAURI_INVOKE("web_url", { path })),
/**
* Acquires the interactive prompt turn for a batch close and brings this window forward.
* Returns `false` if the batch was cancelled while waiting.
*/
windowBeginPrompt: () => __TAURI_INVOKE<boolean>("window_begin_prompt"),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Release the opening window's reservation after navigation or cancellation. */
windowCompleteLaunch: () => typedError<null, IdeError>(__TAURI_INVOKE("window_complete_launch")),
@@ -2290,6 +2299,8 @@ export const commands = {
* with whether a target took the files.
*/
windowDragFiles: (paths: string[]) => typedError<boolean, IdeError>(__TAURI_INVOKE("window_drag_files", { paths })),
/** Releases the interactive prompt turn held by this window. */
windowEndPrompt: () => __TAURI_INVOKE<void>("window_end_prompt"),
/**
* Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a
* breakpoint is hit while the window is in the background (macOS bounces the dock icon,
@@ -2369,6 +2380,11 @@ export const commands = {
* `background` (`#rrggbb`) paints a new window until its page has loaded.
*/
windowOpenSettings: (page: string | null, newProjects: boolean, background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_settings", { page, newProjects, background })),
/**
* Signals that this window passed its close checks and waits for peers closing in the same
* batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled.
*/
windowReadyToClose: () => __TAURI_INVOKE<boolean>("window_ready_to_close"),
/** Appearance › Smooth scrolling for this window's web view (Linux only) */
windowSetSmoothScrolling: (enabled: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("window_set_smooth_scrolling", { enabled })),
/** Height of the web title bar in native logical pixels (CSS height × IDE zoom). */
@@ -4243,6 +4259,10 @@ export type CloseContext = {
quitting: boolean,
/** Number of open project windows (settings windows excluded), including the caller. */
windows: number,
/** Whether this window currently has auxiliary document windows that must settle first. */
hasDocumentWindows: boolean,
/** Whether this close runs alongside other windows or on a background tab (prompts serialize and raise). */
batch: boolean,
};
export type CodeAction = {
@@ -9283,6 +9303,8 @@ export type Launch_Serialize = {
editor: EditorLaunch_Serialize | null,
};
export type LegacyPasswordAction = "check" | "retry" | "removePlaintext";
/** One SDK or library with its source folders (`< Python 3.12 (.venv) >`). */
export type LibraryGroup = {
/** Display name, e.g. `Python 3.12 (.venv)`. */
+16
View File
@@ -90,6 +90,8 @@
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
min-width: 3ch;
text-align: end;
}
/* Pin and Archive appear beside the age while the pointer is on the row. */
.rowActions {
@@ -107,6 +109,20 @@
.row:has(.rowActions:focus-within) .age {
margin-left: 0;
}
/* The status mark sits in a fixed slot just before the age, so marks form a column. */
.status {
flex: none;
display: flex;
align-items: center;
justify-content: center;
width: 16px;
margin-left: auto;
}
.row:has(.status) .age,
.row:hover .status,
.row:has(.rowActions:focus-within) .status {
margin-left: 0;
}
.rowAction {
display: flex;
align-items: center;
+7 -2
View File
@@ -422,8 +422,6 @@ export function AgentsView() {
n.task.title
)}
</span>
{/* Ready tasks say so by their group; the others show what they're doing. */}
{n.task.status !== "ready" && <TaskStatusIcon status={n.task.status} />}
{unread.has(n.task.id) && (
<span className={styles.unreadDot} role="img" aria-label={tx("Unread")} title={tx("Unread")} />
)}
@@ -442,6 +440,13 @@ export function AgentsView() {
{canArchive(n.task) &&
rowButton("Archive", "archive", () => void executeAction("agents.archiveTasks", [n.task.id]))}
</span>
{/* Ready tasks say so by their group; the others show what they're doing, in a column
beside the age so the marks line up whatever the title length. */}
{n.task.status !== "ready" && (
<span className={styles.status}>
<TaskStatusIcon status={n.task.status} />
</span>
)}
<span className={styles.age}>{age(n.task.updatedMs ?? 0)}</span>
</span>
);
+1 -1
View File
@@ -526,7 +526,7 @@ function ModelPicker({
!unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
className={styles.chip}
aria-label={tx`Model settings: ${summary}`}
title={
fullSummary && fullSummary !== summary
+15 -3
View File
@@ -1154,7 +1154,7 @@
flex-wrap: wrap;
align-items: center;
align-content: flex-start;
gap: 0 6px;
gap: 0 var(--space-1-5);
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
@@ -1166,7 +1166,7 @@
align-items: center;
min-width: 0;
height: 22px;
gap: 6px;
gap: var(--space-1-5);
}
.meterGroup {
display: inline-flex;
@@ -1174,7 +1174,7 @@
align-items: center;
min-width: 0;
height: 22px;
gap: 6px;
gap: var(--space-1-5);
}
.meterDivider {
flex: none;
@@ -1916,6 +1916,18 @@
flex: none;
color: var(--fg-muted);
}
.toolDir {
flex: none;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 4px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
}
.toolPath {
flex: none;
max-width: 180px;
+17
View File
@@ -43,6 +43,7 @@ import {
entriesKey,
findSubagent,
groupTasks,
providerIcon,
subagentTitle,
turnNumbers,
upsertEntry,
@@ -82,6 +83,22 @@ const option = (category: string, values: string[], current: string | null): Age
via: "option",
});
describe("providerIcon", () => {
it("uses the agent's logo, shared by its legacy and adapter ids", () => {
expect(providerIcon("devin")).toBe("agent-devin");
expect(providerIcon("amp-acp")).toBe("agent-amp-acp");
expect(providerIcon("claude-acp")).toBe("agent-claude");
expect(providerIcon("codex-acp")).toBe("agent-codex");
expect(providerIcon("kimi-code")).toBe("agent-kimi");
expect(providerIcon("opencode-v2")).toBe("agent-opencode");
expect(providerIcon("hermes-work")).toBe("agent-hermes");
});
it("falls back to the generic agents icon", () => {
expect(providerIcon("my-agent")).toBe("toolwindow-agents");
});
});
describe("fenced blocks", () => {
it("finds closed blocks, a longer fence holding backticks", () => {
const text = fenced("a ``` b\n```", "terminal zsh");
+11 -22
View File
@@ -1,5 +1,6 @@
/** Pure helpers: task grouping, entry updates, labels. */
import type { AgentEntry, AgentStatus, AgentSubagentStatus, AgentTask } from "@/bindings";
import { isIconName } from "@/ui/icons";
export const SESSION_KIND = "agent-session";
export const HOME_KIND = "agent-home";
@@ -52,26 +53,6 @@ export function subagentStatusLabel(s: AgentSubagentStatus): string {
}
}
const PROVIDER_ICONS = new Set([
"claude",
"codex",
"gemini",
"copilot",
"cursor",
"opencode",
"qwen",
"qoder",
"qodercn",
"kimi",
"goose",
"auggie",
"kiro",
"vibe",
"omp",
"deepseek-harness",
"hermes",
]);
/** Suggests an agent-file id for a display name (`"My Agent!"` → `"my-agent"`). */
export function slugifyId(name: string): string {
return name
@@ -83,10 +64,18 @@ export function slugifyId(name: string): string {
/** The agent a Hermes profile runs as: `hermes` for `default`, else `hermes-<slug>` (`hermes -p <name> acp`). */
export const hermesAgentId = (profile: string) => (profile === "default" ? "hermes" : `hermes-${slugifyId(profile)}`);
/** Providers whose logo is another provider's: legacy and ACP-adapter ids of the same agent. */
const ICON_ALIASES: Record<string, string> = {
"claude-acp": "claude",
"codex-acp": "codex",
"kimi-code": "kimi",
"opencode-v2": "opencode",
};
/** The agent's logo; custom agents get the generic agents icon, Hermes profiles Hermes'. */
export function providerIcon(provider: string): string {
if (PROVIDER_ICONS.has(provider)) return `agent-${provider}`;
return provider.startsWith("hermes-") ? "agent-hermes" : "toolwindow-agents";
const id = ICON_ALIASES[provider] ?? (provider.startsWith("hermes-") ? "hermes" : provider);
return isIconName(`agent-${id}`) ? `agent-${id}` : "toolwindow-agents";
}
export interface TaskGroup {
+4 -2
View File
@@ -17,7 +17,7 @@ import {
type TurnRow,
} from "./conversationRows";
import { Fold } from "./Folds";
import { samePropsExcept, shortTitle } from "./shared";
import { commandTitle, samePropsExcept, shortTitle } from "./shared";
import { ThoughtEntry, ToolEntry } from "./toolEntries";
/** "Edited 2 files · Read 4 files": what a run of work did; "Reasoning" when it only thought. */
@@ -124,7 +124,9 @@ export const ProcessRun = memo(function ProcessRun({
const live = [...tools].reverse().find(({ entry }) => liveTool(entry))?.entry;
const last = row.entries.at(-1)!.entry;
const current = live
? shortTitle(task, live.title || live.kind)
? live.kind === "execute"
? commandTitle(task, live.title || live.kind).title
: shortTitle(task, live.title || live.kind)
: working && last.type === "thought"
? tx("Thinking")
: null;
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { AgentEntry } from "@/bindings";
import { foldedTurns } from "../timeline";
import { foldedTurns, summarizeWork } from "../timeline";
import { conversationRows, foldTurnRows, rowEntries, sameRow } from "./conversationRows";
const user = (text: string): AgentEntry => ({
@@ -47,6 +47,30 @@ describe("conversationRows", () => {
expect(rows[4]!.kind === "process" ? rows[4]!.entries.length : 0).toBe(2);
});
it("groups shell commands that only read or search, and keeps the others separate", () => {
const run = (id: string, title: string): AgentEntry => ({
...(tool(id, "execute") as Extract<AgentEntry, { type: "tool" }>),
title,
});
const entries: AgentEntry[] = [
user("a"),
{ type: "thought", text: "look around" },
run("c1", "cd /repo && git grep -n foo -- src"),
run("c2", "sed -n 1,40p src/a.ts"),
{ type: "thought", text: "now test" },
run("c3", "pnpm test"),
run("c4", "git diff --stat"),
run("c5", "cat a.ts | head"),
agent("done"),
];
const rows = conversationRows(entries, 0);
expect(rows.map((row) => row.kind)).toEqual(["entry", "process", "entry", "process", "entry"]);
expect(rows[1]!.kind === "process" ? rows[1]!.entries.map((e) => e.index) : []).toEqual([1, 2, 3, 4]);
expect(rows[3]!.kind === "process" ? rows[3]!.entries.map((e) => e.index) : []).toEqual([6, 7]);
const work = summarizeWork(rowEntries(rows[1]!));
expect([work.search, work.read, work.run]).toEqual([1, 1, 0]);
});
it("flattens grouped runs inside a folded turn to avoid nested folds", () => {
const entries: AgentEntry[] = [
user("a"),
@@ -1,5 +1,5 @@
import type { AgentEntry } from "@/bindings";
import { type FoldedTurn } from "../timeline";
import { exploringCommand, type FoldedTurn } from "../timeline";
export type ToolEntryData = Extract<AgentEntry, { type: "tool" }>;
@@ -23,12 +23,16 @@ export const liveTool = (entry: AgentEntry) =>
const EXPLORATION_KINDS = new Set(["read", "search", "fetch", "think"]);
/**
* Reasoning and read-only exploration tool calls fold together, running ones included: the run
* keeps its place while a call finishes, and its summary line says what is running. Edits,
* commands and other side-effecting calls stay visible as their own rows.
* Reasoning and read-only exploration fold together, running calls included: the run keeps its
* place while a call finishes, and its summary line says what is running. Exploration is a
* read, search or fetch, or a shell command that only reads or searches (`grep`, `sed -n`,
* `git diff`); edits and other commands stay visible as their own rows.
*/
export const isProcessEntry = (entry: AgentEntry) =>
entry.type === "thought" || (entry.type === "tool" && EXPLORATION_KINDS.has(entry.kind) && entry.diffs.length === 0);
entry.type === "thought" ||
(entry.type === "tool" &&
entry.diffs.length === 0 &&
(EXPLORATION_KINDS.has(entry.kind) || exploringCommand(entry) !== null));
/**
* The conversation's rows from `from`: a run of reasoning and finished tool calls becomes
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { AgentTask } from "@/bindings";
import { commandTitle } from "./shared";
const task = { cwd: "/repo/app" } as AgentTask;
describe("commandTitle", () => {
it("drops a cd into the task's own folder", () => {
expect(commandTitle(task, "cd /repo/app && git grep -n foo")).toEqual({ title: "git grep -n foo", dir: null });
expect(commandTitle(task, "cd . ; ls")).toEqual({ title: "ls", dir: null });
});
it("keeps another folder as the place the command ran", () => {
expect(commandTitle(task, "cd /repo/app-icons && pnpm test")).toEqual({
title: "pnpm test",
dir: "/repo/app-icons",
});
expect(commandTitle(task, `cd "/repo/my app/" && ls`)).toEqual({ title: "ls", dir: "/repo/my app" });
});
it("leaves commands without a leading cd, or that are only a cd, as they are", () => {
expect(commandTitle(task, "git status && cd x && ls")).toEqual({ title: "git status && cd x && ls", dir: null });
expect(commandTitle(task, "cd /tmp")).toEqual({ title: "cd /tmp", dir: null });
expect(commandTitle(task, "cat /repo/app/src/a.ts")).toEqual({ title: "cat src/a.ts", dir: null });
});
});
+10
View File
@@ -1,5 +1,6 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import { useEffect, useState } from "react";
import { splitLeadingCd } from "../shellCommand";
import { useAgents } from "../store";
export function providerName(id: string) {
@@ -21,6 +22,15 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Agent-written titles with the task's own folder dropped from paths. */
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
/**
* A command's title without the `cd <dir> &&` agents put before every call, and the folder it
* moved to when that is not the task's own: the command is what tells calls apart.
*/
export function commandTitle(task: AgentTask, title: string): { title: string; dir: string | null } {
const { command, dir } = splitLeadingCd(title);
return { title: shortTitle(task, command), dir: dir === task.cwd || dir === "." ? null : dir };
}
/**
* `memo`'s comparison for props rebuilt with every render without changing: a prop named in
* `by` is equal when its rule says so, any other prop when it is the same value.
+11 -2
View File
@@ -16,7 +16,7 @@ import { cancelTask } from "../store";
import { openChangeDiff } from "./ChangesTab";
import { Fold } from "./Folds";
import { liveTool } from "./conversationRows";
import { shortTitle, useNow } from "./shared";
import { commandTitle, shortTitle, useNow } from "./shared";
/** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
@@ -104,13 +104,22 @@ export const ToolEntry = memo(function ToolEntry({
const live = liveTool(entry);
const took = toolDuration(entry);
const run = entry.kind === "execute" ? toolRun(entry) : null;
const title = shortTitle(task, entry.title || entry.kind);
// Commands lose the `cd <dir> &&` agents start them with; another folder shows as a tag.
const { title, dir } =
entry.kind === "execute"
? commandTitle(task, entry.title || entry.kind)
: { title: shortTitle(task, entry.title || entry.kind), dir: null };
// A title that already names the file ("Read pom.xml") needs no second link to it.
const links =
entry.kind === "execute" ? [] : entry.locations.slice(0, 3).filter((path) => !title.includes(basename(path)));
const head = (
<>
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} className={styles.toolKindIcon} />
{dir && (
<span className={styles.toolDir} title={dir}>
{basename(dir)}
</span>
)}
<span className={styles.toolTitle} title={entry.title || entry.kind}>
{title}
</span>
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { readOnlyCommand, splitLeadingCd } from "./shellCommand";
describe("splitLeadingCd", () => {
it("takes the folder off the front", () => {
expect(splitLeadingCd("cd /repo && git status")).toEqual({ command: "git status", dir: "/repo" });
expect(splitLeadingCd(`cd "/my repo/" ; ls`)).toEqual({ command: "ls", dir: "/my repo" });
expect(splitLeadingCd("cd /tmp")).toEqual({ command: "cd /tmp", dir: null });
});
});
describe("readOnlyCommand", () => {
it.each([
["git grep -n foo -- src", "search"],
["cd /repo && rg -n 'a|b' src | head -20", "search"],
["grep -rn foo src 2>/dev/null | wc -l", "search"],
["find . -name '*.ts' -not -path './node_modules/*'", "search"],
["sed -n 1,40p src/a.ts", "read"],
["cat a.ts; echo ---; head -5 b.ts", "read"],
["git diff --stat origin/main...HEAD", "read"],
["git -C ../other log --oneline -3", "read"],
["ls -la src && wc -l src/*.ts", "read"],
["git branch --show-current", "read"],
["git worktree list | head; grep -n x LICENSE | head", "search"],
["pgrep -fl openidea | head", "read"],
["FOO=1 cat a.ts 2>&1 | sort | uniq -c", "read"],
])("%s → %s", (command, kind) => {
expect(readOnlyCommand(command)).toBe(kind);
});
it.each([
"pnpm test",
"cargo build",
"git commit -m 'x'",
"git branch -D old",
"git worktree add ../x",
"git stash -q",
"git remote add up url",
"sed -i '' 's/a/b/' a.ts",
"sed -n 1p a.ts > out.txt",
"grep foo a.ts >> log",
"find . -name '*.tmp' -delete",
"find . -exec rm {} ;",
"cat a.ts | xargs rm",
"echo $(rm -rf x)",
"cat <<'EOF' > a.ts",
"sort -o a.txt a.txt",
"sleep 10 &",
"rm -rf build",
"",
])("%s may change something", (command) => {
expect(readOnlyCommand(command)).toBeNull();
});
it("does not split on operators inside quotes", () => {
expect(readOnlyCommand(`grep -n "a && rm -rf /" src`)).toBe("search");
expect(readOnlyCommand(`echo 'x' ; rm a`)).toBeNull();
});
});
+159
View File
@@ -0,0 +1,159 @@
/** Reading what an agent's shell command does, from its text alone. */
/** A leading `cd <dir> &&` (or `;`), with the directory quoted or bare. */
const LEADING_CD = /^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)\s*/;
/** `command` without the `cd <dir> &&` agents put before it, and that folder; `null` when there is none. */
export function splitLeadingCd(command: string): { command: string; dir: string | null } {
const match = LEADING_CD.exec(command);
if (!match || match[0].length === command.length) return { command, dir: null };
const dir = match[1]!.replace(/^(["'])(.*)\1$/, "$2").replace(/\/+$/, "");
return { command: command.slice(match[0].length), dir };
}
/** Programs that look for something. */
const SEARCH = new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "find", "fd", "mdfind", "locate"]);
/** Programs that only print what is there. */
const READ = new Set([
"cat",
"head",
"tail",
"sed",
"awk",
"nl",
"wc",
"ls",
"tree",
"stat",
"file",
"pwd",
"echo",
"printf",
"jq",
"sort",
"uniq",
"cut",
"tr",
"column",
"diff",
"cmp",
"which",
"type",
"realpath",
"readlink",
"basename",
"dirname",
"du",
"df",
"true",
"cd",
"ps",
"pgrep",
"lsof",
"date",
"uname",
"whoami",
]);
/** Git subcommands that only read the repository. */
const GIT_READ = new Set([
"status",
"diff",
"log",
"show",
"blame",
"ls-files",
"ls-tree",
"rev-parse",
"merge-base",
"describe",
"cat-file",
"shortlog",
"reflog",
]);
/** Splits on `&&`, `||`, `;` and `|` outside quotes; `null` when the text has what this can't read safely. */
function segments(command: string): string[] | null {
const out: string[] = [];
let current = "";
let quote: string | null = null;
for (let i = 0; i < command.length; i++) {
const c = command[i]!;
if (quote) {
if (c === quote) quote = null;
else if (c === "\\" && quote === '"') current += command[i++] ?? "";
current += c;
continue;
}
if (c === "'" || c === '"') quote = c;
else if (c === "`" || c === "\n" || (c === "$" && command[i + 1] === "(")) return null;
else if (c === "<" && command[i + 1] === "<") return null;
else if (c === ">") {
// Only output thrown away (`>/dev/null`, `2>&1`) leaves the disk as it was.
const target = /^>?\s*(\/dev\/null\b|&\d)/.exec(command.slice(i + 1));
if (!target) return null;
i += target[0].length;
continue;
} else if (c === ";" || c === "|" || (c === "&" && command[i + 1] === "&")) {
out.push(current);
current = "";
if (command[i + 1] === c) i++;
continue;
} else if (c === "&") return null;
current += c;
}
if (quote) return null;
out.push(current);
return out.map((s) => s.trim()).filter(Boolean);
}
const words = (segment: string) => segment.match(/"[^"]*"|'[^']*'|\S+/g) ?? [];
/** What one segment does: `"search"`, `"read"`, or `null` when it may change something. */
function segmentKind(segment: string): "search" | "read" | null {
const args = words(segment).filter(
(w, i, all) => !(/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) && all.slice(0, i).every((p) => /=/.test(p))),
);
const [program, ...rest] = args;
if (!program) return null;
const name = program.replace(/^.*\//, "");
if (name === "git") {
// Global options before the subcommand, some taking a value (`git -C <dir> log`).
let at = 0;
while (at < rest.length && rest[at]!.startsWith("-"))
at += /^(-C|-c|--git-dir|--work-tree|--namespace)$/.test(rest[at]!) ? 2 : 1;
const sub = rest[at];
if (sub === "grep") return "search";
const next = rest[at + 1];
if (sub === "worktree" || sub === "stash")
return next === "list" || (sub === "stash" && next === "show") ? "read" : null;
if (sub === "remote") return next === undefined || next === "-v" || next === "show" ? "read" : null;
if (sub === "branch") return rest.some((a) => /^-(d|D|m|M|c|C|-delete|-move|-copy)$/.test(a)) ? null : "read";
return sub && GIT_READ.has(sub) ? "read" : null;
}
if (name === "sed" && rest.some((a) => /^-[a-zA-Z]*i|^--in-place/.test(a))) return null;
if (name === "awk" && rest.some((a) => /inplace/.test(a))) return null;
if (name === "sort" && rest.some((a) => /^-[a-zA-Z]*o|^--output/.test(a))) return null;
if (name === "find" && rest.some((a) => /^-(delete|exec|execdir|ok|okdir|fprint|fprintf|fls)$/.test(a))) return null;
if (name === "fd" && rest.some((a) => /^(-x|-X|--exec|--exec-batch)$/.test(a))) return null;
if (SEARCH.has(name)) return "search";
return READ.has(name) ? "read" : null;
}
/**
* Whether a shell command only looks at the workspace, and how: `"search"` when it looks for
* something (`grep`, `rg`, `find`, `git grep`), `"read"` when it prints files or state (`cat`,
* `sed -n`, `ls`, `git diff`); `null` when it may change something or can't be told.
*/
export function readOnlyCommand(command: string): "search" | "read" | null {
const parts = segments(splitLeadingCd(command).command);
if (!parts?.length) return null;
let kind: "search" | "read" = "read";
for (const part of parts) {
const k = segmentKind(part);
if (!k) return null;
if (k === "search") kind = "search";
}
return kind;
}
+17 -2
View File
@@ -3,6 +3,7 @@
* the conversation renders the rows these describe.
*/
import type { AgentEntry } from "@/bindings";
import { readOnlyCommand } from "./shellCommand";
type ToolEntry = Extract<AgentEntry, { type: "tool" }>;
@@ -56,9 +57,14 @@ function countTool(s: WorkSummary, e: ToolEntry, edited: Set<string>) {
case "search":
s.search++;
break;
case "execute":
s.run++;
case "execute": {
// A command that only reads or searches counts as what it did.
const kind = exploringCommand(e);
if (kind === "search") s.search++;
else if (kind === "read") s.read++;
else s.run++;
break;
}
case "fetch":
s.fetch++;
break;
@@ -148,6 +154,15 @@ export interface ToolRun {
}
/** Splits an `execute` tool's text into its command, output and exit code, where it names them. */
/**
* How a shell command call only looks at the workspace (`"search"`, `"read"`), from the command
* it ran; `null` for any other call, or a command that may change something.
*/
export function exploringCommand(entry: ToolEntry): "search" | "read" | null {
if (entry.kind !== "execute" || entry.diffs.length) return null;
return readOnlyCommand(toolRun(entry).command ?? entry.title);
}
export function toolRun(entry: ToolEntry): ToolRun {
const text = entry.output ?? "";
const command = /^\$ (.+)$/m.exec(text)?.[1] ?? null;
+89 -7
View File
@@ -35,7 +35,15 @@ const flushSession = vi.fn();
beforeEach(() => {
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
vi.spyOn(ipc, "onIdeEvent").mockReturnValue(() => {});
vi.spyOn(ipc.commands, "windowCloseContext").mockResolvedValue({ quitting: false, windows: 1 });
vi.spyOn(ipc.commands, "windowCloseContext").mockResolvedValue({
quitting: false,
windows: 1,
hasDocumentWindows: false,
batch: false,
});
vi.spyOn(ipc.commands, "windowBeginPrompt").mockResolvedValue(true);
vi.spyOn(ipc.commands, "windowEndPrompt").mockResolvedValue(undefined);
vi.spyOn(ipc.commands, "windowReadyToClose").mockResolvedValue(true);
vi.spyOn(ipc.commands, "windowGroupCancelClose").mockResolvedValue(undefined);
vi.spyOn(ipc.commands, "appCancelQuit").mockResolvedValue(undefined);
vi.spyOn(ipc.commands, "closeProject").mockResolvedValue(undefined);
@@ -89,7 +97,12 @@ describe("native window close", () => {
});
it.each([1, 2])("closes one of %s windows when opted in", async (windows) => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows });
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: false,
windows,
hasDocumentWindows: false,
batch: false,
});
const prevented = await close({ closeWithoutWelcome: true, closeTabsWithWindow: true });
expect(prevented).not.toHaveBeenCalled();
expect(ipc.commands.closeProject).not.toHaveBeenCalled();
@@ -97,7 +110,12 @@ describe("native window close", () => {
});
it("closes a nonlast window with defaults and keeps its saved tabs", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: false,
windows: 2,
hasDocumentWindows: false,
batch: false,
});
const prevented = await close({});
expect(prevented).not.toHaveBeenCalled();
expect(ipc.commands.closeProject).not.toHaveBeenCalled();
@@ -126,7 +144,12 @@ describe("native window close", () => {
});
it("stays open when an untitled buffer's Save As is cancelled", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: false,
windows: 2,
hasDocumentWindows: false,
batch: false,
});
vi.mocked(services.maybeEditorService).mockReturnValue({
forgetSavedTabs: forget,
keepSavedTabs: keep,
@@ -159,7 +182,12 @@ describe("native window close", () => {
os: "linux",
commands: [],
});
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: false,
windows: 2,
hasDocumentWindows: false,
batch: false,
});
vi.mocked(deps.ask).mockResolvedValueOnce({ button: "keep", checked: false });
const terminate = vi.fn(async () => {});
deps.runningProcesses = vi.fn(async () => ["docker compose up"]);
@@ -221,7 +249,12 @@ describe("quitting from outside the window", () => {
});
it("leaves a window with nothing to ask where it is while the app quits", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: true, windows: 2 });
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: true,
windows: 2,
hasDocumentWindows: false,
batch: true,
});
deps.runningProcesses = async () => [];
const { d, asked } = recordingDeps("cancel");
useProject.setState({
@@ -234,10 +267,17 @@ describe("quitting from outside the window", () => {
await native.close!({ preventDefault: vi.fn() });
expect(asked).toEqual([]);
expect(native.order).toEqual([]);
expect(ipc.commands.windowBeginPrompt).not.toHaveBeenCalled();
expect(ipc.commands.windowReadyToClose).toHaveBeenCalledOnce();
});
it("raises each window before the prompts a quit makes it show", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: true, windows: 2 });
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: true,
windows: 2,
hasDocumentWindows: false,
batch: true,
});
deps.runningProcesses = async () => ["server.js"];
const { d } = recordingDeps("cancel");
useProject.setState({
@@ -249,6 +289,48 @@ describe("quitting from outside the window", () => {
await vi.waitFor(() => expect(native.close).toBeDefined());
await native.close!({ preventDefault: vi.fn() });
expect(native.order.slice(0, 4)).toEqual(["unminimize", "show", "setFocus", "ask"]);
expect(ipc.commands.windowBeginPrompt).toHaveBeenCalledOnce();
expect(ipc.commands.windowEndPrompt).toHaveBeenCalledOnce();
expect(ipc.commands.appCancelQuit).toHaveBeenCalledOnce();
});
it("restores saved tabs and stays open when a peer cancels the batch at the close barrier", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: true,
windows: 2,
hasDocumentWindows: false,
batch: true,
});
vi.mocked(ipc.commands.windowReadyToClose).mockResolvedValueOnce(false);
const prevented = await close({ closeTabsWithWindow: true });
expect(prevented).toHaveBeenCalledOnce();
expect(forget).toHaveBeenCalledOnce();
expect(keep).toHaveBeenCalledOnce();
expect(ipc.commands.appCancelQuit).not.toHaveBeenCalled();
});
it("skips prompting when a peer already cancelled the batch while waiting for the prompt turn", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({
quitting: true,
windows: 2,
hasDocumentWindows: false,
batch: true,
});
vi.mocked(ipc.commands.windowBeginPrompt).mockResolvedValueOnce(false);
deps.runningProcesses = async () => ["server.js"];
const { d, asked } = recordingDeps("terminate");
useProject.setState({
project: { root: "/project", name: "project" },
lightEdit: false,
settings: { general: {} },
} as never);
uninstall = installCloseGuard(d);
await vi.waitFor(() => expect(native.close).toBeDefined());
const preventDefault = vi.fn();
await native.close!({ preventDefault });
expect(preventDefault).toHaveBeenCalledOnce();
expect(asked).toEqual([]);
expect(native.order).toEqual([]);
expect(ipc.commands.appCancelQuit).not.toHaveBeenCalled();
});
});
+36 -4
View File
@@ -248,8 +248,12 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
closing = true;
let forgot = false;
let quitting = false;
let promptHeld = false;
let batchAborted = false;
const cancel = async () => {
await (quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
if (!batchAborted) {
await (quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
}
return false;
};
const undoForget = () => {
@@ -260,9 +264,27 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
try {
const ctx = await commands.windowCloseContext();
quitting = ctx.quitting;
// Each window of a quit asks about its own processes and unsaved changes, if it has any.
if (quitting) deps = raisingBeforeAsk(deps);
if (!(await closeDocumentWindows())) return await cancel();
// In a quit or multi-tab close, windows check in parallel; only a window that needs to ask
// acquires the prompt turn and comes forward so prompts still run one at a time.
if (quitting || ctx.batch) {
const baseAsk = deps.ask;
deps = {
...deps,
ask: async (request) => {
if (!promptHeld) {
const proceed = await commands.windowBeginPrompt();
if (!proceed) {
batchAborted = true;
return { button: "cancel", checked: false };
}
promptHeld = true;
}
await raiseWindowForPrompts();
return baseAsk(request);
},
};
}
if (ctx.hasDocumentWindows !== false && !(await closeDocumentWindows())) return await cancel();
const s = useProject.getState();
const welcome = returnsToWelcome(quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings);
const remote = useRemote.getState();
@@ -316,6 +338,12 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
forgot = false;
return await cancel();
}
if (!(await commands.windowReadyToClose())) {
batchAborted = true;
undoForget();
maybeEditorService()?.cancelClose?.();
return false;
}
return true;
} catch (e) {
undoForget();
@@ -324,6 +352,10 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
deps.onSaveFailed(e);
return false;
} finally {
if (promptHeld) {
promptHeld = false;
void commands.windowEndPrompt().catch(() => {});
}
closing = false;
}
}
+2 -2
View File
@@ -99,7 +99,7 @@ describe("Java debugging (java-debug through jdtls)", () => {
expect(isJavaDebuggable({ ...app, kind: "maven" })).toBe(false);
const l = await javaLaunchConfig(app, "/p");
expect(invoked).toEqual([
["javaResolveLaunch", ["api", false, "automatic", expect.any(Number), expect.anything()]],
["javaResolveLaunch", ["api", false, true, "automatic", expect.any(Number), expect.anything()]],
["javaDebugAdapter", ["api"]],
["javaDebugServer", ["api"]],
]);
@@ -240,7 +240,7 @@ it.each(["sibling", "/outside/modules"])("debugs from %s with the main class mod
const launch = await javaLaunchConfig({ ...app, module, cwd }, "/p");
expect(invoked).toContainEqual([
"javaResolveLaunch",
["api", false, "automatic", expect.any(Number), expect.anything()],
["api", false, true, "automatic", expect.any(Number), expect.anything()],
]);
expect(invoked).toContainEqual(["javaDebugServer", ["api"]]);
expect(launch.cwd).toBe(cwd.startsWith("/") ? cwd : `/p/${cwd}`);
@@ -70,7 +70,7 @@ async function startAndStop() {
).toContain("Building and resolving the classpath of Main…");
expect(useDebugRunSessions.getState().sessions[0]?.configId).toBe(config.id);
await executeAction("debug.stop");
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![3]);
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![4]);
expect(useDebug.getState().sessions[session.id]?.status).toBe("terminated");
expect(useDebugRunSessions.getState().sessions).toEqual([]);
return { starting };
+5 -5
View File
@@ -145,16 +145,16 @@ export async function javaLaunchConfig(
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
preparation?.signal.throwIfAborted();
const { module, info, resolved } = await prepareJavaLaunch(
rc,
preparation ?? {
const { module, info, resolved } = await prepareJavaLaunch(rc, {
...(preparation ?? {
request: nextRequestId(),
signal: new AbortController().signal,
saveAll: async () => {
await maybeEditorService()?.saveAll();
},
},
);
}),
debug: true,
});
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
if (info.errorCount > 0 && !preparation?.report)
notifications().notify({
+2 -2
View File
@@ -147,7 +147,7 @@ const boot = {
describe("Spring Boot application updates", () => {
it("processes resources and publishes them to the resolved runtime output", async () => {
await updateTomcat(boot, "resources");
expect(mocks.resolve).toHaveBeenCalledWith("app", false, "noBuild", 1, expect.anything());
expect(mocks.resolve).toHaveBeenCalledWith("app", false, true, "noBuild", 1, expect.anything());
expect(mocks.runBuild).toHaveBeenCalledWith({ id: "build" });
expect(mocks.publish).toHaveBeenCalledWith(boot.config, ["/p/app/bin/main"], "a.Main");
expect(mocks.update).not.toHaveBeenCalled();
@@ -155,7 +155,7 @@ describe("Spring Boot application updates", () => {
});
it("compiles and invokes the existing scoped HotSwap action in debug", async () => {
await updateTomcat(boot, "classes");
expect(mocks.resolve).toHaveBeenCalledWith("app", false, "make", 1, expect.anything());
expect(mocks.resolve).toHaveBeenCalledWith("app", false, true, "make", 1, expect.anything());
expect(mocks.action).toHaveBeenCalledWith("debug.reloadChangedClasses", { configId: "boot" });
});
it("explains compiled classes require restart without a debugger", async () => {
+2
View File
@@ -54,6 +54,8 @@ async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging:
mode === "classes" ? "make" : "noBuild",
request,
followLaunchBuild(request, tx`Build before launch: ${config.name}`),
// HotSwap reloads what the Java language server compiles.
debugging,
);
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
throw updateBuildError(info);
+64 -8
View File
@@ -84,7 +84,14 @@ afterEach(() => {
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
const session = await startRun({ ...config, module: "app", cwd });
expect(session?.status).toBe("running");
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ cwd, args: ["-cp", "/p/app/target/classes", "a.Main"] }),
expect.anything(),
@@ -108,13 +115,27 @@ const launchInfo = (build: "succeeded" | "failed" | "withErrors") => ({
it.each(["noBuild", "rebuild"] as const)("passes the %s build policy to the resolver", async (buildPolicy) => {
await startRun({ ...config, module: "app", buildPolicy });
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, buildPolicy, expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
buildPolicy,
expect.any(Number),
expect.anything(),
);
});
it("always applies the launch policy after a Before launch Build Project", async () => {
useProject.setState({ project: { root: "/p" } as never });
await startRun({ ...config, module: "app" });
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
useProject.setState({ project: null });
});
@@ -145,7 +166,14 @@ it.each([undefined, "automatic", "make", "rebuild"] as const)(
it("finds the source module for an old saved configuration without a module", async () => {
await startRun({ ...config, cwd: "/outside/modules" });
expect(ipc.findFiles).toHaveBeenCalledWith("Main.java", 1000);
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ cwd: "/outside/modules" }),
expect.anything(),
@@ -166,7 +194,14 @@ it.each([null, "/elsewhere"])("recovers an attached module from its indexed path
});
const session = await startRun({ ...config, cwd });
expect(session?.status).toBe("running");
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
module,
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ cwd: cwd ?? module, module }),
expect.anything(),
@@ -184,7 +219,14 @@ it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath reso
expect.anything(),
expect.any(Number),
);
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
expect(boot.args).toBe(args);
expect(args).not.toContain("-Dspring.output.ansi.enabled=always");
});
@@ -193,14 +235,28 @@ it.each(["never", "detect", "always"])("preserves an explicit Spring Boot consol
const args = [`-Dspring.output.ansi.enabled=${value}`, "-cp", "lib/*", "a.Main"];
await startRun({ ...config, kind: "spring-boot", args });
expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number));
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
});
it("keeps plain Java runs with an explicit classpath free of Spring Boot options", async () => {
const args = ["-cp", "lib/*", "a.Main"];
await startRun({ ...config, args });
expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number));
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
"app",
false,
false,
"automatic",
expect.any(Number),
expect.anything(),
);
});
it("adds the Spring Boot console option once when resolving the module classpath", async () => {
+1 -1
View File
@@ -69,7 +69,7 @@ describe("Stop during Java launch resolution", () => {
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
const session = useRun.getState().sessions[0]!;
expect(session.status).toBe("starting");
const request = ipc.javaResolveLaunch.mock.calls[0]![3];
const request = ipc.javaResolveLaunch.mock.calls[0]![4];
expect(request).toEqual(expect.any(Number));
await stopSession(session.id);
expect(ipc.cancelRequest).toHaveBeenCalledExactlyOnceWith(request);
+8 -1
View File
@@ -292,7 +292,14 @@ describe("updating a running Tomcat deployment", () => {
it("compiles the selected WAR module and copies its outputs instead of rebuilding the WAR", async () => {
const c = config({ deployment: "artifact", artifact: "maven:web/pom.xml" });
expect(await syncTomcatOutputs(c, false)).toBe(true);
expect(commands.javaResolveLaunch).toHaveBeenCalledWith("web", false, "make", expect.anything(), expect.anything());
expect(commands.javaResolveLaunch).toHaveBeenCalledWith(
"web",
false,
false,
"make",
expect.anything(),
expect.anything(),
);
expect(commands.runTomcatSync).toHaveBeenCalledWith(c, "web", ["/p/web/target/classes", "/m2/lib.jar"], false);
});
+2
View File
@@ -8,10 +8,12 @@ import { onIdeEvent } from "@/platform/ipc";
import { registerOverlay } from "@/workbench/contributions";
import { dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { AskpassHost } from "./AskpassDialog";
import { startPasswordMigrationNotice } from "./passwordMigration";
import { chooseSshSession, SSH_SETTINGS_PAGE, startSshSession } from "./session";
export function activate(): () => void {
const disposers = [
startPasswordMigrationNotice(),
registerOverlay({ id: "ssh.askpass", component: AskpassHost }),
onIdeEvent("askpass", (e) => enqueueAskpass({ id: e.id, prompt: e.prompt, kind: e.kind, remember: e.remember })),
onIdeEvent("askpassDone", (e) => dropAskpass(e.id)),
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more