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

..
8 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai c6a1a36676 chore: v0.1.3
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 17:30:21 +08:00
l0ng-ai 6165cb0174 perf: Add a black-box comparison with other IDEs (#6)
perf/compare/bench.py launches each IDE in apps.toml on the same project
and measures it from the outside, the same way for each: time to the
project window, to CPU settling and to log markers; memory and CPU of the
whole process tree; idle CPU, exit time, cache and install size. Runs on
Windows, macOS and Linux with psutil; --wipe-caches measures a cold index.

README: a Benchmark section with the first results against IntelliJ IDEA.
2026-10-23 16:54:39 +08:00
l0ng-ai 79f6caeaa8 test: Count ignored names in the excluded-folders glob test (#8)
a66f01e adds files.ignoredNames to exclude_globs(), so the expected
length is file_excludes() + 1, not files.exclude + 1. The test failed on
every platform since.
2026-10-23 16:41:18 +08:00
l0ng-ai dbfe66a119 chore: Add generated IDE-state .gitignore files 2026-10-23 15:40:41 +08:00
l0ng-ai a66f01ec87 feat(files): Add Ignored Files and Folders setting, honoured everywhere
Name patterns the IDE treats as nonexistent (.DS_Store, __pycache__, *.pyc, VCS dirs, ...) were hard-coded in five places, and Git changes ignored none of them, so .DS_Store showed up as unversioned. files.ignoredNames (IDEA's default list) now drives the project view, navigation bar, index, watcher, Find in Files, inspections and the Git status.
2026-10-23 15:40:41 +08:00
l0ng-ai bf06ca7832 feat(app): Show a themed splash until the launch project opens
Project windows are created in setup with the saved theme's frame colour, and the splash covers the first render while the launch project opens, so a window no longer flashes white or the Welcome screen. Single-instance is now release-only so a dev build can run beside an installed release.
2026-10-23 15:40:41 +08:00
l0ng-ai 63a03d1c08 fix: Status refresh loop, double project open at startup, jdtls Java requirement (#5)
* fix: Stop the status refresh loop and the double project open at startup

Every status rewrote .git/index, even with nothing to persist: gix's
`write_changes` writes an empty change set too. The watcher reports
.git/index writes as VCS changes, so each status triggered the next one,
together with an ahead/behind walk. On a repository with a long history
(freqtrade, 33k commits behind upstream) that kept a core busy for as long
as the project was open. Write back only when `has_changes()`.

A project passed on the command line was opened twice: the launch and the
"reopen last project" restore ran concurrently, and the restore checked
for an open project before the launch had finished. The second open found
the index cache locked and indexed in memory only; with a different last
project, the window ended up on whichever finished last. The restore now
waits for the startup launch.

* fix(lsp): Run jdtls on the Java version its bundles need

jdtls's launcher checks for Java 21, and so did JDTLS_MIN_JAVA, but the
Eclipse platform a release ships moves on: 1.63 bundles
org.eclipse.core.filesystem with JavaSE-25, so on a JDK 21 the server died
resolving its bundles ("jdtls is not ready (Crashed)") and the error told
users to install the 21 they already had.

Read the requirement from the installed jdtls instead: the highest osgi.ee
capability / Bundle-RequiredExecutionEnvironment among its plugins'
manifests (cached per install), never below 21. The runtime choice, the
rescan while no JDK fits and the "needs JDK N" message use it.

Fixes #4
2026-10-23 15:20:36 +08:00
l0ng-ai 4be1b152ef fix(ui): Drop the inner focus outline on text and search fields
The global :focus-visible outline outranked the module's `outline: none`
by load order, drawing a second ring inside the framed field's own focus
ring (visible on the Settings search box).

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 14:52:13 +08:00
44 змінених файлів з 1442 додано та 111 видалено

No files matched your search

+3
Переглянути файл
@@ -0,0 +1,3 @@
# Per-user IDE state
/shelf/
/changelists.json
+3
Переглянути файл
@@ -0,0 +1,3 @@
# Per-user IDE state
/shelf/
/changelists.json
Створено
+27 -26
Переглянути файл
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-analysis"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3976,7 +3976,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -3991,7 +3991,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"dunce",
"serde",
@@ -4003,7 +4003,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-run",
@@ -4017,7 +4017,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4034,7 +4034,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4054,7 +4054,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"libc",
@@ -4067,7 +4067,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4081,7 +4081,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"parking_lot",
@@ -4099,7 +4099,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"blake3",
"criterion",
@@ -4121,7 +4121,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"futures",
"ide-core",
@@ -4136,7 +4136,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"blake3",
"criterion",
@@ -4188,7 +4188,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"futures",
"globset",
@@ -4211,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-language",
@@ -4229,7 +4229,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-run",
@@ -4242,7 +4242,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4260,7 +4260,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"dunce",
"ide-core",
@@ -4272,11 +4272,12 @@ dependencies = [
"tempfile",
"toml 0.9.12+spec-1.1.0",
"tracing",
"zip 2.4.2",
]
[[package]]
name = "ide-search"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"criterion",
"globset",
@@ -4295,7 +4296,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-language",
@@ -4310,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"ide-core",
"libc",
@@ -4323,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"criterion",
"ide-core",
@@ -4335,7 +4336,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"flate2",
"hex",
@@ -4355,7 +4356,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"dunce",
"gix",
@@ -4372,7 +4373,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"chardetng",
"dunce",
@@ -4392,7 +4393,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"blake3",
"dunce",
@@ -5816,7 +5817,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"dirs 6.0.0",
"dunce",
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.2"
version = "0.1.3"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+20
Переглянути файл
@@ -17,6 +17,26 @@ its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages.
## Benchmark
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
with warm caches, median of 5 runs:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|---|---|---|
| Window with the project | **0.9 s** | 3.1 s |
| Ready (CPU settled) | **1.1 s** | 13.2 s |
| Memory (USS, all processes) | **169 MB** | 2011 MB |
| CPU time until ready | **2.4 s** | 47.9 s |
| Idle CPU | **4 %** of a core | 7 % of a core |
| Quit | **0.3 s** | 5.9 s |
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
Windows 11, 32-core AMD, 62 GB RAM.
IDEA analyses Python more deeply, so "ready" doesn't mean the same work on
both sides. Both are measured from the outside, the same way: see
[`perf/compare`](perf/compare) to run it on your machine and projects.
## Build
```sh
+106
Переглянути файл
@@ -0,0 +1,106 @@
//! "Ignored Files and Folders" (IDEA: Settings › File Types): file names the IDE
//! treats as nonexistent — hidden from the project view and navigation, never
//! indexed or searched, never offered as unversioned changes.
/// IDEA's default list, plus `.jj` and the Windows shell files.
pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
"*.pyc",
"*.pyo",
"*.rbc",
"*.yarb",
"*~",
".DS_Store",
".git",
".hg",
".jj",
".svn",
"CVS",
"__pycache__",
"_svn",
"vssver.scc",
"vssver2.scc",
"Thumbs.db",
"desktop.ini",
];
/// Matches single path segments against name patterns (`*` and `?` wildcards).
#[derive(Clone, Debug, Default)]
pub struct IgnoredNames {
exact: Vec<String>,
wildcards: Vec<String>,
}
impl IgnoredNames {
pub fn new(patterns: &[String]) -> Self {
let mut out = Self::default();
for p in patterns.iter().map(|p| p.trim()).filter(|p| !p.is_empty() && !p.contains('/')) {
if p.contains(['*', '?']) {
out.wildcards.push(p.to_owned());
} else {
out.exact.push(p.to_owned());
}
}
out
}
pub fn is_ignored_name(&self, name: &str) -> bool {
self.exact.iter().any(|e| e == name) || self.wildcards.iter().any(|w| wildcard(w.as_bytes(), name.as_bytes()))
}
/// Whether any segment of a `/`-separated relative path is ignored.
pub fn is_ignored_path(&self, rel: &str) -> bool {
rel.split('/').any(|seg| !seg.is_empty() && self.is_ignored_name(seg))
}
}
fn wildcard(p: &[u8], s: &[u8]) -> bool {
let (mut pi, mut si, mut star, mut mark) = (0, 0, None, 0);
while si < s.len() {
if pi < p.len() && (p[pi] == b'?' || p[pi] == s[si]) {
pi += 1;
si += 1;
} else if pi < p.len() && p[pi] == b'*' {
star = Some(pi);
pi += 1;
mark = si;
} else if let Some(st) = star {
pi = st + 1;
mark += 1;
si = mark;
} else {
return false;
}
}
p[pi..].iter().all(|&c| c == b'*')
}
#[cfg(test)]
mod tests {
use super::*;
fn defaults() -> IgnoredNames {
IgnoredNames::new(&DEFAULT_IGNORED_NAMES.iter().map(|s| s.to_string()).collect::<Vec<_>>())
}
#[test]
fn matches_names_and_wildcards() {
let m = defaults();
for name in [".DS_Store", "__pycache__", "a.pyc", "notes.txt~", "Thumbs.db"] {
assert!(m.is_ignored_name(name), "{name}");
}
for name in ["DS_Store", "a.py", "pyc", "src", ".gitignore"] {
assert!(!m.is_ignored_name(name), "{name}");
}
assert!(wildcard(b"a?c*", b"abcdef"));
assert!(!wildcard(b"a?c", b"abcd"));
}
#[test]
fn matches_any_path_segment() {
let m = defaults();
assert!(m.is_ignored_path("src/.DS_Store"));
assert!(m.is_ignored_path("pkg/__pycache__/"));
assert!(m.is_ignored_path("pkg/__pycache__/mod.cpython-312.pyc"));
assert!(!m.is_ignored_path("src/main.rs"));
}
}
+1
Переглянути файл
@@ -8,6 +8,7 @@ pub mod editor_settings;
pub mod error;
pub mod event;
pub mod ids;
pub mod ignored;
pub mod ipc_path;
pub mod project_dir;
pub mod settings;
+16 -2
Переглянути файл
@@ -303,6 +303,8 @@ pub struct FileSettings {
/// Save on focus loss / tab switch, like IDEA.
pub auto_save: bool,
pub exclude: Vec<String>,
/// Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`].
pub ignored_names: Vec<String>,
pub trim_trailing_whitespace: bool,
pub ensure_final_newline: bool,
/// Local History keeps changes from this many working days (days with changes), like IDEA.
@@ -316,6 +318,7 @@ impl Default for FileSettings {
Self {
auto_save: true,
exclude: vec!["**/.git".into(), "**/node_modules".into(), "**/target".into()],
ignored_names: crate::ignored::DEFAULT_IGNORED_NAMES.iter().map(|s| (*s).into()).collect(),
trim_trailing_whitespace: true,
ensure_final_newline: true,
local_history_days: 5,
@@ -423,9 +426,9 @@ pub struct ProjectStructureSettings {
}
impl Settings {
/// `files.exclude` plus the Project Structure excluded folders as globs.
/// `files.exclude`, the ignored names and the Project Structure excluded folders as globs.
pub fn exclude_globs(&self) -> Vec<String> {
let mut out = self.files.exclude.clone();
let mut out = self.file_excludes();
for dir in &self.project_structure.excluded {
let dir = dir.trim().trim_matches('/');
if !dir.is_empty() {
@@ -434,6 +437,17 @@ impl Settings {
}
out
}
/// `files.exclude` plus `files.ignoredNames` (a bare name matches at any depth).
pub fn file_excludes(&self) -> Vec<String> {
let mut out = self.files.exclude.clone();
out.extend(self.files.ignored_names.iter().filter(|n| !n.trim().is_empty()).cloned());
out
}
pub fn ignored_names(&self) -> crate::ignored::IgnoredNames {
crate::ignored::IgnoredNames::new(&self.files.ignored_names)
}
}
#[cfg(test)]
+2 -2
Переглянути файл
@@ -9,8 +9,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::UNIX_EPOCH;
/// VCS metadata directories are never indexed.
const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj", ".DS_Store"];
/// VCS metadata directories are never indexed, whatever the ignored names say.
const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj"];
pub(crate) struct PathFilter {
root: PathBuf,
+1
Переглянути файл
@@ -15,6 +15,7 @@ serde_json.workspace = true
specta.workspace = true
toml.workspace = true
tracing.workspace = true
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
[dev-dependencies]
tempfile.workspace = true
+140 -23
Переглянути файл
@@ -126,23 +126,101 @@ pub fn installed_jdks() -> Arc<[Jdk]> {
}
}
/// Like [`installed_jdks`], but while none can run jdtls the list is rescanned
/// (at most every [`RESCAN_AFTER`]), so a JDK installed after startup is picked
/// up when the server is restarted.
pub fn jdtls_jdks() -> Arc<[Jdk]> {
/// Like [`installed_jdks`], but while none can run jdtls (on Java `min_java`)
/// the list is rescanned (at most every [`RESCAN_AFTER`]), so a JDK installed
/// after startup is picked up when the server is restarted.
pub fn jdtls_jdks(min_java: u32) -> Arc<[Jdk]> {
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
match &*slot {
Some(s) if jdtls_runtime(&s.jdks).is_some() || s.at.elapsed() < RESCAN_AFTER => s.jdks.clone(),
Some(s) if jdtls_runtime(&s.jdks, min_java).is_some() || s.at.elapsed() < RESCAN_AFTER => s.jdks.clone(),
_ => rescan(&mut slot),
}
}
/// Oldest Java version jdtls itself runs on (projects may target older ones).
/// Oldest Java version jdtls runs on when its install can't tell (its launcher's check).
pub const JDTLS_MIN_JAVA: u32 = 21;
/// The JDK to run jdtls with: the first found that is new enough (`JAVA_HOME` wins).
pub fn jdtls_runtime(jdks: &[Jdk]) -> Option<&Jdk> {
jdks.iter().find(|j| j.major >= JDTLS_MIN_JAVA)
pub fn jdtls_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> {
jdks.iter().find(|j| j.major >= min_java)
}
/// The Java version the jdtls that `cfg` launches needs: the highest any of its
/// bundles requires, never below [`JDTLS_MIN_JAVA`]. Its launcher only checks
/// for 21, but the Eclipse platform it ships moves on (1.63 needs 25), and on
/// an older JDK the server dies resolving its bundles.
pub fn jdtls_min_java(cfg: &LanguageServerConfig) -> u32 {
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
let required = search
.and_then(|s| ide_run::which::find_executable(&cfg.command, &s))
.and_then(|exe| dunce::canonicalize(exe).ok())
.and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
.and_then(|home| bundles_min_java(&home));
required.map_or(JDTLS_MIN_JAVA, |v| v.max(JDTLS_MIN_JAVA))
}
/// Per install: (plugins directory mtime, its requirement).
static BUNDLE_JAVA: Mutex<BTreeMap<PathBuf, (std::time::SystemTime, Option<u32>)>> = Mutex::new(BTreeMap::new());
/// Highest Java version required by the bundles in `home`'s `plugins` (or Homebrew's
/// `libexec/plugins`); `None` when there are none to read.
fn bundles_min_java(home: &Path) -> Option<u32> {
let plugins = [home.join("plugins"), home.join("libexec").join("plugins")].into_iter().find(|p| p.is_dir())?;
let modified = std::fs::metadata(&plugins).and_then(|m| m.modified()).ok()?;
let mut cache = BUNDLE_JAVA.lock().unwrap_or_else(|e| e.into_inner());
if let Some((at, v)) = cache.get(&plugins)
&& *at == modified
{
return *v;
}
let required = std::fs::read_dir(&plugins)
.ok()?
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "jar"))
.filter_map(|jar| jar_manifest(&jar))
.filter_map(|manifest| manifest_min_java(&manifest))
.max();
cache.insert(plugins, (modified, required));
required
}
fn jar_manifest(jar: &Path) -> Option<String> {
use std::io::Read;
let mut zip = zip::ZipArchive::new(std::fs::File::open(jar).ok()?).ok()?;
let mut entry = zip.by_name("META-INF/MANIFEST.MF").ok()?;
let mut text = String::new();
entry.read_to_string(&mut text).ok()?;
Some(text)
}
/// The Java version an OSGi bundle manifest requires: its `osgi.ee` capability
/// (`version=25`), else the oldest of its `Bundle-RequiredExecutionEnvironment`s.
fn manifest_min_java(manifest: &str) -> Option<u32> {
// Long headers continue on lines starting with a space.
let mut headers: Vec<String> = Vec::new();
for line in manifest.lines() {
match (line.strip_prefix(' '), headers.last_mut()) {
(Some(rest), Some(last)) => last.push_str(rest),
_ => headers.push(line.to_owned()),
}
}
let header = |name: &str| headers.iter().find_map(|h| h.strip_prefix(name)?.strip_prefix(':')).map(str::trim);
if let Some(caps) = header("Require-Capability") {
let ee = caps.split(',').filter(|c| c.trim_start().starts_with("osgi.ee")).find_map(|c| {
let v = c.split("version=").nth(1)?;
let digits: String = v.chars().take_while(char::is_ascii_digit).collect();
digits.parse::<u32>().ok()
});
if ee.is_some() {
return ee;
}
}
header("Bundle-RequiredExecutionEnvironment")?
.split(',')
.filter_map(|ee| ee.trim().strip_prefix("JavaSE-"))
.filter_map(|v| if v == "1.8" { Some(8) } else { v.parse().ok() })
.min()
}
/// jdtls `java.configuration.runtimes`: one JDK per Java version (the first
@@ -178,14 +256,15 @@ const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot
/// jdtls: its Eclipse workspace (`-data`) lives under the IDE's data
/// directory, one per server root, and no Eclipse metadata is written into
/// the project; it runs on a JDK 21+ (via `JAVA_HOME`, which its launcher
/// reads), installed JDKs are registered as runtimes and `bundles` (e.g. the
/// java-debug plugin jar) are loaded into the server.
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
/// launcher reads), installed JDKs are registered as runtimes and `bundles`
/// (e.g. the java-debug plugin jar) are loaded into the server.
pub fn configure_jdtls(
cfg: &mut LanguageServerConfig,
server_root: &Path,
data_dir: &Path,
jdks: &[Jdk],
min_java: u32,
bundles: &[PathBuf],
) {
if cfg.name != "jdtls" {
@@ -201,11 +280,11 @@ pub fn configure_jdtls(
cfg.args.push(format!("--jvm-arg=-D{METADATA_PROPERTY}=false"));
}
if !cfg.env.contains_key("JAVA_HOME") {
match jdtls_runtime(jdks) {
match jdtls_runtime(jdks, min_java) {
Some(jdk) => {
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
}
None => cfg.launch_error = Some(missing_runtime_message(jdks)),
None => cfg.launch_error = Some(missing_runtime_message(jdks, min_java)),
}
}
let runtimes = runtimes(jdks);
@@ -218,7 +297,7 @@ pub fn configure_jdtls(
}
}
fn missing_runtime_message(jdks: &[Jdk]) -> String {
fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
let mut found: Vec<u32> = jdks.iter().map(|j| j.major).collect();
found.sort_unstable();
found.dedup();
@@ -229,7 +308,7 @@ fn missing_runtime_message(jdks: &[Jdk]) -> String {
format!("found JDK {}", list.join(", "))
};
format!(
"jdtls needs JDK {JDTLS_MIN_JAVA} or newer to run ({found}). Install one (or point JAVA_HOME at it) and \
"jdtls needs JDK {min_java} or newer to run ({found}). Install one (or point JAVA_HOME at it) and \
restart the server; the project can still target an older Java version."
)
}
@@ -330,7 +409,7 @@ mod tests {
Jdk { major: 8, home: PathBuf::from("/jdk8") },
];
let bundles = [PathBuf::from("/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar")];
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, &bundles);
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles);
assert_eq!(cfg.args[0], "-data");
assert!(cfg.args[1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[1]);
assert_eq!(cfg.args[2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
@@ -345,36 +424,74 @@ mod tests {
// Deterministic (reconfigure compares configs) and idempotent.
let before = cfg.clone();
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, &bundles);
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles);
assert_eq!(cfg, before);
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, &bundles);
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles);
assert!(other.args.is_empty() && other.initialization_options.is_none());
}
#[test]
fn jdtls_needs_a_jdk_21_to_run() {
fn jdtls_needs_a_new_enough_jdk_to_run() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, &[]);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, JDTLS_MIN_JAVA, &[]);
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], &[]);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[]);
assert!(cfg.launch_error.unwrap().contains("no JDK was found"));
// An explicit JAVA_HOME is the user's call.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), "/custom".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, &[]);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, JDTLS_MIN_JAVA, &[]);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
assert_eq!(jdtls_runtime(&mixed).unwrap().major, 21);
assert_eq!(jdtls_runtime(&mixed, 21).unwrap().major, 21);
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, 25, &[]);
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
}
#[test]
fn bundle_manifests_give_the_java_jdtls_needs() {
let ee = |m: &str| manifest_min_java(m);
assert_eq!(ee("Bundle-RequiredExecutionEnvironment: JavaSE-25\n"), Some(25));
assert_eq!(ee("Bundle-RequiredExecutionEnvironment: JavaSE-17, JavaSE-1.8\n"), Some(8));
// The capability wins, also when folded over continuation lines.
let folded = "Require-Capability: osgi.service;filter:=\"(x=1)\",osgi.ee;filter:=\"(&(osgi.ee=Ja\r\n \
vaSE)(version=21))\"\r\nBundle-RequiredExecutionEnvironment: JavaSE-17\r\n";
assert_eq!(ee(folded), Some(21));
assert_eq!(ee("Bundle-Name: x\n"), None);
let home = tempfile::tempdir().unwrap();
let plugins = home.path().join("plugins");
std::fs::create_dir(&plugins).unwrap();
let jar = |name: &str, manifest: &str| {
let mut zip = zip::ZipWriter::new(std::fs::File::create(plugins.join(name)).unwrap());
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
zip.start_file("META-INF/MANIFEST.MF", opts).unwrap();
std::io::Write::write_all(&mut zip, manifest.as_bytes()).unwrap();
zip.finish().unwrap();
};
jar(
"org.eclipse.jdt.ls.core_1.63.0.jar",
"Require-Capability: osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=21))\"\n",
);
jar("org.eclipse.core.filesystem_1.12.0.jar", "Bundle-RequiredExecutionEnvironment: JavaSE-25\n");
jar("plain.jar", "Manifest-Version: 1.0\n");
std::fs::write(plugins.join("notes.txt"), "not a jar").unwrap();
assert_eq!(bundles_min_java(home.path()), Some(25));
assert_eq!(bundles_min_java(&home.path().join("missing")), None);
}
#[test]
+1 -1
Переглянути файл
@@ -174,7 +174,7 @@ fn excluded_folders_become_anchored_globs() {
s.project_structure.excluded = vec!["build/".into(), " ".into()];
let globs = s.exclude_globs();
assert!(globs.contains(&"/build".to_owned()));
assert_eq!(globs.len(), s.files.exclude.len() + 1);
assert_eq!(globs.len(), s.file_excludes().len() + 1);
}
/// Prints what this machine has installed.
+6
Переглянути файл
@@ -2,6 +2,7 @@
//! writes (commit, checkout, push/pull, stash, merge) shell out to `git` so
//! hooks, credentials and signing behave exactly as on the command line.
use ide_core::ignored::IgnoredNames;
use ide_core::{CancellationToken, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -283,6 +284,7 @@ pub struct Repo {
root: PathBuf,
git_dir: PathBuf,
inner: std::sync::Mutex<repo::Cache>,
ignored: std::sync::RwLock<IgnoredNames>,
}
impl Repo {
@@ -294,6 +296,10 @@ impl Repo {
pub fn root(&self) -> &Path {
&self.root
}
/// Untracked files with one of these names (or under such a folder) are not reported.
pub fn set_ignored_names(&self, names: IgnoredNames) {
*self.ignored.write().unwrap_or_else(|p| p.into_inner()) = names;
}
/// Staged (HEAD↔index) and unstaged (index↔worktree, incl. untracked) changes,
/// sorted by path. Conflicted files report `unstaged: Conflicted` and no staged kind.
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let common_dir = absolute(repo.common_dir())?;
let files = config_files(&git_dir, &common_dir);
let cache = Cache { config_stamp: stamp(&files), config_files: files, repo: ts };
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache) }))
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache), ignored: Default::default() }))
}
fn absolute(p: &Path) -> IdeResult<PathBuf> {
+7
Переглянути файл
@@ -18,6 +18,7 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
let repo = r.gix()?;
let mut map: BTreeMap<String, Entry> = BTreeMap::new();
let mut conflicts: HashSet<String> = HashSet::new();
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
let platform = repo
.status(gix::progress::Discard)
@@ -50,6 +51,9 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
continue;
}
let mut path = to_string(entry.rela_path.as_ref());
if ignored.is_ignored_path(&path) {
continue;
}
if entry.disk_kind.is_some_and(|k| k.is_dir()) && !path.ends_with('/') {
path.push('/');
}
@@ -87,7 +91,10 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
}
}
// Persist refreshed stat info so the next status is cheaper (like `git status` does).
// Only when something changed: `write_changes` writes even an empty change set, and
// the rewritten `.git/index` comes back as a VCS change that triggers the next status.
if let Some(mut outcome) = iter.into_outcome()
&& outcome.has_changes()
&& let Some(Err(e)) = outcome.write_changes()
{
tracing::debug!("could not write refreshed index: {e}");
+25
Переглянути файл
@@ -145,6 +145,26 @@ fn repository_without_commits() {
assert!(repo.status().unwrap().is_empty());
}
#[test]
fn status_leaves_an_up_to_date_index_alone() {
// The watcher reports `.git/index` writes as VCS changes, which refresh the
// status: rewriting it unconditionally made that a loop.
let fx = Fixture::new();
fx.write("a.txt", "a\n");
// Older than the index, so it isn't racily clean (that settles after a write or two).
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
std::fs::File::options().write(true).open(fx.path("a.txt")).unwrap().set_modified(past).unwrap();
fx.commit_all("init");
let repo = fx.repo();
repo.status().unwrap(); // may persist refreshed stat info once
let index = fx.path(".git/index");
let before = std::fs::metadata(&index).unwrap().modified().unwrap();
for _ in 0..3 {
assert!(repo.status().unwrap().is_empty());
}
assert_eq!(std::fs::metadata(&index).unwrap().modified().unwrap(), before);
}
#[test]
fn status_matrix() {
let fx = Fixture::new();
@@ -172,8 +192,12 @@ fn status_matrix() {
fx.write("dir/nested/untracked2.txt", "u\n");
fx.write("debug.log", "ignored\n");
fx.write("build/out.bin", "ignored\n");
fx.write(".DS_Store", "junk");
fx.write("dir/.DS_Store", "junk");
fx.write("pkg/__pycache__/m.pyc", "junk");
let repo = fx.repo();
repo.set_ignored_names(ide_core::settings::Settings::default().ignored_names());
let st = repo.status().unwrap();
let check = |rel: &str, staged: Option<ChangeKind>, unstaged: Option<ChangeKind>| {
let s = status_of(&st, rel);
@@ -193,6 +217,7 @@ fn status_matrix() {
assert_eq!(status_of(&st, "renamed.txt").renamed_from.as_deref(), Some("rename_me.txt"));
assert!(!st.iter().any(|s| s.rel_path == "rename_me.txt"), "rename source listed: {st:#?}");
assert!(!st.iter().any(|s| s.rel_path.contains("debug.log") || s.rel_path.contains("build")));
assert!(!st.iter().any(|s| s.rel_path.contains(".DS_Store") || s.rel_path.contains("pkg")), "{st:#?}");
// Sorted by path.
let paths: Vec<_> = st.iter().map(|s| s.rel_path.clone()).collect();
let mut sorted = paths.clone();
+3
Переглянути файл
@@ -0,0 +1,3 @@
# Per-user IDE state
/shelf/
/changelists.json
+52
Переглянути файл
@@ -5,9 +5,61 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenIDEA</title>
<script src="/boot.js"></script>
<style>
/* Start-up splash over the page until the window's launch project is open (platform/splash.ts).
Tokens aren't loaded yet, so the colours mirror --bg-frame / --fg-muted / --accent. */
html, body, .splash { background: #e9eaee; }
:root[data-theme="dark"] :is(body, .splash) { background: #26282c; }
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) { background: #1a1b1e; }
.splash {
position: fixed;
inset: 0;
z-index: 2147483647;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14px;
padding-bottom: 38px;
box-sizing: border-box;
font: 500 15px/1.2 "Inter Variable", Inter, system-ui, -apple-system, sans-serif;
color: #6c707e;
-webkit-user-select: none;
user-select: none;
cursor: default;
animation: splash-in 240ms ease-out 120ms both;
transition: opacity 160ms ease-out;
}
.splash.splash-out { opacity: 0; pointer-events: none; }
:root[data-theme^="dark"] .splash { color: #8c8f95; }
.splash svg { width: 56px; height: 56px; }
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
.splash-bar::after {
content: "";
display: block;
width: 40%;
height: 100%;
background: #3871e1;
animation: splash-bar 1.1s ease-in-out infinite;
}
@keyframes splash-in { from { opacity: 0; } }
@keyframes splash-bar { from { transform: translateX(-100%); } to { transform: translateX(250%); } }
@media (prefers-reduced-motion: reduce) {
.splash, .splash-bar::after { animation: none; }
}
</style>
</head>
<body>
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg viewBox="0 0 64 64" aria-hidden="true">
<rect width="64" height="64" rx="15" fill="#0E0E10" />
<circle cx="26" cy="32" r="11" fill="none" stroke="#FFFFFF" stroke-width="8" />
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
</svg>
<span>OpenIDEA</span>
<div class="splash-bar" role="progressbar" aria-label="Loading"></div>
</div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.2",
"version": "0.1.3",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+2
Переглянути файл
@@ -0,0 +1,2 @@
results/
__pycache__/
+51
Переглянути файл
@@ -0,0 +1,51 @@
# IDE comparison
`pnpm perf` measures OpenIDEA from inside its webview. This measures any IDE
from the outside, the same way for each, so OpenIDEA can be compared with
IntelliJ IDEA (or anything else listed in `apps.toml`).
```sh
pip install -r perf/compare/requirements.txt
python perf/compare/bench.py ~/src/spring-petclinic --runs 10
python perf/compare/bench.py ~/src/spring-petclinic --runs 5 --wipe-caches # cold index
```
Each run launches the app on the project, waits until it is ready, idles,
closes it, and records:
| Metric | How |
|---|---|
| `window_s` | first visible window whose title matches `window_title` (the project name) |
| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
| `exit_s` | until every process has exited |
| `cache_mb`, install size | `cache_dirs`, `install_dir` |
Apps run interleaved, rotating the order, after `--warmup` discarded runs.
Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
`results.json`, and each run's stdout.
## Fair runs
- Release builds only; a running instance of the same executable (a
`pnpm tauri dev` build too) would take over the launch, so the script refuses.
- IDEA: open the project once by hand and trust it; turn off *Reopen projects
on startup* and *Confirm before exiting*; note the version, `-Xmx` and whether
Shared Indexes were on.
- Same machine, power plan and plugged in; exclude the project and caches from
antivirus scanning, or neither.
- `--drop-os-cache` runs a command before each launch for a cold OS cache:
`sync; echo 3 | sudo tee /proc/sys/vm/drop_caches` (Linux), `sudo purge`
(macOS), `RAMMap64.exe -Et` (Windows, admin).
- Typing latency is not covered: measure it on screen with Typometer for both.
## Platform notes
- Windows: windows via `user32`, closed with `WM_CLOSE`.
- macOS: windows via Quartz (`pyobjc-framework-Quartz`; titles need Screen
Recording permission). WebKit helpers are children of launchd and are
attributed through `responsibility_get_pid_responsible_for_pid`.
- Linux: windows via `wmctrl` (X11). Without it `window_s` is skipped and
readiness counts from launch.
+43
Переглянути файл
@@ -0,0 +1,43 @@
# Apps compared by bench.py. Any value can be a { windows, macos, linux } table.
# Placeholders: {project} (absolute path), {project_name} (its directory name);
# ~ and environment variables are expanded.
#
# command executable, launched directly (not through a shell or `open`)
# args default ["{project}"]
# window_title regex; the first visible window whose title matches marks "window_s"
# logs globs of log files to watch, besides the app's stdout
# markers name → regex; the first and last matching log line time is recorded
# ready_after markers that must have appeared before "ready" can be declared
# cache_dirs globs deleted by --wipe-caches, and measured for "cache_mb"
# install_dir measured once for the install size
# quit_command instead of WM_CLOSE (Windows) / SIGTERM (macOS, Linux)
# daemons process names meant to outlive the app (not waited for or killed on exit)
# single_instance default true: refuse to start while a process with the same
# executable name runs (it would take over the launch)
[apps.openidea]
name = "OpenIDEA"
command = { windows = "%LOCALAPPDATA%/OpenIDEA/openidea.exe", macos = "/Applications/OpenIDEA.app/Contents/MacOS/openidea", linux = "/usr/bin/openidea" }
install_dir = { windows = "%LOCALAPPDATA%/OpenIDEA", macos = "/Applications/OpenIDEA.app" }
logs = { windows = "%LOCALAPPDATA%/ai.l0ng.openidea/logs/openidea*.log", macos = "~/Library/Logs/ai.l0ng.openidea/openidea*.log", linux = "~/.local/share/ai.l0ng.openidea/logs/openidea*.log" }
# The index and build caches. jdtls keeps its own workspace under lsp/jdtls,
# next to the jdtls install, so a cold Java run still reuses jdtls's build state.
cache_dirs = { windows = ["%APPDATA%/ai.l0ng.openidea/index", "%APPDATA%/ai.l0ng.openidea/cache"], macos = ["~/Library/Application Support/ai.l0ng.openidea/index", "~/Library/Application Support/ai.l0ng.openidea/cache"], linux = ["~/.local/share/ai.l0ng.openidea/index", "~/.local/share/ai.l0ng.openidea/cache"] }
[apps.openidea.markers]
project_opened = 'opened .* in window'
indexed = 'indexed \d+ files'
lsp_initialized = 'initialized: \{'
[apps.idea]
name = "IntelliJ IDEA"
command = { windows = "C:/Program Files/JetBrains/IntelliJ IDEA 2026.2.3/bin/idea64.exe", macos = "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea", linux = "~/idea/bin/idea" }
daemons = ["jetbrainsd.exe", "jetbrainsd"]
install_dir = { windows = "C:/Program Files/JetBrains/IntelliJ IDEA 2026.2.3", macos = "/Applications/IntelliJ IDEA.app", linux = "~/idea" }
logs = { windows = "%LOCALAPPDATA%/JetBrains/IntelliJIdea2026.2/log/idea.log", macos = "~/Library/Logs/JetBrains/IntelliJIdea2026.2/idea.log", linux = "~/.cache/JetBrains/IntelliJIdea2026.2/log/idea.log" }
# The VFS and the indexes (the whole "system" dir also holds logs and local history).
cache_dirs = { windows = ["%LOCALAPPDATA%/JetBrains/IntelliJIdea2026.2/caches", "%LOCALAPPDATA%/JetBrains/IntelliJIdea2026.2/index"], macos = ["~/Library/Caches/JetBrains/IntelliJIdea2026.2/caches", "~/Library/Caches/JetBrains/IntelliJIdea2026.2/index"], linux = ["~/.cache/JetBrains/IntelliJIdea2026.2/caches", "~/.cache/JetBrains/IntelliJIdea2026.2/index"] }
[apps.idea.markers]
# Indexing done: IDEA leaves dumb mode, possibly several times; compare "last".
smart = 'exit dumb mode \[{project_name}\]'
+614
Переглянути файл
@@ -0,0 +1,614 @@
#!/usr/bin/env python3
"""Black-box IDE comparison: startup, readiness, memory, idle CPU, disk.
Launches each app from apps.toml on the same project, measures it from the
outside (process tree, window list, log lines), closes it, and repeats with
the apps interleaved. Runs on Windows, macOS and Linux; see README.md.
"""
from __future__ import annotations
import argparse
import collections
import ctypes
import datetime as dt
import glob
import json
import os
import platform
import re
import shutil
import signal
import statistics
import subprocess
import sys
import time
import tomllib
from pathlib import Path
try:
import psutil
except ImportError:
sys.exit("psutil is required: pip install -r perf/compare/requirements.txt")
OS = {"Windows": "windows", "Darwin": "macos", "Linux": "linux"}[platform.system()]
HERE = Path(__file__).resolve().parent
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
GONE = (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied)
MB = 1024 * 1024
POLL_S = 0.2
# ── config ──────────────────────────────────────────────────────────────────
def per_os(value):
"""A value, or a {windows, macos, linux} table of per-platform values."""
if isinstance(value, dict) and value and value.keys() <= {"windows", "macos", "linux"}:
return value.get(OS)
return value
def as_list(value) -> list:
return [] if value is None else [value] if isinstance(value, str) else list(value)
def expand(s: str, project: Path) -> str:
s = s.replace("{project}", str(project)).replace("{project_name}", project.name)
return os.path.expandvars(os.path.expanduser(s))
def pattern(s: str, project: Path) -> re.Pattern:
return re.compile(s.replace("{project_name}", re.escape(project.name)))
class App:
def __init__(self, key: str, raw: dict, project: Path):
self.key = key
self.name = raw.get("name", key)
command = per_os(raw.get("command"))
if not command:
raise SystemExit(f"apps.{key}: no command for {OS}")
args = per_os(raw.get("args", ["{project}"]))
self.command = [expand(command, project), *(expand(a, project) for a in args)]
self.logs = [expand(g, project) for g in as_list(per_os(raw.get("logs")))]
self.markers = {k: pattern(v, project) for k, v in raw.get("markers", {}).items()}
self.ready_after = as_list(raw.get("ready_after"))
self.window_title = pattern(raw.get("window_title", "{project_name}"), project)
self.cache_dirs = [expand(d, project) for d in as_list(per_os(raw.get("cache_dirs")))]
self.install_dir = per_os(raw.get("install_dir"))
self.install_dir = expand(self.install_dir, project) if self.install_dir else None
self.quit_command = as_list(per_os(raw.get("quit_command")))
self.single_instance = raw.get("single_instance", True)
self.daemons = {n.lower() for n in as_list(raw.get("daemons"))}
unknown = set(self.ready_after) - self.markers.keys()
if unknown:
raise SystemExit(f"apps.{key}.ready_after names unknown markers: {sorted(unknown)}")
def cache_paths(self) -> list[Path]:
return [Path(p) for d in self.cache_dirs for p in sorted(glob.glob(d))]
# ── windows ─────────────────────────────────────────────────────────────────
if OS == "windows":
from ctypes import wintypes
_user32 = ctypes.WinDLL("user32")
_ENUM = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
_user32.EnumWindows.argtypes = [_ENUM, wintypes.LPARAM]
_user32.IsWindowVisible.argtypes = [wintypes.HWND]
_user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
_user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
_user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
_user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
def _win_windows(pids: set[int]) -> list[tuple[object, str]]:
found = []
def visit(hwnd, _):
if _user32.IsWindowVisible(hwnd):
pid = wintypes.DWORD()
_user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
if pid.value in pids:
buf = ctypes.create_unicode_buffer(_user32.GetWindowTextLengthW(hwnd) + 1)
_user32.GetWindowTextW(hwnd, buf, len(buf))
found.append((hwnd, buf.value))
return True
_user32.EnumWindows(_ENUM(visit), 0)
return found
def _mac_windows(pids: set[int]) -> list[tuple[object, str]] | None:
try:
import Quartz
except ImportError:
return None
infos = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID
)
# Titles need the Screen Recording permission; without it they come back empty.
return [
(None, str(w.get("kCGWindowName") or ""))
for w in infos
if w.get("kCGWindowOwnerPID") in pids and w.get("kCGWindowLayer") == 0
]
def _x11_windows(pids: set[int]) -> list[tuple[object, str]] | None:
if not shutil.which("wmctrl"):
return None
try:
out = subprocess.run(["wmctrl", "-lp"], capture_output=True, text=True, timeout=2).stdout
except (OSError, subprocess.TimeoutExpired):
return None
found = []
for line in out.splitlines():
parts = line.split(None, 4)
if len(parts) >= 4 and parts[2].isdigit() and int(parts[2]) in pids:
found.append((parts[0], parts[4] if len(parts) > 4 else ""))
return found
def visible_windows(pids: set[int]) -> list[tuple[object, str]] | None:
"""(handle, title) of the visible top-level windows owned by `pids`; None when this platform can't tell."""
if OS == "windows":
return _win_windows(pids)
if OS == "macos":
return _mac_windows(pids)
return _x11_windows(pids)
# ── process tree ────────────────────────────────────────────────────────────
_responsible = None
if OS == "macos":
try:
_responsible = ctypes.CDLL("/usr/lib/libSystem.B.dylib").responsibility_get_pid_responsible_for_pid
_responsible.argtypes = [ctypes.c_int]
_responsible.restype = ctypes.c_int
except (OSError, AttributeError):
_responsible = None
class Tree:
"""Every process the app started, including ones whose parent already exited.
On macOS, WKWebView's helper processes are children of launchd, so they are
attributed through the responsible-pid API (or, failing that, by name and
start time).
"""
def __init__(self, root: psutil.Process, started: float):
self.root = root
self.started = started
self.procs: dict[tuple[int, float], psutil.Process] = {}
self.cpu: dict[tuple[int, float], float] = {}
self.cpu_exited = 0.0
def _discover(self):
found = [self.root]
for p in list(self.procs.values()):
try:
found += p.children(recursive=True)
except GONE:
pass
if OS == "macos":
found += self._webkit()
for p in found:
try:
self.procs.setdefault((p.pid, p.create_time()), p)
except GONE:
pass
def _webkit(self) -> list[psutil.Process]:
out = []
for p in psutil.process_iter(["name", "create_time"]):
if not (p.info["name"] or "").startswith("com.apple.WebKit"):
continue
if _responsible:
if _responsible(p.pid) == self.root.pid:
out.append(p)
elif (p.info["create_time"] or 0) >= self.started - 1:
out.append(p)
return out
def sample(self) -> tuple[float, int]:
"""(total CPU seconds ever used by the tree, current summed RSS bytes)."""
self._discover()
rss = 0
for key, p in list(self.procs.items()):
try:
with p.oneshot():
t = p.cpu_times()
self.cpu[key] = t.user + t.system
rss += p.memory_info().rss
except GONE:
self.cpu_exited += self.cpu.pop(key, 0.0)
del self.procs[key]
return self.cpu_exited + sum(self.cpu.values()), rss
def pids(self) -> set[int]:
return {pid for pid, _ in self.procs}
def alive(self) -> list[psutil.Process]:
return [p for p in self.procs.values() if p.is_running()]
def memory(self) -> dict:
"""Summed memory of the live tree. RSS double-counts shared pages, USS leaves them out."""
rss = uss = pss = 0
by_name: dict[str, int] = collections.Counter()
count = 0
for p in self.alive():
try:
full = p.memory_full_info()
except GONE:
continue
count += 1
rss += full.rss
uss += full.uss
pss += getattr(full, "pss", 0)
by_name[p.name()] += full.uss
out = {"rss_mb": rss / MB, "uss_mb": uss / MB, "procs": count}
if OS == "linux":
out["pss_mb"] = pss / MB
out["uss_by_process_mb"] = {k: round(v / MB, 1) for k, v in by_name.most_common()}
return out
# ── logs ────────────────────────────────────────────────────────────────────
class LogTail:
"""New lines appended to the files matching some globs since construction."""
def __init__(self, globs: list[str], extra: list[Path]):
self.globs = globs
self.extra = extra
self.offsets: dict[str, int] = {}
self.partial: dict[str, str] = {}
for path in self._paths():
self.offsets[path] = os.path.getsize(path)
def _paths(self) -> list[str]:
paths = [p for g in self.globs for p in glob.glob(g)]
return paths + [str(p) for p in self.extra if p.exists()]
def lines(self) -> list[str]:
out = []
for path in self._paths():
try:
with open(path, "rb") as f:
f.seek(self.offsets.get(path, 0))
chunk = f.read()
self.offsets[path] = f.tell()
except OSError:
continue
if not chunk:
continue
text = self.partial.pop(path, "") + chunk.decode("utf-8", "replace")
*complete, rest = text.split("\n")
if rest:
self.partial[path] = rest
out += [ANSI.sub("", line) for line in complete]
return out
# ── one run ─────────────────────────────────────────────────────────────────
def running_instances(app: App) -> list[psutil.Process]:
"""Processes with the app's executable name, from any install or build: a
single-instance app hands the launch to them even when the paths differ."""
name = os.path.normcase(Path(app.command[0]).name)
return [p for p in psutil.process_iter(["name"]) if os.path.normcase(p.info["name"] or "") == name]
def dir_size(path: Path) -> int:
if path.is_file():
return path.stat().st_size
total = 0
for root, _, files in os.walk(path):
for f in files:
try:
total += os.lstat(os.path.join(root, f)).st_size
except OSError:
pass
return total
def close(app: App, tree: Tree, proc: subprocess.Popen, timeout: float) -> tuple[float | None, list[str]]:
"""Asks the app to quit, waits for the whole tree, kills what's left.
Returns (seconds until every process exited, or None if it had to kill; names of killed leftovers).
"""
t0 = time.perf_counter()
if app.quit_command:
subprocess.run(app.quit_command, check=False)
elif OS == "windows":
# Only the project windows: closing a framework's hidden message windows
# (Tauri's single-instance and event-target ones) stalls the real shutdown.
for hwnd, title in _win_windows(tree.pids()):
if app.window_title.search(title):
_user32.PostMessageW(hwnd, 0x0010, 0, 0) # WM_CLOSE
else:
proc.send_signal(signal.SIGTERM)
def remaining() -> list[psutil.Process]:
out = []
for p in tree.alive():
try:
if p.name().lower() not in app.daemons:
out.append(p)
except GONE:
pass
return out
while time.perf_counter() - t0 < timeout:
tree.sample()
if not remaining():
return time.perf_counter() - t0, []
time.sleep(POLL_S)
leftovers = remaining()
names = []
for p in leftovers:
try:
names.append(p.name())
p.kill()
except GONE:
pass
psutil.wait_procs(leftovers, timeout=10)
return None, names
def run_once(app: App, args, out_dir: Path, label: str) -> dict:
running = running_instances(app) if app.single_instance else []
if running:
pids = ", ".join(str(p.pid) for p in running)
raise SystemExit(f"{app.name} is already running (pid {pids}); close it first, it would take over the launch.")
if args.wipe_caches:
for path in app.cache_paths():
shutil.rmtree(path, ignore_errors=True) if path.is_dir() else path.unlink(missing_ok=True)
if args.drop_os_cache:
subprocess.run(args.drop_os_cache, shell=True, check=True)
if args.cooldown:
time.sleep(args.cooldown)
stdout_path = out_dir / f"{label}.stdout.log"
tail = LogTail(app.logs, [stdout_path])
started_wall = time.time()
with open(stdout_path, "wb") as stdout:
t0 = time.perf_counter()
proc = subprocess.Popen(app.command, stdout=stdout, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
tree = Tree(psutil.Process(proc.pid), started_wall)
result: dict = {"app": app.key, "label": label, "markers_first_s": {}, "markers_last_s": {}}
window_supported = True
window_s = None
history: collections.deque[tuple[float, float]] = collections.deque()
peak_rss = 0
ready_s = None
while True:
now = time.perf_counter() - t0
cpu, rss = tree.sample()
peak_rss = max(peak_rss, rss)
history.append((now, cpu))
while history and now - history[0][0] > args.quiet_secs:
history.popleft()
for line in tail.lines():
for name, rx in app.markers.items():
if rx.search(line):
result["markers_first_s"].setdefault(name, now)
result["markers_last_s"][name] = now
if window_s is None and window_supported:
windows = visible_windows(tree.pids())
if windows is None:
window_supported = False
elif any(app.window_title.search(title) for _, title in windows):
window_s = now
if not tree.alive():
raise SystemExit(
f"{app.name} exited during startup (code {proc.poll()}); an instance started elsewhere may have "
f"taken the launch. Output: {stdout_path}"
)
waited = (window_s is not None or not window_supported) and all(
m in result["markers_first_s"] for m in app.ready_after
)
span = now - history[0][0]
if waited and span >= args.quiet_secs * 0.95:
busy = (cpu - history[0][1]) / span
if busy < args.quiet_cores:
# Never before what it waited for (the quiet span can start earlier).
ready_s = max(now - span, window_s or 0, *(result["markers_first_s"][m] for m in app.ready_after))
break
if now > args.timeout:
result["timed_out"] = True
break
time.sleep(POLL_S)
result["window_s"] = window_s
result["ready_s"] = ready_s
result["peak_rss_mb"] = peak_rss / MB
# Idle: what it costs to just sit there with the project open.
idle_cpu0, _ = tree.sample()
i0 = time.perf_counter()
while time.perf_counter() - i0 < args.idle_secs:
time.sleep(POLL_S * 5)
_, rss = tree.sample()
peak_rss = max(peak_rss, rss)
idle_cpu1, _ = tree.sample()
result["idle_cpu_pct"] = 100 * (idle_cpu1 - idle_cpu0) / (time.perf_counter() - i0)
result["peak_rss_mb"] = peak_rss / MB
result.update(tree.memory())
result["total_cpu_s"] = idle_cpu0
exit_s, killed = close(app, tree, proc, args.close_timeout)
result["exit_s"] = exit_s
if killed:
result["killed_on_exit"] = killed
result["cache_mb"] = sum(dir_size(p) for p in app.cache_paths()) / MB
return result
# ── report ──────────────────────────────────────────────────────────────────
METRICS = [
("window_s", "Window with project title (s)"),
("ready_s", "Ready: CPU settled (s)"),
("peak_rss_mb", "Peak RSS, startup + idle (MB)"),
("rss_mb", "RSS after idle (MB)"),
("uss_mb", "USS after idle (MB)"),
("pss_mb", "PSS after idle (MB)"),
("procs", "Processes"),
("total_cpu_s", "CPU used until ready (s)"),
("idle_cpu_pct", "Idle CPU (% of a core)"),
("exit_s", "Exit (s)"),
("cache_mb", "Cache dirs on disk (MB)"),
]
def fmt(value: float | None) -> str:
return "–" if value is None else f"{value:.2f}"
def summarize(values: list[float]) -> str:
if not values:
return "–"
med = statistics.median(values)
if len(values) == 1:
return f"{med:.2f}"
return f"{med:.2f} ({min(values):.2f}–{max(values):.2f})"
def report(apps: list[App], runs: list[dict], meta: dict) -> str:
def column(app: App, getter) -> str:
vals = [v for r in runs if r["app"] == app.key and (v := getter(r)) is not None]
return summarize(vals)
rows = [(title, lambda r, k=key: r.get(k)) for key, title in METRICS]
for app in apps:
for m in app.markers:
rows.append((f"{app.name}: log `{m}` first (s)", lambda r, m=m: r["markers_first_s"].get(m)))
rows.append((f"{app.name}: log `{m}` last (s)", lambda r, m=m: r["markers_last_s"].get(m)))
lines = [
f"# IDE benchmark: {meta['project']}",
"",
f"{meta['os']} · {meta['cpu']} · {meta['cores']} cores · {meta['ram_gb']:.0f} GB RAM · "
f"mode **{meta['mode']}** · {meta['runs']} runs · {meta['date']}",
"",
"Median (min–max). Times are seconds from launch.",
"",
"| Metric | " + " | ".join(a.name for a in apps) + " |",
"|---|" + "---|" * len(apps),
]
for title, getter in rows:
cells = [column(a, getter) for a in apps]
if any(c != "–" for c in cells):
lines.append(f"| {title} | " + " | ".join(cells) + " |")
for app in apps:
if app.install_dir and Path(app.install_dir).exists():
lines.append(f"\n{app.name} install size: {dir_size(Path(app.install_dir)) / MB:.0f} MB")
timeouts = [r["label"] for r in runs if r.get("timed_out")]
if timeouts:
lines.append(f"\n⚠ CPU never settled within the timeout: {', '.join(timeouts)}")
killed = [f"{r['label']}: {', '.join(r['killed_on_exit'])}" for r in runs if r.get("killed_on_exit")]
if killed:
lines.append("\n⚠ Killed after the exit timeout: " + "; ".join(killed))
return "\n".join(lines) + "\n"
# ── main ────────────────────────────────────────────────────────────────────
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("project", type=Path, help="project directory every app opens")
ap.add_argument("--config", type=Path, default=HERE / "apps.toml")
ap.add_argument("--apps", help="comma-separated keys from the config (default: all)")
ap.add_argument("--runs", type=int, default=5, help="measured runs per app (default 5)")
ap.add_argument("--warmup", type=int, default=1, help="discarded runs per app first (default 1)")
ap.add_argument("--wipe-caches", action="store_true", help="delete each app's cache_dirs before every run (cold index)")
ap.add_argument("--drop-os-cache", metavar="CMD", help="shell command run before every run to drop the OS file cache")
ap.add_argument("--quiet-secs", type=float, default=5, help="CPU must stay low this long to count as ready")
ap.add_argument("--quiet-cores", type=float, default=0.1, help="'low' = below this many cores busy (default 0.1)")
ap.add_argument("--idle-secs", type=float, default=30, help="idle period measured after ready")
ap.add_argument("--timeout", type=float, default=900, help="give up waiting for ready after this many seconds")
ap.add_argument("--close-timeout", type=float, default=60)
ap.add_argument("--cooldown", type=float, default=5, help="pause before each launch")
ap.add_argument("--out", type=Path, default=HERE / "results")
ap.add_argument("--yes", action="store_true", help="don't ask before wiping caches")
args = ap.parse_args()
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
project = args.project.resolve()
if not project.is_dir():
raise SystemExit(f"not a directory: {project}")
config = tomllib.loads(args.config.read_text(encoding="utf-8"))
keys = args.apps.split(",") if args.apps else list(config["apps"])
apps = [App(k, config["apps"][k], project) for k in keys]
if args.wipe_caches:
targets = [p for a in apps for p in a.cache_paths()]
for p in targets:
if len(p.resolve().parts) < 4 or p.resolve() == Path.home():
raise SystemExit(f"refusing to wipe a top-level path: {p}")
print("Before every run these will be deleted:\n " + "\n ".join(map(str, targets)))
if targets and not args.yes and input("Continue? [y/N] ").strip().lower() != "y":
return
stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
out_dir = args.out / f"{stamp}-{project.name}"
out_dir.mkdir(parents=True)
mode = "cold index" if args.wipe_caches else "warm"
if args.drop_os_cache:
mode += " + cold OS cache"
meta = {
"project": str(project),
"os": f"{platform.system()} {platform.release()}",
"cpu": platform.processor() or platform.machine(),
"cores": psutil.cpu_count(logical=True),
"ram_gb": psutil.virtual_memory().total / 1024**3,
"mode": mode,
"runs": args.runs,
"date": stamp,
"commands": {a.key: a.command for a in apps},
"args": {k: str(v) for k, v in vars(args).items()},
}
runs: list[dict] = []
total = args.warmup + args.runs
for i in range(total):
# Rotate the order so neither app always runs right after the other.
order = apps[i % len(apps) :] + apps[: i % len(apps)]
for app in order:
warm = i < args.warmup
label = f"{app.key}-{'warmup' if warm else 'run'}{i + 1 if warm else i - args.warmup + 1}"
print(f"[{label}] launching…", flush=True)
r = run_once(app, args, out_dir, label)
print(
f"[{label}] window {fmt(r['window_s'])} s · ready {fmt(r['ready_s'])} s · "
f"USS {r['uss_mb']:.0f} MB · idle CPU {r['idle_cpu_pct']:.1f}%",
flush=True,
)
if not warm:
runs.append(r)
(out_dir / "results.json").write_text(json.dumps({"meta": meta, "runs": runs}, indent=2), encoding="utf-8")
text = report(apps, runs, meta)
(out_dir / "report.md").write_text(text, encoding="utf-8")
print("\n" + text)
print(f"Raw results: {out_dir / 'results.json'}")
if __name__ == "__main__":
main()
+2
Переглянути файл
@@ -0,0 +1,2 @@
psutil>=6
pyobjc-framework-Quartz>=10; sys_platform == "darwin"
+2 -4
Переглянути файл
@@ -23,11 +23,9 @@ use std::time::Instant;
use tauri::ipc::Channel;
use tauri::{State, Window};
/// Files of `scope`, minus excluded roots.
/// Files of `scope`, minus excluded roots and ignored names.
fn files_in_scope(project: &Project, scope: &SearchScope, cancel: &CancellationToken) -> IdeResult<Vec<SourceFile>> {
let excluded: Vec<String> =
project.roots().excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))).collect();
let mask = FileMask::new(&[], &excluded)?;
let mask = FileMask::new(&[], &project.search_excludes())?;
Ok(ide_search::scope_files(&project.root, scope, &mask, None, cancel)?
.into_iter()
.map(|f| SourceFile { path: f.path, rel_path: f.rel_path })
+3 -2
Переглянути файл
@@ -29,9 +29,10 @@ pub async fn search_start(
on_event: Channel<SearchEvent>,
) -> IdeResult<()> {
let project = state.project(window.label())?;
// Excluded roots (Project Structure marks and detected `target`, `node_modules`, …) are never searched.
// Excluded roots (Project Structure marks and detected `target`, `node_modules`, …) and
// ignored names are never searched.
query.exclude.extend(project.search_excludes());
let roots = project.roots();
query.exclude.extend(roots.excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))));
let set = match query.scope {
ide_search::SearchScope::FileSet { set } => Some(set),
_ => None,
+6 -2
Переглянути файл
@@ -50,9 +50,12 @@ pub fn run() {
#[cfg(debug_assertions)]
export_bindings(&builder);
let app = tauri::Builder::default();
// Single instance first: a second launch focuses this one and opens its path argument.
let app = tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(windows::on_second_instance))
// Release only, so a dev build can run beside an installed release (same identifier).
#[cfg(not(debug_assertions))]
let app = app.plugin(tauri_plugin_single_instance::init(windows::on_second_instance));
let app = app
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.plugin(
@@ -84,6 +87,7 @@ pub fn run() {
app.manage(windows);
app.manage(menu_state);
app.on_menu_event(on_menu_event);
windows::create_main_window(app.handle())?;
Ok(())
})
.on_window_event(|window, event| match event {
+26 -6
Переглянути файл
@@ -246,8 +246,9 @@ impl AppState {
if cfg.name == "jdtls" {
let bundles: Vec<PathBuf> =
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
let jdks = ide_sdk::java::jdtls_jdks();
ide_sdk::java::configure_jdtls(cfg, server_root, &data_dir, &jdks, &bundles);
let min_java = ide_sdk::java::jdtls_min_java(cfg);
let jdks = ide_sdk::java::jdtls_jdks(min_java);
ide_sdk::java::configure_jdtls(cfg, server_root, &data_dir, &jdks, min_java, &bundles);
}
}));
}
@@ -375,9 +376,13 @@ impl AppState {
impl Project {
/// Runs `f` with the git repository, or fails when the project is not under git.
pub fn with_repo<T>(&self, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
crate::commands::vcs::apply_git_executable(&self.settings.effective());
let settings = self.settings.effective();
crate::commands::vcs::apply_git_executable(&settings);
match self.repo.lock().as_ref() {
Some(repo) => f(repo),
Some(repo) => {
repo.set_ignored_names(settings.ignored_names());
f(repo)
}
None => Err(IdeError::unavailable("project is not a git repository")),
}
}
@@ -435,7 +440,22 @@ impl Project {
self.cache_dir.join("build")
}
/// `files.exclude` plus the effective excluded roots (user-marked and detected).
/// File masks (`ide_search::FileMask`) for Find in Files and inspections: the
/// excluded roots and the ignored names (files, and everything under such folders).
pub fn search_excludes(&self) -> Vec<String> {
let mut out: Vec<String> =
self.roots().excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))).collect();
for name in &self.settings.effective().files.ignored_names {
let name = name.trim();
if !name.is_empty() && !name.contains(['/', ',']) {
out.push(name.to_owned());
out.push(format!("**/{name}/**"));
}
}
out
}
/// `files.exclude`, the ignored names and the effective excluded roots (user-marked and detected).
pub fn exclude_globs(&self) -> Vec<String> {
exclude_globs(&self.settings.effective(), &self.detected_roots.read())
}
@@ -508,7 +528,7 @@ pub fn history_retention(settings: &ide_core::settings::Settings) -> ide_workspa
}
fn exclude_globs(settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> Vec<String> {
let mut globs = settings.files.exclude.clone();
let mut globs = settings.file_excludes();
globs.extend(ProjectRoots::compute(detected.to_vec(), &settings.project_structure).excluded_globs());
globs
}
+71 -20
Переглянути файл
@@ -11,6 +11,7 @@
//! [`Launch::settings_page`] tells it which page to show.
use crate::state::AppState;
use ide_core::settings::AppearanceSettings;
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
@@ -18,7 +19,8 @@ use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::{AppHandle, Emitter, Manager, WebviewWindow, WebviewWindowBuilder};
use tauri::utils::config::{Color, WindowConfig};
use tauri::{AppHandle, Emitter, Manager, Theme, WebviewWindow, WebviewWindowBuilder};
/// Tells a window that a pending launch is waiting for it.
pub const LAUNCH_EVENT: &str = "openidea://launch";
@@ -195,19 +197,66 @@ pub fn target_window(app: &AppHandle) -> Option<WebviewWindow> {
sorted_labels(windows.keys().map(String::as_str)).first().and_then(|l| windows.get(l)).cloned()
}
/// Creates a new project window; `project` is opened by its frontend on load.
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
let windows = app.webview_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = app
.config()
fn window_config(app: &AppHandle) -> IdeResult<WindowConfig> {
app.config()
.app
.windows
.iter()
.find(|w| w.label == MAIN)
.or_else(|| app.config().app.windows.first())
.cloned()
.ok_or_else(|| IdeError::internal("no window configuration"))?;
.ok_or_else(|| IdeError::internal("no window configuration"))
}
/// The theme's `--bg-frame` (tokens.css), mirroring `resolveThemeId` in theme.ts.
pub fn frame_color(appearance: &AppearanceSettings, os_dark: bool) -> Color {
const LIGHT: Color = Color(0xe9, 0xea, 0xee, 0xff);
const DARK: Color = Color(0x26, 0x28, 0x2c, 0xff);
const DARK_HC: Color = Color(0x1a, 0x1b, 0x1e, 0xff);
let sync = appearance.sync_with_os || appearance.theme == "system";
let theme = match (sync, os_dark) {
(false, _) => &appearance.theme,
(true, true) => &appearance.preferred_dark_theme,
(true, false) => &appearance.preferred_light_theme,
};
match theme.as_str() {
"dark-hc" => DARK_HC,
"dark" => DARK,
"light" => LIGHT,
_ if sync && os_dark => DARK,
_ => LIGHT,
}
}
/// Builds a project window painted in the saved theme's frame colour, so it
/// doesn't flash the light default before its page (and splash) loads.
fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<WebviewWindow> {
let appearance = app.try_state::<AppState>().map(|s| s.global_settings.effective().appearance);
if let Some(a) = &appearance {
config.background_color = Some(frame_color(a, false));
}
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
// "Sync with OS" needs the OS mode, known once the window exists.
if let Some(a) = appearance.filter(|a| a.sync_with_os || a.theme == "system")
&& window.theme().is_ok_and(|t| t == Theme::Dark)
{
let _ = window.set_background_color(Some(frame_color(&a, true)));
}
Ok(window)
}
/// The first window (`create: false` in tauri.conf.json so it can take the theme's colour).
pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
build_project_window(app, window_config(app)?)
}
/// Creates a new project window; `project` is opened by its frontend on load.
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
let windows = app.webview_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = window_config(app)?;
config.label = label.clone();
if let Some(name) = project.as_deref().and_then(Path::file_name) {
config.title = name.to_string_lossy().into_owned();
@@ -223,9 +272,7 @@ pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<Web
config.center = false;
}
app.state::<WindowsState>().set_launch(&label, Launch { project: project.map(Into::into), settings_page: None });
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
let window = build_project_window(app, config)?;
focus(&window);
Ok(window)
}
@@ -300,6 +347,7 @@ pub fn open_path(app: &AppHandle, path: &Path) {
}
/// Second instance launched: focus this one and open its path argument.
#[cfg_attr(debug_assertions, allow(dead_code))]
pub fn on_second_instance(app: &AppHandle, args: Vec<String>, cwd: String) {
match cli_path(&args, Path::new(&cwd)) {
Some(path) => open_path(app, &path),
@@ -342,15 +390,7 @@ pub fn open_settings_window(
return Ok(());
}
let parent = app.get_webview_window(&parent_label).ok_or_else(|| IdeError::not_found("no parent window"))?;
let mut config = app
.config()
.app
.windows
.iter()
.find(|w| w.label == MAIN)
.or_else(|| app.config().app.windows.first())
.cloned()
.ok_or_else(|| IdeError::internal("no window configuration"))?;
let mut config = window_config(app)?;
config.label = label.clone();
config.title = "Settings".into();
// Frameless on Windows like project windows (tauri.windows.conf.json): the page draws
@@ -398,6 +438,17 @@ mod tests {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn frame_color_follows_theme_and_os_mode() {
let mut a = AppearanceSettings::default();
assert_eq!(frame_color(&a, true), Color(0xe9, 0xea, 0xee, 0xff));
a.theme = "dark-hc".into();
assert_eq!(frame_color(&a, false), Color(0x1a, 0x1b, 0x1e, 0xff));
a.sync_with_os = true;
assert_eq!(frame_color(&a, false), Color(0xe9, 0xea, 0xee, 0xff));
assert_eq!(frame_color(&a, true), Color(0x26, 0x28, 0x2c, 0xff));
}
#[test]
fn labels_sort_main_first_then_numerically() {
assert_eq!(
+2 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.2",
"version": "0.1.3",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -13,6 +13,7 @@
"windows": [
{
"label": "main",
"create": false,
"title": "OpenIDEA",
"width": 1440,
"height": 900,
+1
Переглянути файл
@@ -3,6 +3,7 @@
"windows": [
{
"label": "main",
"create": false,
"title": "OpenIDEA",
"width": 1440,
"height": 900,
+2
Переглянути файл
@@ -1854,6 +1854,8 @@ export type FileSettings = {
/** Save on focus loss / tab switch, like IDEA. */
autoSave?: boolean,
exclude?: string[],
/** Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`]. */
ignoredNames?: string[],
trimTrailingWhitespace?: boolean,
ensureFinalNewline?: boolean,
/** Local History keeps changes from this many working days (days with changes), like IDEA. */
+15 -5
Переглянути файл
@@ -2,6 +2,7 @@
* Navigation bar popup (⌘↑) model: the path of the active file as segments
* (project › dirs › file › symbols at the caret) and the child list of a segment.
*/
import { isIgnoredName } from "@/platform/ignoredNames";
import type { FileEntry, OutlineItem } from "@/platform/ipc";
import { badgeKind, fileIconName } from "@/ui";
@@ -19,7 +20,11 @@ const parentOf = (p: string) => p.slice(0, Math.max(p.lastIndexOf("/"), 0)) || "
const nameOf = (p: string) => p.slice(p.lastIndexOf("/") + 1);
/** Segments for `path`; directories from the project root, or just the parent folder outside it. */
export function navSegments(project: { root: string; name: string } | null, path: string, chain: readonly OutlineItem[]): NavSegment[] {
export function navSegments(
project: { root: string; name: string } | null,
path: string,
chain: readonly OutlineItem[],
): NavSegment[] {
const out: NavSegment[] = [];
const parent = parentOf(path);
if (project && (parent === project.root || parent.startsWith(project.root + "/"))) {
@@ -42,12 +47,17 @@ export function navSegments(project: { root: string; name: string } | null, path
return out;
}
const HIDDEN = new Set([".git", ".hg", ".svn", ".DS_Store", "__pycache__"]);
export function dirChildren(entries: readonly FileEntry[]): NavChild[] {
return entries
.filter((e) => !HIDDEN.has(e.name))
.map((e) => ({ kind: e.kind === "dir" || (e.kind === "symlink" && e.size === 0) ? "dir" : "file", path: e.path, label: e.name }) as NavChild);
.filter((e) => !isIgnoredName(e.name))
.map(
(e) =>
({
kind: e.kind === "dir" || (e.kind === "symlink" && e.size === 0) ? "dir" : "file",
path: e.path,
label: e.name,
}) as NavChild,
);
}
/** Children of a file or symbol segment: its outline items (one level). */
+5 -2
Переглянути файл
@@ -6,7 +6,8 @@
import type { Action } from "@/platform/actions";
import { t } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename, confirmLeaveProject, openProject, useProject } from "@/platform/project";
import { basename, confirmLeaveProject, openProject, provideStartupLaunch, useProject } from "@/platform/project";
import { holdSplash } from "@/platform/splash";
import { notifications } from "@/workbench/contributions";
import { ask } from "./prompt";
@@ -195,7 +196,9 @@ export function installLaunchHandling(): () => void {
if (!isTauri()) return () => {};
let disposed = false;
let unlisten: (() => void) | undefined;
void consumeLaunch();
const launch = consumeLaunch();
provideStartupLaunch(launch);
holdSplash(launch);
void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
const off = await getCurrentWebviewWindow().listen(LAUNCH_EVENT, () => void consumeLaunch());
if (disposed) off();
+4 -10
Переглянути файл
@@ -4,10 +4,11 @@
* incremental refresh for `fsChanged` events. No React, no IPC.
*/
import type { FileEntry } from "@/bindings";
import { isIgnoredName } from "@/platform/ignoredNames";
import { isSameOrInside, nameOf, parentOf, relativeTo } from "./paths";
export interface TreeOptions {
/** Show IDE-hidden names (`.git`, `.DS_Store`, …). Dotfiles are always shown. */
/** Show ignored names (`files.ignoredNames`: `.git`, `.DS_Store`, …). Dotfiles are always shown. */
showHidden: boolean;
/** Show entries matched by .gitignore / exclude settings (dimmed). */
showExcluded: boolean;
@@ -53,16 +54,9 @@ export interface TreeModel {
export type Listings = ReadonlyMap<string, readonly FileEntry[]>;
/** Names IDEA hides by default ("Ignored Files and Folders"). */
const IDE_HIDDEN = new Set([".git", ".hg", ".svn", "CVS", "_svn", ".DS_Store", "__pycache__", "vssver.scc", "vssver2.scc"]);
const IDE_HIDDEN_EXT = /\.(pyc|pyo|rbc|yarb)$|~$/;
export function isIdeHidden(name: string): boolean {
return IDE_HIDDEN.has(name) || IDE_HIDDEN_EXT.test(name);
}
export function isVisible(entry: FileEntry, opts: TreeOptions): boolean {
if (!opts.showHidden && isIdeHidden(entry.name)) return false;
// Ignored names are also excluded on the backend; only "Show Hidden" brings them back.
if (isIgnoredName(entry.name)) return opts.showHidden;
if (!opts.showExcluded && entry.ignored) return false;
return true;
}
+6
Переглянути файл
@@ -4,6 +4,7 @@
* so `validateSettings` never throws — anything unknown or malformed falls
* back to the default (mirrors `ide-core::settings` defaults).
*/
import { DEFAULT_IGNORED_NAMES } from "@/platform/ignoredNames";
import type { Settings } from "@/platform/ipc";
import {
DEFAULT_LANGUAGES,
@@ -58,6 +59,7 @@ export interface ValidSettings extends WorkflowSettings {
files: {
autoSave: boolean;
exclude: string[];
ignoredNames: string[];
trimTrailingWhitespace: boolean;
ensureFinalNewline: boolean;
/** Local History keeps this many working days (days with changes). */
@@ -95,6 +97,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
files: {
autoSave: true,
exclude: ["**/.git", "**/node_modules", "**/target"],
ignoredNames: [...DEFAULT_IGNORED_NAMES],
trimTrailingWhitespace: true,
ensureFinalNewline: true,
localHistoryDays: 5,
@@ -188,6 +191,9 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
exclude: Array.isArray(f.exclude)
? f.exclude.filter((x): x is string => typeof x === "string" && !!x.trim())
: [...d.files.exclude],
ignoredNames: Array.isArray(f.ignoredNames)
? f.ignoredNames.filter((x): x is string => typeof x === "string" && !!x.trim())
: [...d.files.ignoredNames],
trimTrailingWhitespace: bool(f.trimTrailingWhitespace, d.files.trimTrailingWhitespace),
ensureFinalNewline: bool(f.ensureFinalNewline, d.files.ensureFinalNewline),
localHistoryDays: num(f.localHistoryDays, d.files.localHistoryDays, LIMITS.localHistoryDays, true),
+17 -1
Переглянути файл
@@ -20,6 +20,19 @@ function ExcludeRow() {
);
}
function IgnoredNamesRow() {
const [names, setNames] = useSetting<string[]>("files.ignoredNames");
return (
<Row
label="Ignore files and folders"
stacked
hint="Names (e.g. .DS_Store, *.pyc) hidden from the project tree, navigation bar, search, indexing and Git changes."
>
<GlobListEditor value={names} onChange={setNames} placeholder="*.ext" aria-label="Ignored names" />
</Row>
);
}
export const BUILTIN_PAGES: PageSpec[] = [
{
id: "keymap",
@@ -39,7 +52,10 @@ export const BUILTIN_PAGES: PageSpec[] = [
sections: [
{
title: "Ignored Files and Folders",
options: [{ kind: "custom", label: "Exclude patterns", component: ExcludeRow }],
options: [
{ kind: "custom", label: "Ignore files and folders", component: IgnoredNamesRow },
{ kind: "custom", label: "Exclude patterns", component: ExcludeRow },
],
},
],
},
+54
Переглянути файл
@@ -0,0 +1,54 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const openProject = vi.fn();
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: { ...real.commands, settingsGet: async () => ({ general: { reopenLastProject: true } }) },
};
});
vi.mock("@tauri-apps/api/window", () => ({ getCurrentWindow: () => ({ label: "main" }) }));
vi.mock("@/platform/project", async (orig) => {
const real = await orig<typeof import("@/platform/project")>();
return { ...real, openProject: (p: string) => openProject(p) };
});
const { reopenLastProject, _resetSessionForTests } = await import("./session");
const { provideStartupLaunch, useProject } = await import("@/platform/project");
beforeEach(() => {
openProject.mockReset();
useProject.setState({ project: null });
sessionStorage.clear();
localStorage.setItem("openidea.session.openProject", "/p/last");
_resetSessionForTests();
});
describe("reopenLastProject", () => {
it("waits for the command-line project instead of opening the last one too", async () => {
let finishLaunch!: () => void;
provideStartupLaunch(
new Promise<void>((resolve) => {
finishLaunch = () => {
useProject.setState({ project: { root: "/p/launch" } as never });
resolve();
};
}),
);
const reopened = reopenLastProject();
await new Promise((r) => setTimeout(r, 0));
expect(openProject).not.toHaveBeenCalled();
finishLaunch();
await reopened;
expect(openProject).not.toHaveBeenCalled();
});
it("reopens the last project when the launch named none", async () => {
provideStartupLaunch(Promise.resolve());
await reopenLastProject();
expect(openProject).toHaveBeenCalledWith("/p/last");
});
});
+3 -1
Переглянути файл
@@ -6,7 +6,7 @@
import { getCurrentWindow } from "@tauri-apps/api/window";
import { create } from "zustand";
import { commands, isTauri, type Settings } from "@/platform/ipc";
import { openProject, useProject } from "@/platform/project";
import { openProject, startupLaunchHandled, useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
const SESSION_KEY = "openidea.session.openProject";
@@ -104,6 +104,8 @@ export async function reopenLastProject(): Promise<void> {
/* use the local preference */
}
if (!reopenEnabled(settings, useSession.getState().reopenPref)) return;
// A project passed on the command line wins over the last session's.
await startupLaunchHandled();
if (useProject.getState().project) return;
await reopen(path);
}
+2
Переглянути файл
@@ -6,6 +6,7 @@ import { activateSecondaryWindow, activateWorkbench } from "./workbench/activate
import { activateFeatures, activateSettingsWindowFeatures, SettingsWindow, settingsWindowParent } from "./features";
import { installKeyboardDispatcher } from "./platform/keymap";
import { isTauri } from "./platform/ipc";
import { hideSplash } from "./platform/splash";
import { prefetchLazyComponents } from "./ui";
if (import.meta.env.DEV && isTauri()) {
@@ -42,5 +43,6 @@ if (settingsParent !== null) {
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>{settingsParent !== null ? <SettingsWindow /> : <Workbench />}</React.StrictMode>,
);
hideSplash();
// Views split out of the start-up bundle load in the background once the UI is up.
if (settingsParent === null) prefetchLazyComponents();
+49
Переглянути файл
@@ -0,0 +1,49 @@
/** "Ignored Files and Folders" (`files.ignoredNames`): names hidden everywhere; mirrors `ide_core::ignored`. */
import { useProject } from "./project";
/** Defaults of `ide_core::ignored::DEFAULT_IGNORED_NAMES`; used until settings load. */
export const DEFAULT_IGNORED_NAMES: readonly string[] = [
"*.pyc",
"*.pyo",
"*.rbc",
"*.yarb",
"*~",
".DS_Store",
".git",
".hg",
".jj",
".svn",
"CVS",
"__pycache__",
"_svn",
"vssver.scc",
"vssver2.scc",
"Thumbs.db",
"desktop.ini",
];
let cached: { names: readonly string[]; exact: Set<string>; wildcards: RegExp[] } | null = null;
function compile(names: readonly string[]) {
const exact = new Set<string>();
const wildcards: RegExp[] = [];
for (const raw of names) {
const n = raw.trim();
if (!n || n.includes("/")) continue;
if (!/[*?]/.test(n)) exact.add(n);
else {
const body = n
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*")
.replace(/\?/g, ".");
wildcards.push(new RegExp(`^${body}$`, "s"));
}
}
return { names, exact, wildcards };
}
export function isIgnoredName(name: string): boolean {
const names = useProject.getState().settings?.files?.ignoredNames ?? DEFAULT_IGNORED_NAMES;
const m = cached?.names === names ? cached : (cached = compile(names));
return m.exact.has(name) || m.wildcards.some((re) => re.test(name));
}
+12
Переглянути файл
@@ -27,6 +27,18 @@ export function confirmLeaveProject(): Promise<boolean> {
return useProject.getState().project && leaveGuard ? leaveGuard() : Promise.resolve(true);
}
let startupLaunch: Promise<void> | null = null;
/** Installs this window's startup launch (the project it was started or created for, features/app/windows.ts). */
export function provideStartupLaunch(launch: Promise<void>) {
startupLaunch = launch;
}
/** Settles once the startup launch has opened its project (if any), so a restore doesn't race it. */
export function startupLaunchHandled(): Promise<void> {
return (startupLaunch ?? Promise.resolve()).catch(() => {});
}
export async function openProject(path: string): Promise<ProjectInfo> {
useProject.setState({ opening: true });
try {
+29
Переглянути файл
@@ -0,0 +1,29 @@
/**
* The start-up splash (`#splash` in index.html). It covers the first render and
* stays up while start-up work holds it (opening the window's launch project),
* so a project window never flashes the Welcome screen first.
*/
const holds: Promise<unknown>[] = [];
/** Never keep the splash longer than this; a slow open shows its own progress. */
const MAX_WAIT_MS = 4000;
/** Keeps the splash up until `work` settles. Call before `hideSplash()`. */
export function holdSplash(work: Promise<unknown>): void {
holds.push(work.catch(() => {}));
}
/** Fades the splash out once every hold has settled and the page has painted. */
export function hideSplash(): void {
const el = document.getElementById("splash");
if (!el) return;
const timeout = new Promise((resolve) => setTimeout(resolve, MAX_WAIT_MS));
void Promise.race([Promise.all(holds), timeout]).then(() =>
// Two frames: let React commit the state the holds produced before uncovering it.
requestAnimationFrame(() =>
requestAnimationFrame(() => {
el.classList.add("splash-out");
setTimeout(() => el.remove(), 200);
}),
),
);
}
+5
Переглянути файл
@@ -74,6 +74,11 @@
-webkit-user-select: text;
user-select: text;
}
.input:focus-visible,
.searchInput:focus-visible {
/* The frame's focus ring stands in for the global :focus-visible outline. */
outline: none;
}
.invalid .searchInput {
color: var(--danger);
}