дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 11:18:20 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
64ad79d801 |
No files matched your search
Створено
+37
-38
@@ -4071,7 +4071,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4094,7 +4094,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4108,7 +4108,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4119,7 +4119,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4134,7 +4134,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4143,7 +4143,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4160,7 +4160,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4174,7 +4174,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4192,7 +4192,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4218,7 +4218,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4231,7 +4231,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4251,7 +4251,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4263,7 +4263,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4276,7 +4276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"criterion",
|
||||
@@ -4337,7 +4337,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4355,7 +4355,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4377,7 +4377,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4394,7 +4394,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4450,7 +4450,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4476,7 +4476,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4499,7 +4499,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"ide-core",
|
||||
@@ -4520,7 +4520,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4533,7 +4533,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4550,7 +4550,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4573,7 +4573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4592,7 +4592,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4612,7 +4612,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4625,7 +4625,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4647,7 +4647,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4662,7 +4662,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4675,7 +4675,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4688,7 +4688,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4709,7 +4709,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4730,7 +4730,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4752,7 +4752,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4768,7 +4768,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6309,7 +6309,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6374,7 +6374,6 @@ dependencies = [
|
||||
"tauri-plugin-updater",
|
||||
"tauri-plugin-window-state",
|
||||
"tauri-specta",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.37"
|
||||
version = "0.1.36"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -821,14 +821,13 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
mod tests {
|
||||
#[test]
|
||||
fn independent_gradle_builds_keep_their_launchers_and_task_paths() {
|
||||
let wrapper = if cfg!(windows) { "gradlew.bat" } else { "gradlew" };
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
for dir in ["a", "b"] {
|
||||
std::fs::create_dir_all(root.join(dir).join("app/src/main/java")).unwrap();
|
||||
std::fs::write(root.join(dir).join("settings.gradle"), "include 'app'").unwrap();
|
||||
std::fs::write(root.join(dir).join("app/build.gradle"), "plugins { id 'java' }").unwrap();
|
||||
std::fs::write(root.join(dir).join(wrapper), "").unwrap();
|
||||
std::fs::write(root.join(dir).join("gradlew"), "").unwrap();
|
||||
}
|
||||
let settings = ide_core::settings::GradleSettings {
|
||||
linked_projects: Some(vec!["a".into(), "b".into()]),
|
||||
@@ -843,7 +842,7 @@ mod tests {
|
||||
assert_eq!(all.steps[1].cwd, root.join("b"));
|
||||
let module = super::plan(root, &model, super::BuildKind::Rebuild, Some(&root.join("b/app")), None).unwrap();
|
||||
assert_eq!(module.steps.len(), 1);
|
||||
assert_eq!(module.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
|
||||
assert_eq!(module.steps[0].program, root.join("b/gradlew").to_string_lossy());
|
||||
assert_eq!(module.steps[0].cwd, root.join("b"));
|
||||
assert_eq!(module.steps[0].env["JAVA_HOME"], "/jdk-b");
|
||||
assert_eq!(module.steps[0].args, ["--console=plain", ":app:clean", ":app:classes", ":app:testClasses"]);
|
||||
@@ -855,7 +854,7 @@ mod tests {
|
||||
nested.path = ":b:app".into();
|
||||
model.gradle[0].projects.push(nested);
|
||||
let nested = super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).unwrap();
|
||||
assert_eq!(nested.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
|
||||
assert_eq!(nested.steps[0].program, root.join("b/gradlew").to_string_lossy());
|
||||
assert_eq!(nested.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
model.gradle.clear();
|
||||
assert!(super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).is_err());
|
||||
@@ -863,7 +862,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn absolute_linked_roots_build_the_project_and_external_source_module() {
|
||||
let wrapper = if cfg!(windows) { "gradlew.bat" } else { "gradlew" };
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("workspace");
|
||||
@@ -873,7 +871,7 @@ mod tests {
|
||||
std::fs::write(external.join("settings.gradle"), "include 'app'").unwrap();
|
||||
let source = external.join("app/src/main/java/App.java");
|
||||
std::fs::write(&source, "class App {}").unwrap();
|
||||
std::fs::write(external.join(wrapper), "").unwrap();
|
||||
std::fs::write(external.join("gradlew"), "").unwrap();
|
||||
let settings = ide_core::settings::GradleSettings {
|
||||
linked_projects: Some(vec![external.to_string_lossy().into_owned()]),
|
||||
..Default::default()
|
||||
@@ -882,7 +880,7 @@ mod tests {
|
||||
model.gradle[0].env.insert("JAVA_HOME".into(), "/external-jdk".into());
|
||||
let all = super::plan(&root, &model, super::BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(all.steps[0].cwd, external);
|
||||
assert_eq!(all.steps[0].program, external.join(wrapper).to_string_lossy());
|
||||
assert_eq!(all.steps[0].program, external.join("gradlew").to_string_lossy());
|
||||
let module = super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None).unwrap();
|
||||
assert_eq!(module.steps[0].cwd, external);
|
||||
assert_eq!(module.steps[0].env["JAVA_HOME"], "/external-jdk");
|
||||
|
||||
@@ -481,15 +481,6 @@ pub fn normalize_linked_projects(root: &Path, dirs: &[String]) -> ide_core::IdeR
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The form `normalize_linked_projects` saves `dir` in, also for a folder that no longer
|
||||
/// exists, so a path the UI sends (`C:\…` on Windows) matches the saved entry.
|
||||
pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
match (dunce::canonicalize(root), dunce::canonicalize(root.join(dir))) {
|
||||
(Ok(root), Ok(path)) => rel(&root, &path),
|
||||
_ => dir.replace('\\', "/"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
@@ -684,30 +675,6 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_path_from_the_ui_finds_the_saved_link() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("workspace");
|
||||
let external = temp.path().join("external");
|
||||
for dir in [root.join("a"), external.clone()] {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("settings.gradle"), "").unwrap();
|
||||
}
|
||||
let native = |p: &std::path::Path| p.to_string_lossy().into_owned();
|
||||
// Saved by linking; unlinking may send a native, absolute or non-canonical spelling.
|
||||
for (dir, sent) in [
|
||||
("a", native(&root.join("a"))),
|
||||
("a", "a".to_owned()),
|
||||
("a", native(&root.join("a").join("..").join("a"))),
|
||||
("../external", native(&external)),
|
||||
] {
|
||||
let saved = super::normalize_linked_projects(&root, &[dir.into()]).unwrap();
|
||||
assert_eq!(super::linked_project_key(&root, &sent), saved[0], "{sent}");
|
||||
}
|
||||
// A folder deleted since it was linked still matches its saved entry.
|
||||
assert_eq!(super::linked_project_key(&root, r"gone\build"), "gone/build");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_linkage_preserves_default_discovery_and_can_unlink_every_build() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -216,7 +216,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(
|
||||
gradle_external_roots(&root, &temp.path().join("cache"), &settings),
|
||||
[dunce::canonicalize(&external).unwrap()]
|
||||
[external.canonicalize().unwrap()]
|
||||
);
|
||||
settings.linked_projects = Some(vec![]);
|
||||
assert!(gradle_external_roots(&root, &temp.path().join("cache"), &settings).is_empty());
|
||||
|
||||
@@ -24,7 +24,6 @@ pub mod text;
|
||||
pub mod tool_path;
|
||||
pub mod version_managers;
|
||||
pub mod workflow_settings;
|
||||
pub mod wsl;
|
||||
|
||||
pub use error::{IdeError, IdeResult};
|
||||
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
//! Projects that live inside a WSL distro are reached from Windows through the
|
||||
//! `\\wsl.localhost\<distro>` (or legacy `\\wsl$\<distro>`) share.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The WSL launcher on Windows.
|
||||
pub const EXE: &str = "wsl.exe";
|
||||
|
||||
/// A location inside a WSL distro.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WslPath {
|
||||
pub distro: String,
|
||||
/// Absolute Linux path, e.g. `/home/me/app`.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// Splits a WSL share path into distro and Linux path. Pure string work, so it
|
||||
/// accepts every spelling the UI and the OS produce: `\\wsl.localhost\X\a`,
|
||||
/// `//wsl$/X/a` and the verbatim `\\?\UNC\wsl.localhost\X\a`.
|
||||
pub fn parse(path: &Path) -> Option<WslPath> {
|
||||
let s = path.to_string_lossy().replace('\\', "/");
|
||||
let s = match s.strip_prefix("//?/UNC/") {
|
||||
Some(rest) => format!("//{rest}"),
|
||||
None => s,
|
||||
};
|
||||
let rest = s.strip_prefix("//")?;
|
||||
let (host, rest) = rest.split_once('/')?;
|
||||
if !host.eq_ignore_ascii_case("wsl.localhost") && !host.eq_ignore_ascii_case("wsl$") {
|
||||
return None;
|
||||
}
|
||||
let (distro, tail) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
if distro.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
|
||||
}
|
||||
|
||||
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
|
||||
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
|
||||
pub fn is_valid_distro(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 64
|
||||
&& !name.starts_with('-')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
|
||||
}
|
||||
|
||||
/// Text of `wsl.exe`'s own output: UTF-16LE (with or without BOM) for its management commands
|
||||
/// and its error messages, UTF-8 for what a command inside the distro prints.
|
||||
pub fn decode_output(raw: &[u8]) -> String {
|
||||
if raw.starts_with(&[0xff, 0xfe]) || raw.get(1) == Some(&0) {
|
||||
let units: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
} else {
|
||||
String::from_utf8_lossy(raw).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Distro names from the output of `wsl.exe -l -q`. That output is UTF-16LE (UTF-8 when
|
||||
/// `WSL_UTF8=1`), one name per line; names that fail [`is_valid_distro`] are dropped, which also
|
||||
/// removes the localized "no installed distributions" message `wsl.exe` prints when there are none.
|
||||
pub fn parse_distro_list(raw: &[u8]) -> Vec<String> {
|
||||
let text = decode_output(raw);
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for line in text.lines() {
|
||||
let name = line.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}');
|
||||
if is_valid_distro(name) && !names.iter().any(|n| n == name) {
|
||||
names.push(name.to_owned());
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Installed WSL distros. Empty off Windows, when WSL is not installed or when `wsl.exe` fails.
|
||||
pub fn list_distros() -> Vec<String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut cmd = std::process::Command::new(EXE);
|
||||
cmd.args(["-l", "-q"]);
|
||||
crate::process::prepare(&mut cmd);
|
||||
match cmd.output() {
|
||||
Ok(out) if out.status.success() => parse_distro_list(&out.stdout),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p(s: &str) -> Option<(String, String)> {
|
||||
parse(Path::new(s)).map(|w| (w.distro, w.path))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_spelling_of_the_share_is_recognised() {
|
||||
let want = Some(("Ubuntu-24.04".to_owned(), "/home/me/app".to_owned()));
|
||||
assert_eq!(p(r"\\wsl.localhost\Ubuntu-24.04\home\me\app"), want);
|
||||
assert_eq!(p("//wsl.localhost/Ubuntu-24.04/home/me/app"), want);
|
||||
assert_eq!(p(r"\\wsl$\Ubuntu-24.04\home\me\app\"), want);
|
||||
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_root_and_foreign_paths() {
|
||||
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
|
||||
assert_eq!(p(r"\\server\share\a"), None);
|
||||
assert_eq!(p(r"\\wsl.localhost\"), None);
|
||||
assert_eq!(p("C:/Users/me"), None);
|
||||
assert_eq!(p("/home/me"), None);
|
||||
}
|
||||
|
||||
fn utf16(s: &str) -> Vec<u8> {
|
||||
std::iter::once(0xfeffu16).chain(s.encode_utf16()).flat_map(u16::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_list_is_decoded_from_utf16_and_utf8() {
|
||||
let want = vec!["Ubuntu-24.04".to_owned(), "Debian".to_owned()];
|
||||
assert_eq!(parse_distro_list(&utf16("Ubuntu-24.04\r\nDebian\r\n\r\n")), want);
|
||||
assert_eq!(parse_distro_list(b"Ubuntu-24.04\nDebian\nDebian\n"), want);
|
||||
assert!(
|
||||
parse_distro_list(&utf16("Windows Subsystem for Linux has no installed distributions.\r\n")).is_empty()
|
||||
);
|
||||
assert!(parse_distro_list(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_names_cannot_smuggle_options_or_paths() {
|
||||
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
|
||||
assert!(!is_valid_distro(bad), "{bad}");
|
||||
}
|
||||
assert!(is_valid_distro("Ubuntu-22.04") && is_valid_distro("docker_desktop"));
|
||||
}
|
||||
}
|
||||
@@ -79,9 +79,7 @@ impl Capability {
|
||||
Self::Secrets => "Store secrets in the system keychain".into(),
|
||||
Self::Events => "Observe workbench events (files opened, saved, focus)".into(),
|
||||
Self::InputEvents => "Observe keystrokes and editor input".into(),
|
||||
Self::Clipboard => {
|
||||
"Copy to the clipboard from its commands, and read and write it from its web views".into()
|
||||
}
|
||||
Self::Clipboard => "Read and write the clipboard from its web views".into(),
|
||||
Self::Net(host) => format!("Connect to {host} (from the machine the project is on)"),
|
||||
Self::Process(bin) => format!("Run {bin} — equivalent to running arbitrary code on this machine"),
|
||||
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
|
||||
|
||||
@@ -86,8 +86,6 @@ pub struct Host {
|
||||
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
|
||||
/// Shutdowns of projects closed with [`Host::close_project_detached`].
|
||||
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
|
||||
/// One open at a time per window (see [`Host::opening`]).
|
||||
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
|
||||
}
|
||||
|
||||
/// How long exit waits for project shutdown before giving up.
|
||||
@@ -137,7 +135,6 @@ impl Host {
|
||||
requests: Default::default(),
|
||||
project_requests: RwLock::default(),
|
||||
closing: Default::default(),
|
||||
open_locks: Default::default(),
|
||||
};
|
||||
host.apply_proxy();
|
||||
host
|
||||
@@ -404,13 +401,6 @@ impl Host {
|
||||
self.requests.cancel(id);
|
||||
}
|
||||
|
||||
/// The lock an open of `window` holds from its check for the current project to its
|
||||
/// insert: two opens racing (a double click, a launch path and a restore) would each start
|
||||
/// an index, language servers and watchers, and the second would replace the first unclosed.
|
||||
pub(crate) fn opening(&self, window: &str) -> Arc<parking_lot::Mutex<()>> {
|
||||
self.open_locks.lock().entry(window.to_owned()).or_default().clone()
|
||||
}
|
||||
|
||||
pub(crate) fn insert_project(&self, window: &str, project: Arc<Project>) {
|
||||
self.projects.write().insert(window.to_owned(), project);
|
||||
}
|
||||
|
||||
@@ -137,8 +137,7 @@ fn linked_gradle_paths(
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let unlinked: Vec<String> = paths.iter().map(|p| ide_build::gradle::linked_project_key(root, p)).collect();
|
||||
linked.retain(|path| !paths.contains(path) && !unlinked.contains(path));
|
||||
linked.retain(|path| !paths.contains(path));
|
||||
}
|
||||
Ok(linked)
|
||||
}
|
||||
|
||||
@@ -422,8 +422,7 @@ struct IdeDir {
|
||||
plugins: PathBuf,
|
||||
}
|
||||
|
||||
/// The settings folders of JetBrains IDEs and Android Studio (2020.1 and later), newest first, one
|
||||
/// per product: its newest version's (an upgrade leaves the older ones behind).
|
||||
/// The settings folders of JetBrains IDEs and Android Studio (2020.1 and later), newest first.
|
||||
fn ide_dirs(layout: Layout, home: &Path, env: impl Fn(&str) -> Option<OsString>) -> Vec<IdeDir> {
|
||||
let var = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let (config_root, data_root) = match layout {
|
||||
@@ -463,8 +462,6 @@ fn ide_dirs(layout: Layout, home: &Path, env: impl Fn(&str) -> Option<OsString>)
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.version.cmp(&a.version).then_with(|| a.label.cmp(&b.label)));
|
||||
let mut products = std::collections::HashSet::new();
|
||||
out.retain(|ide| products.insert(ide.product.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -787,13 +784,6 @@ mod tests {
|
||||
};
|
||||
let mac = mk(home.join("Library/Application Support/JetBrains/IntelliJIdea2025.2"));
|
||||
mk(home.join("Library/Application Support/JetBrains/Toolbox"));
|
||||
// An upgrade leaves the older version's folder behind: only the newest of a product counts.
|
||||
mk(home.join("Library/Application Support/JetBrains/IntelliJIdea2024.3"));
|
||||
mk(home.join("Library/Application Support/JetBrains/IntelliJIdea2025.10"));
|
||||
let dirs = ide_dirs(Layout::Mac, home, |_| None);
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert_eq!(dirs[0].label, "IntelliJ IDEA 2025.10");
|
||||
std::fs::remove_dir(home.join("Library/Application Support/JetBrains/IntelliJIdea2025.10")).unwrap();
|
||||
let dirs = ide_dirs(Layout::Mac, home, |_| None);
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert_eq!(dirs[0].label, "IntelliJ IDEA 2025.2");
|
||||
|
||||
@@ -77,8 +77,6 @@ impl Host {
|
||||
lap = std::time::Instant::now();
|
||||
};
|
||||
let root = dunce::canonicalize(root)?;
|
||||
let opening = self.opening(window);
|
||||
let _opening = opening.lock();
|
||||
// Reject a damaged manifest before replacing the currently open project.
|
||||
ide_workspace::workspace::Workspace::load(&root)?;
|
||||
// The window reloaded (or asked again) for the project it already has: keep
|
||||
@@ -571,8 +569,6 @@ impl Host {
|
||||
return Err(IdeError::invalid(format!("{} is a folder", file.display())));
|
||||
}
|
||||
let dir = file.parent().map(Path::to_path_buf).ok_or_else(|| IdeError::invalid("no parent folder"))?;
|
||||
let opening = self.opening(window);
|
||||
let _opening = opening.lock();
|
||||
if let Ok(current) = self.project(window)
|
||||
&& current.light
|
||||
{
|
||||
|
||||
@@ -251,8 +251,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "remote_disconnect"
|
||||
| "remote_connect"
|
||||
| "remote_bootstrap_list"
|
||||
| "wsl_distros"
|
||||
| "wsl_resolve"
|
||||
| "remote_list"
|
||||
| "remote_open"
|
||||
| "remote_of"
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Opening the project a window is already opening reuses it: racing opens (a double
|
||||
//! click, a launch path and a restore) must not start a second index and language servers.
|
||||
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig};
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
#[test]
|
||||
fn racing_opens_of_one_window_share_one_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("src/Main.java"), "class Main {}\n").unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
|
||||
let _guard = runtime.enter();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: runtime.handle().clone(),
|
||||
project_environment: false,
|
||||
}));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
|
||||
let start = Arc::new(Barrier::new(4));
|
||||
let opens: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let (host, root, start) = (host.clone(), root.clone(), start.clone());
|
||||
std::thread::spawn(move || {
|
||||
start.wait();
|
||||
host.open_project("main", &root).unwrap()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let projects: Vec<_> = opens.into_iter().map(|t| t.join().unwrap()).collect();
|
||||
|
||||
let current = host.project("main").unwrap();
|
||||
for project in &projects {
|
||||
assert!(Arc::ptr_eq(project, ¤t), "every open returns the window's one project");
|
||||
}
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -49,10 +49,6 @@ pub mod framing {
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
// A UTF-16LE line break is `\n\0`: the cut after `\n` leaves a NUL at the start of the
|
||||
// next line, which would turn the `Content-Length` after it into noise.
|
||||
let nuls = line.iter().take_while(|&&b| b == 0).count();
|
||||
line.drain(..nuls);
|
||||
if line.last() != Some(&b'\n') {
|
||||
if n as u64 >= MAX_HEADER_LINE {
|
||||
return Err(Error::new(ErrorKind::InvalidData, "header line too long"));
|
||||
|
||||
@@ -69,21 +69,6 @@ mod framing_tests {
|
||||
assert_eq!(noise[2], "Picked up JAVA_TOOL_OPTIONS: -Dx");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn utf16_output_of_wsl_exe_before_a_message_does_not_swallow_it() {
|
||||
// `wsl.exe` reports its own errors as UTF-16LE with a BOM; the real server only starts
|
||||
// after it, so the first message must still be read whole.
|
||||
let notice = "The Windows Subsystem for Linux instance has terminated.";
|
||||
let mut input: Vec<u8> = [0xff, 0xfe].into();
|
||||
input.extend(format!("{notice}\r\n").encode_utf16().flat_map(u16::to_le_bytes));
|
||||
input.extend(b"Content-Length: 2\r\n\r\n{}");
|
||||
let (msgs, noise) = read_with_noise(&input).await;
|
||||
assert_eq!(msgs.unwrap(), vec![b"{}".to_vec()]);
|
||||
// The text is kept for the error shown to the user, whatever the BOM decodes to.
|
||||
let ascii: String = noise.concat().chars().filter(char::is_ascii).filter(|c| *c != '\0').collect();
|
||||
assert_eq!(ascii.trim(), notice);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unterminated_output_then_eof_is_reported() {
|
||||
// `pause` prints its prompt without a newline and the process is gone.
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
//! its templates (`default="true"`) and temporary configurations. A configuration found in more
|
||||
//! than one place is taken from the first, in that order.
|
||||
//!
|
||||
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script,
|
||||
//! Application, Spring Boot and compound configurations become the matching kinds; other types
|
||||
//! are skipped with their type.
|
||||
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script and
|
||||
//! compound configurations become the matching kinds; other types are skipped with their type.
|
||||
//! `$PROJECT_DIR$` (and `$MODULE_DIR$`, `$MODULE_WORKING_DIR$`, `$ContentRoot$`,
|
||||
//! `$ProjectFileDir$`, all the project directory here) and `$USER_HOME$` are replaced; another
|
||||
//! path variable skips the configuration.
|
||||
@@ -163,8 +162,6 @@ const VITEST: &str = "JavaScriptTestRunnerVitest";
|
||||
const NODE: &str = "NodeJSConfigurationType";
|
||||
const SHELL: &str = "ShConfigurationType";
|
||||
const COMPOUND: &str = "CompoundRunConfigurationType";
|
||||
const APPLICATION: &str = "Application";
|
||||
const SPRING_BOOT: &str = "SpringBootApplicationConfigurationType";
|
||||
|
||||
type Res<T> = Result<T, SkipReason>;
|
||||
|
||||
@@ -332,8 +329,6 @@ impl Cx<'_> {
|
||||
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
|
||||
NODE => self.node(name, c, &mut ignored)?,
|
||||
SHELL => self.shell(name, c)?,
|
||||
APPLICATION => self.java_app(name, c, false, &mut ignored)?,
|
||||
SPRING_BOOT => self.java_app(name, c, true, &mut ignored)?,
|
||||
COMPOUND => {
|
||||
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
|
||||
config(name, "compound", String::new(), Vec::new(), None)
|
||||
@@ -700,54 +695,6 @@ impl Cx<'_> {
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Java
|
||||
|
||||
/// IDEA's Application and Spring Boot types, as the `application` / `spring-boot` forms run
|
||||
/// them: `java <vm options> -cp ${classpath} <main> [--spring.profiles.active=…] <arguments>`
|
||||
/// with the module's runtime classpath.
|
||||
fn java_app(&self, name: &str, c: &El, spring: bool, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let main = if spring { "SPRING_BOOT_MAIN_CLASS" } else { "MAIN_CLASS_NAME" };
|
||||
let Some(main) = self.text(c.option(main))? else { return Err(SkipReason::NothingToRun) };
|
||||
let (_, cwd) = self.cwd(c.option("WORKING_DIRECTORY"))?;
|
||||
let mut args = self.words(c.option("VM_PARAMETERS"))?;
|
||||
args.extend(["-cp".to_owned(), "${classpath}".to_owned(), main]);
|
||||
if spring && let Some(profiles) = self.text(c.option("ACTIVE_PROFILES"))? {
|
||||
args.push(format!("--spring.profiles.active={profiles}"));
|
||||
}
|
||||
args.extend(self.words(c.option("PROGRAM_PARAMETERS"))?);
|
||||
let mut rc =
|
||||
config(name, if spring { "spring-boot" } else { "application" }, "java".into(), args, Some("java-debug"));
|
||||
rc.cwd = cwd.map(Into::into);
|
||||
self.envs(c, &mut rc);
|
||||
if let Some(module) = c.child("module").and_then(|m| m.attr("name")).filter(|m| !m.is_empty()) {
|
||||
match module_dir(self.root, module) {
|
||||
Some(dir) => rc.extras.module = Some(dir),
|
||||
None => ignored.push(format!("module {module}")),
|
||||
}
|
||||
}
|
||||
// Options the forms have no field for.
|
||||
if c.flag("ALTERNATIVE_JRE_PATH_ENABLED") {
|
||||
ignored.push("JRE".into());
|
||||
}
|
||||
if c.flag("INCLUDE_PROVIDED_SCOPE") {
|
||||
ignored.push("provided scope".into());
|
||||
}
|
||||
if c.child("classpathModifications").is_some_and(|m| !m.children.is_empty()) {
|
||||
ignored.push("classpath modifications".into());
|
||||
}
|
||||
if spring {
|
||||
for (option, label) in [("HIDE_BANNER", "hide banner"), ("DEBUG_MODE", "debug output")] {
|
||||
if c.flag(option) {
|
||||
ignored.push(label.into());
|
||||
}
|
||||
}
|
||||
if c.child("additionalParameters").is_some_and(|p| !p.children.is_empty()) {
|
||||
ignored.push("override configuration properties".into());
|
||||
}
|
||||
}
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Shell
|
||||
|
||||
/// A script file (with its interpreter) or script text, kept as the Shell Script form's fields.
|
||||
@@ -888,56 +835,6 @@ fn module_count(root: &Path) -> usize {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The folder (relative, `""` for the project's own) of IDEA module `name`: a Maven module is
|
||||
/// named after its `artifactId` (usually its folder), a Gradle one `<project>.<path>.<source set>`.
|
||||
fn module_dir(root: &Path, name: &str) -> Option<String> {
|
||||
let folder = |dir: &Path| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let exact = |dir: &Path| folder(dir) == name || pom_artifact(dir).is_some_and(|a| a == name);
|
||||
if let Some(dir) = find_module(root, &exact) {
|
||||
return Some(dir);
|
||||
}
|
||||
let gradle = name.strip_suffix(".main").or_else(|| name.strip_suffix(".test")).unwrap_or(name);
|
||||
let last = gradle.rsplit('.').next().filter(|last| *last != name)?;
|
||||
find_module(root, &|dir: &Path| folder(dir) == last)
|
||||
}
|
||||
|
||||
/// The shallowest build folder under `root` (itself included) that `names` accepts.
|
||||
fn find_module(root: &Path, names: &dyn Fn(&Path) -> bool) -> Option<String> {
|
||||
const BUILDS: [&str; 3] = ["pom.xml", "build.gradle", "build.gradle.kts"];
|
||||
let mut level = vec![root.to_path_buf()];
|
||||
for _ in 0..5 {
|
||||
if let Some(found) = level.iter().find(|d| BUILDS.iter().any(|b| d.join(b).is_file()) && names(d)) {
|
||||
let rel = found.strip_prefix(root).ok()?;
|
||||
return Some(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
let mut next: Vec<PathBuf> = level
|
||||
.iter()
|
||||
.filter_map(|d| std::fs::read_dir(d).ok())
|
||||
.flat_map(|entries| entries.flatten().map(|e| e.path()))
|
||||
.filter(|p| p.is_dir())
|
||||
.filter(|p| {
|
||||
let n = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
!n.starts_with('.') && !["node_modules", "target", "build", "out", "src"].contains(&n.as_str())
|
||||
})
|
||||
.collect();
|
||||
next.sort();
|
||||
level = next;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `artifactId` of the module's own `pom.xml` (not its parent's).
|
||||
fn pom_artifact(dir: &Path) -> Option<String> {
|
||||
let pom = std::fs::read_to_string(dir.join("pom.xml")).ok()?;
|
||||
let own = match (pom.find("<parent>"), pom.find("</parent>")) {
|
||||
(Some(start), Some(end)) if start < end => format!("{}{}", &pom[..start], &pom[end..]),
|
||||
_ => pom,
|
||||
};
|
||||
let start = own.find("<artifactId>")? + "<artifactId>".len();
|
||||
let end = start + own[start..].find("</artifactId>")?;
|
||||
Some(own[start..end].trim().to_owned())
|
||||
}
|
||||
|
||||
/// `--settings` from PyCharm's "Settings" field: a file (`mysite/settings/dev.py`, relative to
|
||||
/// the project) becomes its module relative to the working directory; a module stays as it is.
|
||||
fn settings_module(value: &str, root: &Path, dir: &Path) -> String {
|
||||
|
||||
@@ -239,8 +239,8 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
<envs><env name="VITE_API" value="http://localhost:8000" /></envs>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Main" type="JUnit" factoryName="JUnit">
|
||||
<option name="MAIN_CLASS_NAME" value="shop.MainTest" />
|
||||
<configuration name="Main" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="shop.Main" />
|
||||
<method v="2" />
|
||||
</configuration>"#
|
||||
)),
|
||||
@@ -272,7 +272,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"]));
|
||||
|
||||
assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() });
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "Application".into() });
|
||||
|
||||
let dev = get(&r, "dev");
|
||||
assert_eq!((dev.kind.as_str(), dev.command.as_str()), ("npm", "pnpm"));
|
||||
@@ -526,11 +526,14 @@ fn sources_are_offered_when_their_files_exist() {
|
||||
),
|
||||
);
|
||||
assert!(available(dir.path()).is_empty());
|
||||
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="JUnit" />"#));
|
||||
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="Application" />"#));
|
||||
assert_eq!(available(dir.path()), [RunImportSource::Jetbrains]);
|
||||
write(dir.path(), ".vscode/launch.json", "{}");
|
||||
assert_eq!(available(dir.path()), [RunImportSource::Vscode, RunImportSource::Jetbrains]);
|
||||
assert_eq!(reason(&import_from(dir.path(), &[]), "App"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
|
||||
assert_eq!(
|
||||
reason(&import_from(dir.path(), &[]), "App"),
|
||||
&SkipReason::UnsupportedType { type_: "Application".into() }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -699,91 +702,3 @@ fn flags_defaults_inherited_variables_and_nested_django_tests() {
|
||||
assert_eq!((tests.kind.as_str(), tests.is_test), ("python", true));
|
||||
assert_eq!(tests.args[..3], s(&["backend/manage.py", "test", "orders"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_applications_and_spring_boot_keep_their_module() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
write(&root, "pom.xml", "<project><artifactId>shop</artifactId><packaging>pom</packaging></project>");
|
||||
write(
|
||||
&root,
|
||||
"example-service/pom.xml",
|
||||
"<project><parent><artifactId>shop</artifactId></parent><artifactId>example-service</artifactId></project>",
|
||||
);
|
||||
// IDEA names a Maven module after its artifactId, which needn't be its folder.
|
||||
write(
|
||||
&root,
|
||||
"services/api/pom.xml",
|
||||
"<project><parent><artifactId>shop</artifactId></parent><artifactId>api-service</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
".idea/workspace.xml",
|
||||
&workspace(
|
||||
r#" <configuration name="ExampleApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
|
||||
<module name="example-service" />
|
||||
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.ExampleApplication" />
|
||||
<option name="ACTIVE_PROFILES" value="dev,local" />
|
||||
<option name="VM_PARAMETERS" value="-Xmx512m -Dfile.encoding=UTF-8" />
|
||||
<option name="PROGRAM_PARAMETERS" value="--server.port=8081" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/example-service" />
|
||||
<option name="HIDE_BANNER" value="true" />
|
||||
<envs>
|
||||
<env name="TZ" value="UTC" />
|
||||
</envs>
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration name="Api" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="com.example.api.Main" />
|
||||
<module name="api-service" />
|
||||
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
|
||||
<option name="ALTERNATIVE_JRE_PATH" value="17" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Gone" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="Gone" />
|
||||
<module name="removed-module" />
|
||||
</configuration>
|
||||
<configuration name="NoMain" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
|
||||
<module name="example-service" />
|
||||
</configuration>"#,
|
||||
),
|
||||
);
|
||||
|
||||
let r = import_from(&root, &[]);
|
||||
|
||||
let boot = get(&r, "ExampleApplication");
|
||||
assert_eq!(boot.kind, "spring-boot");
|
||||
assert_eq!(boot.command, "java");
|
||||
assert_eq!(
|
||||
boot.args,
|
||||
s(&[
|
||||
"-Xmx512m",
|
||||
"-Dfile.encoding=UTF-8",
|
||||
"-cp",
|
||||
"${classpath}",
|
||||
"com.example.ExampleApplication",
|
||||
"--spring.profiles.active=dev,local",
|
||||
"--server.port=8081",
|
||||
])
|
||||
);
|
||||
assert_eq!(boot.extras.module.as_deref(), Some("example-service"));
|
||||
assert_eq!(cwd(boot), Some(PathBuf::from("example-service")));
|
||||
assert_eq!(boot.env.get("TZ").map(String::as_str), Some("UTC"));
|
||||
assert_eq!(boot.debug_adapter.as_deref(), Some("java-debug"));
|
||||
assert_eq!(ignored(&r, "ExampleApplication"), ["before launch", "hide banner"]);
|
||||
|
||||
let api = get(&r, "Api");
|
||||
assert_eq!(api.kind, "application");
|
||||
assert_eq!(api.args, s(&["-cp", "${classpath}", "com.example.api.Main"]));
|
||||
assert_eq!(api.extras.module.as_deref(), Some("services/api"));
|
||||
assert_eq!(ignored(&r, "Api"), ["JRE"]);
|
||||
|
||||
// A module that isn't here any more: the form finds it by the main class.
|
||||
assert_eq!(get(&r, "Gone").extras.module, None);
|
||||
assert_eq!(ignored(&r, "Gone"), ["module removed-module"]);
|
||||
|
||||
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
|
||||
}
|
||||
@@ -60,9 +60,6 @@ struct Session {
|
||||
writer: Mutex<Box<dyn Write + Send>>,
|
||||
killer: Mutex<Box<dyn ChildKiller + Send + Sync>>,
|
||||
exited: Arc<AtomicBool>,
|
||||
started: Instant,
|
||||
/// The first input was logged (startup diagnostics, see `spawn`).
|
||||
input_logged: AtomicBool,
|
||||
}
|
||||
|
||||
type Sessions = Arc<Mutex<HashMap<TerminalId, Arc<Session>>>>;
|
||||
@@ -95,8 +92,7 @@ impl TerminalManager {
|
||||
let size = pty_size(options.cols, options.rows);
|
||||
let pair = native_pty_system().openpty(size).map_err(|e| IdeError::internal(format!("openpty failed: {e}")))?;
|
||||
|
||||
let wsl = if cfg!(windows) { wsl_shell(&options) } else { None };
|
||||
let (shell, mut args) = wsl.clone().unwrap_or_else(|| resolve_shell(options.shell.as_deref(), &options.args));
|
||||
let (shell, mut args) = resolve_shell(options.shell.as_deref(), &options.args);
|
||||
let mut env = terminal_env(&options.env);
|
||||
if let Some(msystem) = default_msystem(&shell, &options.env, std::env::var("MSYSTEM").ok().as_deref()) {
|
||||
env.insert("MSYSTEM".to_owned(), msystem.to_owned());
|
||||
@@ -109,8 +105,7 @@ impl TerminalManager {
|
||||
}
|
||||
let mut cmd = CommandBuilder::new(&shell);
|
||||
cmd.args(&args);
|
||||
// wsl.exe takes the directory through `--cd`; a UNC share is no valid process cwd.
|
||||
cmd.cwd(if wsl.is_some() { resolve_cwd(Path::new("")) } else { resolve_cwd(&options.cwd) });
|
||||
cmd.cwd(resolve_cwd(&options.cwd));
|
||||
for (k, v) in ide_core::process::host_env_fixes() {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
@@ -141,34 +136,25 @@ impl TerminalManager {
|
||||
writer: Mutex::new(writer),
|
||||
killer: Mutex::new(child.clone_killer()),
|
||||
exited: exited.clone(),
|
||||
started: Instant::now(),
|
||||
input_logged: AtomicBool::new(false),
|
||||
});
|
||||
self.sessions.lock().insert(id, session);
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Msg>();
|
||||
let spawned = spawn_reader(id, reader, tx.clone())
|
||||
.and_then(|_| spawn_waiter(id, child, tx))
|
||||
.and_then(|_| spawn_pump(id, rx, on_output, exited, self.sessions.clone(), sink, Instant::now()));
|
||||
.and_then(|_| spawn_pump(id, rx, on_output, exited, self.sessions.clone(), sink));
|
||||
if let Err(e) = spawned {
|
||||
if let Some(s) = self.sessions.lock().remove(&id) {
|
||||
let _ = s.killer.lock().kill();
|
||||
}
|
||||
return Err(IdeError::internal(format!("failed to start terminal threads: {e}")));
|
||||
}
|
||||
// Info level, with the first output and input below: a session that starts but never shows a
|
||||
// prompt can then be told apart in a user's log (no output, or no reply to the shell's query).
|
||||
tracing::info!(%id, shell, pid = ?info.pid, cols = size.cols, rows = size.rows, "terminal spawned");
|
||||
tracing::debug!(%id, shell, pid = ?info.pid, "terminal spawned");
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
pub fn write(&self, id: TerminalId, data: &str) -> IdeResult<()> {
|
||||
let session = self.session(id)?;
|
||||
if !session.input_logged.swap(true, Ordering::Relaxed) {
|
||||
let cursor_report = data.starts_with("\x1b[") && data.ends_with('R');
|
||||
let ms = session.started.elapsed().as_millis();
|
||||
tracing::info!(%id, ms, bytes = data.len(), cursor_report, "terminal first input");
|
||||
}
|
||||
let mut w = session.writer.lock();
|
||||
w.write_all(data.as_bytes())?;
|
||||
w.flush()?;
|
||||
@@ -401,19 +387,8 @@ fn spawn_pump(
|
||||
exited: Arc<AtomicBool>,
|
||||
sessions: Sessions,
|
||||
sink: SharedSink,
|
||||
started: Instant,
|
||||
) -> std::io::Result<()> {
|
||||
std::thread::Builder::new().name(format!("openidea-term-pump-{}", id.0)).spawn(move || {
|
||||
let first_output = std::cell::Cell::new(true);
|
||||
let on_output = move |text: String| {
|
||||
if first_output.replace(false) {
|
||||
// ConPTY asks for the cursor position (`ESC[6n`) and waits for the answer.
|
||||
let cursor_query = text.contains("\x1b[6n");
|
||||
let ms = started.elapsed().as_millis();
|
||||
tracing::info!(%id, ms, bytes = text.len(), cursor_query, "terminal first output");
|
||||
}
|
||||
on_output(text)
|
||||
};
|
||||
let mut decoder = Utf8Decoder::new();
|
||||
let mut pending = String::new();
|
||||
let mut batch_started: Option<Instant> = None;
|
||||
@@ -481,16 +456,6 @@ fn pty_size(cols: u16, rows: u16) -> PtySize {
|
||||
}
|
||||
}
|
||||
|
||||
/// `wsl.exe` in the distro of a `\\wsl.localhost\...` folder, so its terminal is a Linux
|
||||
/// shell and not PowerShell (#925). An explicitly chosen shell or arguments win.
|
||||
fn wsl_shell(options: &TerminalOptions) -> Option<(String, Vec<String>)> {
|
||||
if options.shell.as_deref().is_some_and(|s| !s.trim().is_empty()) || !options.args.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let w = ide_core::wsl::parse(&options.cwd)?;
|
||||
Some((ide_core::wsl::EXE.into(), vec!["-d".into(), w.distro, "--cd".into(), w.path]))
|
||||
}
|
||||
|
||||
fn resolve_cwd(cwd: &Path) -> PathBuf {
|
||||
if cwd.is_dir() {
|
||||
return cwd.to_path_buf();
|
||||
@@ -539,7 +504,7 @@ pub fn available_shells() -> Vec<String> {
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
for exe in ["pwsh.exe", "powershell.exe", "cmd.exe", ide_core::wsl::EXE] {
|
||||
for exe in ["pwsh.exe", "powershell.exe", "cmd.exe", "wsl.exe"] {
|
||||
if let Some(p) = find_in_path(exe) {
|
||||
add(p);
|
||||
}
|
||||
@@ -894,24 +859,6 @@ mod tests {
|
||||
assert!(h.events.try_recv().is_err() && other_events.try_recv().is_err(), "no cross delivery");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_folder_gets_the_distro_shell_unless_one_is_chosen() {
|
||||
let mut o = sh("true");
|
||||
o.shell = None;
|
||||
o.args = vec![];
|
||||
let (distro, linux_path) = ("Debian-12", "/srv/app");
|
||||
let want = (ide_core::wsl::EXE.to_owned(), vec!["-d".into(), distro.into(), "--cd".into(), linux_path.into()]);
|
||||
for host in ["wsl.localhost", "wsl$"] {
|
||||
o.cwd = PathBuf::from(format!(r"\\{host}\{distro}{}", linux_path.replace('/', r"\"))).into();
|
||||
assert_eq!(wsl_shell(&o), Some(want.clone()), "{host}");
|
||||
}
|
||||
o.shell = Some("pwsh.exe".into());
|
||||
assert_eq!(wsl_shell(&o), None);
|
||||
o.shell = None;
|
||||
o.cwd = PathBuf::from("/tmp").into();
|
||||
assert_eq!(wsl_shell(&o), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_resolution() {
|
||||
let (shell, args) = resolve_shell(Some("/bin/zsh"), &[]);
|
||||
|
||||
@@ -124,7 +124,7 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
|
||||
if !fs::metadata(dir)?.is_dir() {
|
||||
return Err(IdeError::invalid(format!("{} is not a directory", dir.display())));
|
||||
}
|
||||
let gitignore = rules::GitignoreStack::cached(dir);
|
||||
let gitignore = rules::GitignoreStack::new(dir);
|
||||
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
|
||||
let excludes = ExcludeMatcher::new(excludes);
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ use parking_lot::{Mutex, RwLock};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
/// Exclude globs from settings (`files.exclude`), e.g. `**/node_modules`.
|
||||
///
|
||||
@@ -73,14 +72,6 @@ pub(crate) fn find_repo_root(start: &Path) -> Option<PathBuf> {
|
||||
start.ancestors().find(|dir| dir.join(".git").exists()).map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// `info/exclude` of the repository at `root` (shared by its worktrees).
|
||||
fn exclude_path(root: &Path) -> PathBuf {
|
||||
gix::discover(root)
|
||||
.ok()
|
||||
.map(|r| r.common_dir().join("info/exclude"))
|
||||
.unwrap_or_else(|| root.join(".git/info/exclude"))
|
||||
}
|
||||
|
||||
/// Layered gitignore matching: per-directory `.gitignore` / `.ignore` from the
|
||||
/// path's directory up to the repository root (or the file system root when
|
||||
/// not in a repository), then `.git/info/exclude` and the global excludes file.
|
||||
@@ -92,29 +83,6 @@ pub(crate) struct GitignoreStack {
|
||||
nested: Mutex<HashMap<PathBuf, Option<Arc<GitignoreStack>>>>,
|
||||
}
|
||||
|
||||
/// How long [`GitignoreStack::cached`] reuses the repository lookup of a directory.
|
||||
const REPO_LEVEL_TTL: Duration = Duration::from_secs(3);
|
||||
|
||||
/// What changes when `.git/info/exclude` is edited.
|
||||
type Stamp = Option<(SystemTime, u64)>;
|
||||
|
||||
struct RepoLevel {
|
||||
at: Instant,
|
||||
repo_root: Option<PathBuf>,
|
||||
/// `<common dir>/info/exclude`, found by a repository discovery.
|
||||
exclude: Option<PathBuf>,
|
||||
stamp: Stamp,
|
||||
rules: Vec<Gitignore>,
|
||||
}
|
||||
|
||||
/// Repo-level rules by the directory they were looked up for.
|
||||
static REPO_LEVEL: Mutex<Option<HashMap<PathBuf, Arc<RepoLevel>>>> = Mutex::new(None);
|
||||
|
||||
fn stamp_of(file: Option<&Path>) -> Stamp {
|
||||
let meta = std::fs::metadata(file?).ok()?;
|
||||
Some((meta.modified().ok()?, meta.len()))
|
||||
}
|
||||
|
||||
impl GitignoreStack {
|
||||
pub fn new(near: &Path) -> Self {
|
||||
let repo_root = find_repo_root(near);
|
||||
@@ -122,52 +90,15 @@ impl GitignoreStack {
|
||||
Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
|
||||
}
|
||||
|
||||
/// [`new`](Self::new) for listing a directory over and over (expanding a tree, a slow share):
|
||||
/// the walk up to the repository root and the repository discovery are reused for
|
||||
/// [`REPO_LEVEL_TTL`]. An edit of `.git/info/exclude` is still seen at once (its mtime and size
|
||||
/// are checked), as is any `.gitignore` / `.ignore`, which are read fresh. Only a repository
|
||||
/// created in the directory, or a change of the global excludes file, can lag by the TTL.
|
||||
pub fn cached(near: &Path) -> Self {
|
||||
let now = Instant::now();
|
||||
let hit = REPO_LEVEL
|
||||
.lock()
|
||||
.as_ref()
|
||||
.and_then(|m| m.get(near))
|
||||
.cloned()
|
||||
.filter(|e| now.duration_since(e.at) < REPO_LEVEL_TTL && stamp_of(e.exclude.as_deref()) == e.stamp);
|
||||
let entry = hit.unwrap_or_else(|| {
|
||||
let repo_root = find_repo_root(near);
|
||||
let exclude = repo_root.as_deref().map(exclude_path);
|
||||
let entry = Arc::new(RepoLevel {
|
||||
at: now,
|
||||
stamp: stamp_of(exclude.as_deref()),
|
||||
rules: Self::load_repo_level_from(repo_root.as_deref(), exclude.as_deref()),
|
||||
repo_root,
|
||||
exclude,
|
||||
});
|
||||
let mut guard = REPO_LEVEL.lock();
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
map.retain(|_, e| now.duration_since(e.at) < REPO_LEVEL_TTL);
|
||||
map.insert(near.to_path_buf(), entry.clone());
|
||||
entry
|
||||
});
|
||||
Self {
|
||||
repo_root: entry.repo_root.clone(),
|
||||
repo_level: RwLock::new(entry.rules.clone()),
|
||||
cache: Mutex::default(),
|
||||
nested: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn load_repo_level(repo_root: Option<&Path>) -> Vec<Gitignore> {
|
||||
Self::load_repo_level_from(repo_root, repo_root.map(exclude_path).as_deref())
|
||||
}
|
||||
|
||||
fn load_repo_level_from(repo_root: Option<&Path>, exclude: Option<&Path>) -> Vec<Gitignore> {
|
||||
let mut repo_level = Vec::new();
|
||||
if let Some(root) = repo_root {
|
||||
let mut builder = GitignoreBuilder::new(root);
|
||||
if let Some(exclude) = exclude.filter(|f| f.is_file()) {
|
||||
let exclude = gix::discover(root)
|
||||
.ok()
|
||||
.map(|r| r.common_dir().join("info/exclude"))
|
||||
.unwrap_or_else(|| root.join(".git/info/exclude"));
|
||||
if exclude.is_file() {
|
||||
builder.add(exclude);
|
||||
}
|
||||
if let Ok(gi) = builder.build()
|
||||
@@ -188,9 +119,6 @@ impl GitignoreStack {
|
||||
|
||||
/// Re-reads `.git/info/exclude` and the global excludes file.
|
||||
pub fn reload_repo_level(&self) {
|
||||
if let (Some(root), Some(map)) = (&self.repo_root, REPO_LEVEL.lock().as_mut()) {
|
||||
map.retain(|dir, _| !dir.starts_with(root));
|
||||
}
|
||||
self.nested.lock().clear();
|
||||
*self.repo_level.write() = Self::load_repo_level(self.repo_root.as_deref());
|
||||
}
|
||||
@@ -370,39 +298,4 @@ mod tests {
|
||||
assert!(anchored.is_excluded(Path::new("build/out.o")));
|
||||
assert!(!anchored.is_excluded(Path::new("web/build/out.o")));
|
||||
}
|
||||
|
||||
fn repo_with_exclude(rule: &str) -> tempfile::TempDir {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join(".git/info")).unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
|
||||
std::fs::write(tmp.path().join(".git/info/exclude"), rule).unwrap();
|
||||
tmp
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_stack_sees_every_edit_of_the_ignore_files_at_once() {
|
||||
let tmp = repo_with_exclude("secret.txt\n");
|
||||
let (src, secret, note) =
|
||||
(tmp.path().join("src"), tmp.path().join("src/secret.txt"), tmp.path().join("src/note.md"));
|
||||
assert!(GitignoreStack::cached(&src).is_ignored(&secret, false));
|
||||
assert!(!GitignoreStack::cached(&src).is_ignored(¬e, false));
|
||||
std::fs::write(src.join(".gitignore"), "*.md\n").unwrap();
|
||||
assert!(GitignoreStack::cached(&src).is_ignored(¬e, false), "directory .gitignore");
|
||||
std::fs::write(tmp.path().join(".git/info/exclude"), "").unwrap();
|
||||
assert!(!GitignoreStack::cached(&src).is_ignored(&secret, false), "info/exclude");
|
||||
std::fs::write(tmp.path().join(".git/info/exclude"), "note.md\nsecret.txt\n").unwrap();
|
||||
assert!(GitignoreStack::cached(&src).is_ignored(&secret, false), "info/exclude again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_stack_reuses_the_repository_lookup() {
|
||||
let tmp = repo_with_exclude("");
|
||||
let src = tmp.path().join("src");
|
||||
let first = GitignoreStack::cached(&src);
|
||||
let entry = REPO_LEVEL.lock().as_ref().unwrap().get(&src).unwrap().clone();
|
||||
let again = GitignoreStack::cached(&src);
|
||||
assert!(Arc::ptr_eq(&entry, REPO_LEVEL.lock().as_ref().unwrap().get(&src).unwrap()));
|
||||
assert_eq!(first.repo_root(), again.repo_root());
|
||||
assert_eq!(again.repo_root(), Some(tmp.path()));
|
||||
}
|
||||
}
|
||||
@@ -130,15 +130,14 @@ install it from disk.
|
||||
Only port themes whose licence allows redistribution, keep their licence file,
|
||||
and credit the original authors in `authors` and `description`.
|
||||
|
||||
### From JetBrains IDEs (automatic)
|
||||
### From IntelliJ IDEA (automatic)
|
||||
|
||||
To use a theme you already have in a JetBrains IDE, open **Settings › Plugins**, gear
|
||||
To use a theme you already have in IntelliJ, open **Settings › Plugins**, gear
|
||||
menu:
|
||||
|
||||
- **Import Theme from JetBrains IDE…** lists the theme plugins installed in the
|
||||
JetBrains IDEs (and Android Studio) on this computer, one row per plugin of
|
||||
each IDE, the plugins of the themes the IDEs use first. It reads the settings
|
||||
folder of each IDE's newest version: `~/Library/Application Support/JetBrains`
|
||||
- **Import Theme from IntelliJ IDE…** lists the theme plugins installed in the
|
||||
JetBrains IDEs (and Android Studio) on this computer, the theme each IDE uses
|
||||
first. It reads their settings folders: `~/Library/Application Support/JetBrains`
|
||||
(macOS), `%APPDATA%\JetBrains` (Windows), `~/.config/JetBrains` and
|
||||
`~/.local/share/JetBrains` (Linux).
|
||||
- **Import IntelliJ Theme from File…** takes a theme plugin downloaded from the
|
||||
@@ -147,8 +146,8 @@ menu:
|
||||
|
||||
The whole plugin becomes one OpenIDEA theme plugin, `intellij.<plugin id>`, with
|
||||
each of its themes and their editor schemes; it is installed through the usual
|
||||
install page, and the theme in use stays as it is: choose one of its themes in
|
||||
**Settings › Appearance › Theme**. Importing the plugin again replaces it. Both are actions too (`plugins.importIntellijTheme`,
|
||||
install page and the chosen theme (otherwise the first) is applied. Importing
|
||||
the plugin again replaces it. Both are actions too (`plugins.importIntellijTheme`,
|
||||
`plugins.importInstalledIntellijTheme`). The conversion is the one described
|
||||
below.
|
||||
|
||||
|
||||
@@ -186,49 +186,3 @@ test("quick theme menu offers all four palettes and applies their kind", async (
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", palette.kind);
|
||||
}
|
||||
});
|
||||
|
||||
test("gear › Theme previews the theme under the pointer and keeps the one chosen", async ({ workbench: page }) => {
|
||||
const html = page.locator("html");
|
||||
const gear = page.getByRole("button", { name: "IDE and Project Settings", exact: true });
|
||||
const theme = (label: string) => page.getByRole("menuitemcheckbox", { name: label, exact: true });
|
||||
await gear.click();
|
||||
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
|
||||
await theme("Solarized Dark").hover();
|
||||
await expect(html).toHaveAttribute("data-color-theme", "solarized-dark");
|
||||
// A plugin's theme previews too.
|
||||
await theme("Harbor Night").hover();
|
||||
await expect(html).toHaveAttribute("data-plugin-theme", /harbor-night$/);
|
||||
await expect(html).not.toHaveAttribute("data-color-theme");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(html).not.toHaveAttribute("data-plugin-theme");
|
||||
await expect(html).toHaveAttribute("data-theme", "light");
|
||||
|
||||
await gear.click();
|
||||
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
|
||||
await theme("One Dark").hover();
|
||||
await expect(html).toHaveAttribute("data-color-theme", "one-dark");
|
||||
await theme("One Dark").click();
|
||||
await expect(html).toHaveAttribute("data-color-theme", "one-dark");
|
||||
// Chosen, not previewed: the next start-up opens with it.
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("openidea.theme") ?? "{}").colorTheme))
|
||||
.toBe("one-dark");
|
||||
});
|
||||
|
||||
test("Settings › Appearance › Theme previews the highlighted theme until Cancel", async ({ workbench: page }) => {
|
||||
const html = page.locator("html");
|
||||
const dialog = await settings(page);
|
||||
await page.getByRole("button", { name: "Theme", exact: true }).click();
|
||||
await page.getByRole("option", { name: "Solarized Dark", exact: true }).hover();
|
||||
await expect(html).toHaveAttribute("data-color-theme", "solarized-dark");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(html).toHaveAttribute("data-theme", "light");
|
||||
await expect(html).not.toHaveAttribute("data-color-theme");
|
||||
// Picked: it shows until Apply or Cancel.
|
||||
await choose(page, "Theme", "One Dark");
|
||||
await expect(html).toHaveAttribute("data-color-theme", "one-dark");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(html).toHaveAttribute("data-theme", "light");
|
||||
await expect(html).not.toHaveAttribute("data-color-theme");
|
||||
});
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.37",
|
||||
"version": "0.1.36",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -769,7 +769,7 @@ granted, and starts the approved program.
|
||||
the package at its root or in its only folder, or a folder's `plugin.toml`;
|
||||
a zip without a `plugin.toml` there, such as an IntelliJ plugin, is refused; IntelliJ
|
||||
theme plugins are imported instead: _Import IntelliJ Theme from File…_ and _Import Theme
|
||||
from JetBrains IDE…_, see [`docs/plugins/themes.md`](../docs/plugins/themes.md)). The install
|
||||
from IntelliJ IDE…_, see [`docs/plugins/themes.md`](../docs/plugins/themes.md)). The install
|
||||
page lists every capability and whether the package is signed by a publisher
|
||||
the marketplace trusts; nothing is copied until you accept.
|
||||
- **Versions:** installed plugins live in `<app-data>/plugins/<id>/<version>/`
|
||||
|
||||
@@ -220,6 +220,11 @@ describe("IntelliJ theme import", () => {
|
||||
],
|
||||
});
|
||||
expect(pkg.id).toBe("intellij.com-example-deepsea");
|
||||
expect(pkg.themes).toEqual([
|
||||
{ id: "deep-sea", sourceId: "deep-sea-id", name: "Deep Sea" },
|
||||
{ id: "deep-sea-2", sourceId: "copy-id", name: "Deep Sea" },
|
||||
{ id: "shallow", sourceId: "light-id", name: "Shallow" },
|
||||
]);
|
||||
expect(pkg.files.map((f) => f.path)).toEqual([
|
||||
"plugin.toml",
|
||||
"themes/deep-sea.theme.json",
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
use types.{error, extension};
|
||||
|
||||
record action-performed {
|
||||
/// Action id (`editor.duplicate-line`).
|
||||
action: string,
|
||||
title: string,
|
||||
/// How the user started it: `keyboard`, `menu`, `toolbar`,
|
||||
/// `context-menu`, `search` or `other` (more may be added).
|
||||
source: string,
|
||||
/// Its keyboard shortcut, when it has one (`Ctrl+D`).
|
||||
shortcut: option<string>,
|
||||
}
|
||||
|
||||
variant event {
|
||||
file-opened(string),
|
||||
file-saved(string),
|
||||
editor-focused(option<string>),
|
||||
action-performed(action-performed),
|
||||
vcs-changed(string),
|
||||
scheduled,
|
||||
/// A kind added after 1.0 (subscribed to by its name).
|
||||
other(extension),
|
||||
}
|
||||
|
||||
/// Delivers `kind` events from now on, for the rest of the session (also
|
||||
/// across idle reclaim: an event activates the plugin again). Declare
|
||||
/// `activation = ["on-event:<kind>"]` to get them before first use.
|
||||
/// Kinds: `file-opened`, `file-saved`, `editor-focused` (the focused editor
|
||||
/// changed), `vcs-changed` (a repository's state changed: commit,
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran) and
|
||||
/// `scheduled` (the `on-schedule` period elapsed); later IDEs add more,
|
||||
/// and an IDE that doesn't know one fails with `invalid`.
|
||||
/// Requires `events` (`events.input` for `action-performed`).
|
||||
subscribe: func(kind: string) -> result<_, error>;
|
||||
unsubscribe: func(kind: string);
|
||||
}
|
||||
|
||||
/// Long-running work with a progress indicator. While a task is open, the
|
||||
/// call that began it may run for the background budget (60 s) instead of 5 s.
|
||||
interface tasks {
|
||||
resource task {
|
||||
/// `done` of `total` units (`none`: indeterminate), with a short status.
|
||||
report: func(done: u32, total: option<u32>, message: option<string>);
|
||||
/// The user cancelled it: stop soon and return.
|
||||
is-cancelled: func() -> bool;
|
||||
}
|
||||
|
||||
/// Starts a task shown in the status bar; dropping it ends it.
|
||||
begin: func(title: string, cancellable: bool) -> task;
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
/// Called once after the instance is created: subscribe to events and
|
||||
/// restore state from `storage`. Contributions (commands, languages,
|
||||
/// themes, …) are declared in plugin.toml, not registered here.
|
||||
/// An error fails the activation (shown on the plugin's page).
|
||||
activate: func(ctx: context) -> result<_, error>;
|
||||
/// Called before the instance is dropped (disable, uninstall, idle reclaim).
|
||||
deactivate: func();
|
||||
}
|
||||
|
||||
interface commands {
|
||||
use types.{error};
|
||||
use invocation.{invocation};
|
||||
|
||||
/// Runs one of the plugin's commands. Returns an optional message.
|
||||
/// `cancelled` (the user gave up) and `denied` (a capability is missing)
|
||||
/// are not counted as the plugin failing.
|
||||
run: func(id: string, ctx: borrow<invocation>, arg: option<string>) -> result<option<string>, error>;
|
||||
}
|
||||
|
||||
interface event-handler {
|
||||
use events.{event};
|
||||
use invocation.{invocation};
|
||||
|
||||
/// A batch of subscribed events, oldest first, from one window (`ctx`).
|
||||
handle: func(events: list<event>, ctx: borrow<invocation>);
|
||||
}
|
||||
|
||||
/// Optional export (world `plugin-syntax`): syntax of the plugin's own
|
||||
/// languages, for languages the IDE has no grammar for. The IDE calls it
|
||||
/// with the whole document; results are flat. Offsets are UTF-8 byte offsets
|
||||
/// into `text` (the IDE converts them); lines are 0-based.
|
||||
interface syntax-provider {
|
||||
/// One highlighted range. `kind` is a highlight category: keyword, string,
|
||||
/// string-special, escape, regexp, atom, number, constant, comment,
|
||||
/// doc-comment, function, function-call, builtin, type, namespace,
|
||||
/// variable, self-variable, property, attribute, macro, label, tag,
|
||||
/// operator, punctuation. Unknown kinds are ignored; ranges must be
|
||||
/// sorted and not overlap.
|
||||
record token {
|
||||
start: u32,
|
||||
end: u32,
|
||||
kind: string,
|
||||
}
|
||||
|
||||
/// A symbol of the structure view. `parent` is the index of the enclosing
|
||||
/// symbol in the same list (which must come first).
|
||||
record symbol {
|
||||
name: string,
|
||||
detail: option<string>,
|
||||
/// class, interface, struct, enum, function, method, constructor,
|
||||
/// field, property, variable, constant, module, namespace, event, …
|
||||
kind: string,
|
||||
start: u32,
|
||||
end: u32,
|
||||
name-start: u32,
|
||||
name-end: u32,
|
||||
parent: option<u32>,
|
||||
}
|
||||
|
||||
/// A foldable line range. `kind`: region, comment or imports.
|
||||
record fold {
|
||||
start-line: u32,
|
||||
end-line: u32,
|
||||
kind: string,
|
||||
}
|
||||
|
||||
highlights: func(language: string, text: string) -> list<token>;
|
||||
outline: func(language: string, text: string) -> list<symbol>;
|
||||
folding: func(language: string, text: string) -> list<fold>;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
use types.{log-level};
|
||||
|
||||
log: func(level: log-level, message: string);
|
||||
}
|
||||
|
||||
interface ui {
|
||||
use types.{notification-level};
|
||||
|
||||
record status-item {
|
||||
text: string,
|
||||
tooltip: option<string>,
|
||||
/// One of the plugin's commands, run when the item is clicked.
|
||||
command: option<string>,
|
||||
}
|
||||
|
||||
/// Shows a notification balloon in the window the current command or
|
||||
/// event came from (every window when there is none).
|
||||
show-notification: func(level: notification-level, title: string, body: string);
|
||||
/// Shows or updates the plugin's status bar item `id` in every window.
|
||||
set-status-item: func(id: string, item: status-item);
|
||||
remove-status-item: func(id: string);
|
||||
}
|
||||
|
||||
/// Persistent key-value storage of the plugin (survives restarts and idle
|
||||
/// reclaim; instance memory does not). Requires `storage`. At most 1 MiB.
|
||||
interface storage {
|
||||
use types.{error};
|
||||
|
||||
get: func(key: string) -> result<option<string>, error>;
|
||||
set: func(key: string, value: string) -> result<_, error>;
|
||||
delete: func(key: string) -> result<_, error>;
|
||||
/// Keys starting with `prefix`, sorted.
|
||||
keys: func(prefix: string) -> result<list<string>, error>;
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
use types.{error, range, location};
|
||||
|
||||
enum severity {
|
||||
error,
|
||||
warning,
|
||||
info,
|
||||
hint,
|
||||
}
|
||||
|
||||
/// Another place that explains a diagnostic (the earlier declaration, say).
|
||||
record related-information {
|
||||
location: location,
|
||||
message: string,
|
||||
}
|
||||
|
||||
record diagnostic {
|
||||
range: range,
|
||||
severity: severity,
|
||||
message: string,
|
||||
/// Rule or check id (`LineLength`).
|
||||
code: option<string>,
|
||||
/// The tool that found it, when not the plugin itself (`checkstyle`).
|
||||
source: option<string>,
|
||||
/// `unnecessary` (shown faded) and `deprecated` (struck through); unknown ones are ignored.
|
||||
tags: list<string>,
|
||||
related: list<related-information>,
|
||||
}
|
||||
|
||||
/// Replaces the plugin's diagnostics for the file at `path` (absolute, in
|
||||
/// an open project); an empty list clears them. Requires `project.read`.
|
||||
publish: func(path: string, diagnostics: list<diagnostic>) -> result<_, error>;
|
||||
}
|
||||
|
||||
/// HTTP(S) to the hosts granted with `net:<host>`.
|
||||
interface net {
|
||||
use types.{error};
|
||||
|
||||
record header {
|
||||
name: string,
|
||||
value: string,
|
||||
}
|
||||
|
||||
record request {
|
||||
method: string,
|
||||
/// `https://…`; plain `http://` only to `localhost` / `127.0.0.1`.
|
||||
url: string,
|
||||
/// `{{secret:<name>}}` in a value is replaced by the plugin's secret
|
||||
/// `name` on the way out (requires `secrets`); the plugin never sees it.
|
||||
headers: list<header>,
|
||||
body: option<list<u8>>,
|
||||
/// Default 30 s; the call's own budget applies too.
|
||||
timeout-ms: option<u32>,
|
||||
}
|
||||
|
||||
record response {
|
||||
status: u16,
|
||||
headers: list<header>,
|
||||
/// At most 8 MiB.
|
||||
body: list<u8>,
|
||||
}
|
||||
|
||||
/// Fails with `denied` for a host the plugin may not reach, `cancelled`
|
||||
/// when a newer request replaced the call or the user cancelled.
|
||||
fetch: func(req: request) -> result<response, error>;
|
||||
}
|
||||
|
||||
/// Secrets the user stored for the plugin (Settings › Plugins, kept in the
|
||||
/// OS keychain). Plugins only use them through `{{secret:<name>}}` in
|
||||
/// `net` requests. Requires `secrets`.
|
||||
interface secrets {
|
||||
is-set: func(name: string) -> bool;
|
||||
}
|
||||
|
||||
/// One-off runs of programs granted with `process:<program>` (the file the
|
||||
/// user approved, checked before every run).
|
||||
interface process {
|
||||
use types.{error};
|
||||
use workspace.{project};
|
||||
|
||||
record output {
|
||||
/// `none` when killed by a signal.
|
||||
status: option<s32>,
|
||||
/// At most 4 MiB each (the rest is dropped).
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
}
|
||||
|
||||
/// Runs `program` with `args` in `cwd`'s root (else the plugin's data
|
||||
/// directory) and waits; cancelled with the task or call. Call it inside
|
||||
/// a task for anything slow.
|
||||
run: func(program: string, args: list<string>, cwd: option<borrow<project>>, stdin: option<string>) -> result<output, error>;
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/// OpenIDEA plugin API, version 1.0. Once released, 1.x only adds (new
|
||||
/// interfaces, new optional exports; plugins/README.md, "Evolving the plugin
|
||||
/// API"); a 2.0 keeps 1.0 running through an adapter in the host.
|
||||
///
|
||||
/// A plugin is a WebAssembly component targeting the `plugin` world (or
|
||||
/// `plugin-syntax`). It runs sandboxed: no filesystem, network, environment
|
||||
/// or processes beyond WASI's clocks and randomness; everything else goes
|
||||
/// through the imports below, gated by the capabilities granted in
|
||||
/// `plugin.toml` (a missing one returns `error::denied`).
|
||||
package openidea:[email protected];
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
import ui;
|
||||
import storage;
|
||||
import workspace;
|
||||
import editor;
|
||||
import invocation;
|
||||
import vcs;
|
||||
import events;
|
||||
import tasks;
|
||||
import diagnostics;
|
||||
import net;
|
||||
import secrets;
|
||||
import process;
|
||||
import views;
|
||||
import settings;
|
||||
|
||||
export lifecycle;
|
||||
export commands;
|
||||
export event-handler;
|
||||
}
|
||||
|
||||
/// A plugin that also provides syntax for its languages.
|
||||
world plugin-syntax {
|
||||
include plugin;
|
||||
export syntax-provider;
|
||||
}
|
||||
|
||||
/// A plugin with editor providers (`[[contributes.providers]]`).
|
||||
world plugin-providers {
|
||||
include plugin;
|
||||
export providers;
|
||||
}
|
||||
|
||||
/// A plugin with views or custom editors (`[[contributes.views]]`,
|
||||
/// `[[contributes.custom-editors]]`).
|
||||
world plugin-views {
|
||||
include plugin;
|
||||
export view-provider;
|
||||
}
|
||||
|
||||
/// Only the `syntax-provider` export: guests generate it next to `plugin`
|
||||
/// (the component tools merge both into one component).
|
||||
world syntax {
|
||||
export syntax-provider;
|
||||
}
|
||||
|
||||
/// Only the `providers` export, generated next to `plugin` like `syntax`.
|
||||
world editor-providers {
|
||||
export providers;
|
||||
}
|
||||
|
||||
/// Only the `view-provider` export, generated next to `plugin` like `syntax`.
|
||||
world views-provider {
|
||||
export view-provider;
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
/// on the editing path: a result later than ~50 ms is dropped, a call still
|
||||
/// running at 500 ms is interrupted.
|
||||
interface providers {
|
||||
use types.{error, position, range, text-edit, location};
|
||||
|
||||
/// The document a request is about.
|
||||
record document {
|
||||
path: string,
|
||||
language: string,
|
||||
version: u64,
|
||||
text: string,
|
||||
}
|
||||
|
||||
record completion-item {
|
||||
label: string,
|
||||
detail: option<string>,
|
||||
/// Icon and sort group: text, method, function, constructor, field,
|
||||
/// variable, class, interface, module, property, unit, value, enum,
|
||||
/// keyword, snippet, color, file, reference, folder, enum-member,
|
||||
/// constant, struct, event, operator or type-parameter. Unknown kinds
|
||||
/// show no icon.
|
||||
kind: option<string>,
|
||||
/// With `snippet`, tab stops and placeholders (`$1`, `${1:name}`, `$0`).
|
||||
insert-text: string,
|
||||
snippet: bool,
|
||||
/// Replaced on accept; `none`: the word at the caret.
|
||||
replace: option<range>,
|
||||
sort-text: option<string>,
|
||||
/// Matched against what was typed instead of `label`.
|
||||
filter-text: option<string>,
|
||||
documentation: option<string>,
|
||||
/// Applied with the item elsewhere in the document (an import).
|
||||
additional-edits: list<text-edit>,
|
||||
}
|
||||
|
||||
record inline-suggestion {
|
||||
insert-text: string,
|
||||
/// Replaced range; `none` inserts at the caret.
|
||||
replace: option<range>,
|
||||
}
|
||||
|
||||
record file-edit {
|
||||
path: string,
|
||||
edits: list<text-edit>,
|
||||
}
|
||||
|
||||
record code-action {
|
||||
title: string,
|
||||
/// `quickfix`, `refactor`, …
|
||||
kind: option<string>,
|
||||
preferred: bool,
|
||||
edits: list<file-edit>,
|
||||
/// The plugin's own reference: with it and no `edits`, the edits are
|
||||
/// computed by `resolve-code-action` once the user picks the action.
|
||||
data: option<string>,
|
||||
}
|
||||
|
||||
record line-marker {
|
||||
line: u32,
|
||||
/// Gutter icon: `navigate` (default), `implemented`, `implementing`, `run`.
|
||||
icon: option<string>,
|
||||
tooltip: string,
|
||||
/// Opened on click.
|
||||
target: option<location>,
|
||||
}
|
||||
|
||||
completion: func(doc: document, at: position, trigger: option<string>) -> list<completion-item>;
|
||||
/// Ghost text at the caret (typing replaces an older request: it is cancelled).
|
||||
inline-completion: func(doc: document, at: position) -> option<inline-suggestion>;
|
||||
/// Actions for `selection` (quick fixes for the plugin's own diagnostics).
|
||||
code-actions: func(doc: document, selection: range) -> list<code-action>;
|
||||
/// The edits of an action `code-actions` returned with `data`, when the
|
||||
/// user picks it (the command budget applies, not the editor's 50 ms).
|
||||
resolve-code-action: func(doc: document, action: code-action) -> result<code-action, error>;
|
||||
definition: func(doc: document, at: position) -> list<location>;
|
||||
line-markers: func(doc: document) -> list<line-marker>;
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
interface types {
|
||||
/// Why a host call failed. A capability that is not granted is reported
|
||||
/// as `denied`, so the plugin can degrade (0.1 trapped instead).
|
||||
variant error {
|
||||
/// Not granted; the payload names the capability (`editor.write`).
|
||||
denied(string),
|
||||
/// The document changed since the version the edit was made for.
|
||||
stale,
|
||||
not-found(string),
|
||||
invalid(string),
|
||||
/// Cancelled by the user, or the plugin is being stopped.
|
||||
cancelled,
|
||||
failed(string),
|
||||
}
|
||||
|
||||
enum log-level {
|
||||
trace,
|
||||
debug,
|
||||
info,
|
||||
warn,
|
||||
error,
|
||||
}
|
||||
|
||||
enum notification-level {
|
||||
info,
|
||||
warning,
|
||||
error,
|
||||
}
|
||||
|
||||
record position {
|
||||
line: u32,
|
||||
character: u32,
|
||||
}
|
||||
|
||||
record range {
|
||||
start: position,
|
||||
end: position,
|
||||
}
|
||||
|
||||
record text-edit {
|
||||
range: range,
|
||||
text: string,
|
||||
}
|
||||
|
||||
/// A range in a file (absolute path).
|
||||
record location {
|
||||
path: string,
|
||||
range: range,
|
||||
}
|
||||
|
||||
/// A case added after 1.0, carried by the `other` case of a variant that
|
||||
/// grows (events, view bodies, view events, form fields): its kind and its
|
||||
/// data as JSON. Whoever doesn't know the kind ignores it or shows a
|
||||
/// fallback; the SDKs decode the kinds they know.
|
||||
record extension {
|
||||
kind: string,
|
||||
data: string,
|
||||
}
|
||||
|
||||
/// Passed to `lifecycle.activate`.
|
||||
record context {
|
||||
plugin-id: string,
|
||||
plugin-version: string,
|
||||
/// Version of this API the host implements, e.g. "1.0".
|
||||
api-version: string,
|
||||
/// Capabilities granted to the plugin (`editor.write`, `process:git`, …).
|
||||
capabilities: list<string>,
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
/// `[[contributes.customEditors]]`. The plugin describes what to show; the
|
||||
/// IDE renders it with its own components (theme, keyboard, accessibility)
|
||||
/// and sends the user's actions back as `view-event`s. Nothing of the plugin
|
||||
/// runs in the WebView, except a `html` body, which is shown in a sandboxed
|
||||
/// frame that can only exchange messages with the plugin.
|
||||
interface view-types {
|
||||
use types.{extension};
|
||||
|
||||
record button {
|
||||
id: string,
|
||||
label: string,
|
||||
/// An IDE icon name (`refresh`, `add`, `remove`, `run`, …).
|
||||
icon: option<string>,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
/// A tree node; `parent` is the key of an earlier item (none: a root).
|
||||
record tree-item {
|
||||
key: string,
|
||||
parent: option<string>,
|
||||
label: string,
|
||||
icon: option<string>,
|
||||
/// Grey text after the label.
|
||||
detail: option<string>,
|
||||
/// Shows an expander even before its children are known
|
||||
/// (`expand` asks for them).
|
||||
expandable: bool,
|
||||
expanded: bool,
|
||||
}
|
||||
|
||||
record list-item {
|
||||
key: string,
|
||||
label: string,
|
||||
icon: option<string>,
|
||||
detail: option<string>,
|
||||
}
|
||||
|
||||
variant field-value {
|
||||
text(string),
|
||||
multiline(string),
|
||||
checkbox(bool),
|
||||
/// The options and the chosen one.
|
||||
choice(tuple<list<string>, string>),
|
||||
/// A field type added after 1.0 (an IDE that doesn't know it leaves it out).
|
||||
other(extension),
|
||||
}
|
||||
|
||||
record field {
|
||||
key: string,
|
||||
label: string,
|
||||
value: field-value,
|
||||
}
|
||||
|
||||
/// Rows `first-row`..`first-row + len(rows)` of `total-rows`: the IDE
|
||||
/// asks for the rows it shows (`viewport`), so large tables stay cheap.
|
||||
record table {
|
||||
columns: list<string>,
|
||||
total-rows: u32,
|
||||
first-row: u32,
|
||||
rows: list<list<string>>,
|
||||
editable: bool,
|
||||
}
|
||||
|
||||
variant body {
|
||||
/// A centred message (empty state, errors).
|
||||
message(string),
|
||||
tree(list<tree-item>),
|
||||
%list(list<list-item>),
|
||||
form(list<field>),
|
||||
table(table),
|
||||
/// HTML shown in a sandboxed frame: no scripts from elsewhere, no
|
||||
/// network, no IDE API. Its script talks to the plugin with
|
||||
/// `openidea.postMessage(text)` / `openidea.onMessage(fn)`.
|
||||
html(string),
|
||||
/// A body added after 1.0; an IDE that doesn't know it says it needs updating.
|
||||
other(extension),
|
||||
}
|
||||
|
||||
record view {
|
||||
toolbar: list<button>,
|
||||
body: body,
|
||||
/// A line below the body (counts, last refresh…).
|
||||
status: option<string>,
|
||||
}
|
||||
|
||||
/// The table rows the IDE shows.
|
||||
record viewport {
|
||||
first-row: u32,
|
||||
rows: u32,
|
||||
}
|
||||
|
||||
record cell-edit {
|
||||
row: u32,
|
||||
column: u32,
|
||||
value: string,
|
||||
}
|
||||
|
||||
variant view-event {
|
||||
/// A toolbar button.
|
||||
button(string),
|
||||
/// Double click / Enter on a tree or list item.
|
||||
activate(string),
|
||||
select(string),
|
||||
expand(string),
|
||||
collapse(string),
|
||||
/// A form field changed: key and new value (`true`/`false` for checkboxes).
|
||||
field(tuple<string, string>),
|
||||
cell(cell-edit),
|
||||
/// Insert an empty row before this one (the row count: append).
|
||||
insert-row(u32),
|
||||
delete-rows(list<u32>),
|
||||
/// From the `html` body's script.
|
||||
message(string),
|
||||
/// An event added after 1.0, from a body or field added after 1.0.
|
||||
other(extension),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a plugin's code can ask of its views.
|
||||
interface views {
|
||||
use types.{error};
|
||||
|
||||
/// The view (or every custom editor of that id) shows outdated content:
|
||||
/// the IDE renders it again.
|
||||
refresh: func(view: string);
|
||||
/// Sends a message to the script of a view's `html` body.
|
||||
post-message: func(view: string, message: string) -> result<_, error>;
|
||||
/// Opens a terminal tab in the window the call came from, running
|
||||
/// `program` (pinned by a `process:<program>` grant) with `args` in the
|
||||
/// project root: long-running output (logs) and interactive sessions.
|
||||
open-terminal: func(title: string, program: string, args: list<string>) -> result<_, error>;
|
||||
}
|
||||
|
||||
/// The plugin's own settings (`[contributes.settings]`), as the user set them
|
||||
/// (project over global) or the schema's default.
|
||||
interface settings {
|
||||
/// The value of `key` as JSON (`true`, `3`, `"text"`), none if unknown.
|
||||
get: func(key: string) -> option<string>;
|
||||
}
|
||||
|
||||
/// Optional export (world `plugin-views`): content of declared views and
|
||||
/// custom editors. For a custom editor, `ctx.editor()` is its document.
|
||||
interface view-provider {
|
||||
use view-types.{view, viewport, view-event};
|
||||
use invocation.{invocation};
|
||||
use types.{error};
|
||||
|
||||
render: func(view: string, viewport: option<viewport>, ctx: borrow<invocation>) -> result<view, error>;
|
||||
handle: func(view: string, event: view-event, ctx: borrow<invocation>) -> result<_, error>;
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
interface workspace {
|
||||
use types.{error};
|
||||
|
||||
/// A project open in the IDE.
|
||||
resource project {
|
||||
/// Absolute path of the project root. Requires `project.read`.
|
||||
root: func() -> result<string, error>;
|
||||
/// Reads a UTF-8 text file inside the project (absolute, or relative
|
||||
/// to the root); paths leaving the root are refused. Unsaved editor
|
||||
/// contents win over the disk. Requires `project.read`.
|
||||
read-file: func(path: string) -> result<string, error>;
|
||||
/// Project files whose root-relative path matches `glob` (`**/*Mapper.xml`),
|
||||
/// at most `limit`, as absolute paths. Ignored and excluded files are
|
||||
/// skipped. Requires `project.read`.
|
||||
find-files: func(glob: string, limit: u32) -> result<list<string>, error>;
|
||||
}
|
||||
|
||||
/// Projects open in any window. Requires `project.read`.
|
||||
projects: func() -> result<list<project>, error>;
|
||||
}
|
||||
|
||||
interface editor {
|
||||
use types.{error, range, text-edit};
|
||||
|
||||
record document {
|
||||
/// Grows with every change; edits name the version they were made for.
|
||||
version: u64,
|
||||
text: string,
|
||||
}
|
||||
|
||||
/// A file open in an editor.
|
||||
resource text-editor {
|
||||
/// Absolute path of the file.
|
||||
path: func() -> string;
|
||||
/// Language id (`rust`, `solidity`, …).
|
||||
language: func() -> string;
|
||||
/// Current version and text. Requires `editor.read`.
|
||||
document: func() -> result<document, error>;
|
||||
/// Selections when the command was invoked (a cursor is an empty
|
||||
/// range). Requires `editor.read`.
|
||||
selections: func() -> result<list<range>, error>;
|
||||
/// Applies `edits` as one undoable change, only if the document is
|
||||
/// still at `version` (else `stale`, and nothing changes). Ranges are
|
||||
/// in that version and must not overlap. Returns the new version.
|
||||
/// Requires `editor.write`.
|
||||
apply-edits: func(version: u64, edits: list<text-edit>) -> result<u64, error>;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a command or event comes from.
|
||||
interface invocation {
|
||||
use workspace.{project};
|
||||
use editor.{text-editor};
|
||||
|
||||
resource invocation {
|
||||
/// The window's project.
|
||||
project: func() -> option<project>;
|
||||
/// The window's focused editor.
|
||||
editor: func() -> option<text-editor>;
|
||||
}
|
||||
}
|
||||
|
||||
/// Git, for the repository containing a project.
|
||||
interface vcs {
|
||||
use types.{error};
|
||||
use workspace.{project};
|
||||
|
||||
record repository-status {
|
||||
/// Absolute path of the working tree root.
|
||||
root: string,
|
||||
/// `none` when HEAD is detached.
|
||||
branch: option<string>,
|
||||
commit: option<string>,
|
||||
upstream: option<string>,
|
||||
ahead: u32,
|
||||
behind: u32,
|
||||
/// Merge / rebase / cherry-pick in progress.
|
||||
operation: option<string>,
|
||||
/// Files with staged or unstaged changes.
|
||||
changed-files: u32,
|
||||
}
|
||||
|
||||
/// `none` when the project is not in a repository. Requires `vcs.read`.
|
||||
status: func(project: borrow<project>) -> result<option<repository-status>, error>;
|
||||
/// Fetches all remotes (pruning deleted branches). Requires `vcs.write`.
|
||||
/// Long-running: call it inside a task.
|
||||
fetch: func(project: borrow<project>) -> result<_, error>;
|
||||
}
|
||||
@@ -140,18 +140,12 @@ fn released_apis_are_unchanged() {
|
||||
for (key, was) in &release {
|
||||
match current.get(key) {
|
||||
None => broken.push(format!("{key}: removed (was {was})")),
|
||||
// A world may gain imports and exports; everything else stays as it was. Items are
|
||||
// compared without their `@version`: a later minor names them `@1.1.0`, and wasmtime
|
||||
// resolves the release's `@1.0.0` to it.
|
||||
// A world may gain imports and exports; everything else stays as it was.
|
||||
Some(now) if key.starts_with("world ") => {
|
||||
let had = |s: &str, part: &str| -> Vec<String> {
|
||||
let start = s.find(part).unwrap() + part.len();
|
||||
let end = s[start..].find(']').unwrap() + start;
|
||||
s[start..end]
|
||||
.split(", ")
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(|x| x.split('@').next().unwrap_or(x).to_owned())
|
||||
.collect()
|
||||
s[start..end].split(", ").filter(|x| !x.is_empty()).map(str::to_owned).collect()
|
||||
};
|
||||
for part in ["imports [", "exports ["] {
|
||||
let now = had(now, part);
|
||||
|
||||
@@ -74,9 +74,6 @@ ide-docker = { path = "../crates/ide-docker" }
|
||||
ide-android = { path = "../crates/ide-android" }
|
||||
ide-github = { path = "../crates/ide-github" }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6"
|
||||
# Plugin secrets in the login keychain.
|
||||
|
||||
@@ -49,7 +49,6 @@ pub mod window;
|
||||
pub mod window_drag;
|
||||
pub mod window_group;
|
||||
pub mod workspace;
|
||||
pub mod wsl;
|
||||
|
||||
use tauri_specta::collect_commands;
|
||||
|
||||
@@ -536,8 +535,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
db::db_set_ssh_secret,
|
||||
db::db_trust_ssh_host,
|
||||
ssh::ssh_test,
|
||||
wsl::wsl_distros,
|
||||
wsl::wsl_resolve,
|
||||
ssh::ssh_set_secret,
|
||||
ssh::ssh_needs_secret,
|
||||
ssh::ssh_trust_host,
|
||||
|
||||
@@ -52,17 +52,17 @@ pub async fn window_open_file_in_new_window(
|
||||
windows::open_file_in_new_window(&app, project, file)
|
||||
}
|
||||
|
||||
/// [`window_open_project`] for folder `path` of `target` (an SSH host or a WSL distribution;
|
||||
/// Remote Development); a new window connects itself.
|
||||
/// [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
/// `ssh_config` (Remote Development); a new window connects itself.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_remote(
|
||||
app: AppHandle,
|
||||
target: crate::remote_dev::RemoteTarget,
|
||||
ssh_config: String,
|
||||
path: String,
|
||||
new_window: bool,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
windows::open_remote_window(&app, &target, &path, new_window)
|
||||
windows::open_remote_window(&app, &ssh_config, &path, new_window)
|
||||
}
|
||||
|
||||
/// Opens an empty (welcome) window; returns its label.
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Installed WSL distros, for the "Connect to WSL" picker. `wsl.exe` can stall while the WSL
|
||||
/// service starts, so the wait is bounded.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn wsl_distros() -> IdeResult<Vec<String>> {
|
||||
let list = tokio::task::spawn_blocking(ide_core::wsl::list_distros);
|
||||
match tokio::time::timeout(Duration::from_secs(8), list).await {
|
||||
Ok(joined) => joined.map_err(|e| IdeError::internal(e.to_string())),
|
||||
Err(_) => Err(IdeError::internal("wsl.exe did not answer in time")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The WSL project a `\\wsl.localhost\<distro>\…` folder stands for, so the frontend opens it
|
||||
/// through the distro and not as a network folder. `None` for any other path.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn wsl_resolve(path: std::path::PathBuf) -> Option<crate::windows::RemoteLaunch> {
|
||||
crate::windows::wsl_launch(&path)
|
||||
}
|
||||
@@ -16,7 +16,6 @@ mod macos;
|
||||
mod menu;
|
||||
mod plugin_web;
|
||||
mod remote_dev;
|
||||
mod remote_wsl;
|
||||
|
||||
mod state;
|
||||
mod theme_frame;
|
||||
|
||||
@@ -28,46 +28,24 @@ pub async fn remote_bootstrap_list(
|
||||
state.remote.list(&ide_ssh::FsConnection::Sftp { ssh }, &path).await
|
||||
}
|
||||
|
||||
/// Where a remote project lives and how the server there is reached.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum RemoteTarget {
|
||||
/// The host of SSH configuration `config`.
|
||||
Ssh { config: String },
|
||||
/// A WSL distribution on this machine.
|
||||
Wsl { distro: String },
|
||||
}
|
||||
|
||||
/// Where the server is installed on the remote host (per version).
|
||||
fn install_dir(version: &str) -> String {
|
||||
format!("~/{SERVER_DIR}/{version}")
|
||||
format!("~/.openidea/server/{version}")
|
||||
}
|
||||
|
||||
/// Under the remote home: where the server builds are kept, one folder per version.
|
||||
pub(crate) const SERVER_DIR: &str = ".openidea/server";
|
||||
|
||||
/// File name of the server binary on every host.
|
||||
pub(crate) const SERVER_BIN: &str = "openidea-server";
|
||||
|
||||
/// Printed before a probe's answer: shell start-up files and `wsl.exe` may print first.
|
||||
pub(crate) const PROBE_MARK: &str = "__OPENIDEA_PROBE__";
|
||||
|
||||
/// One remote window's connection.
|
||||
pub struct Connection {
|
||||
peer: Peer,
|
||||
pub target: RemoteTarget,
|
||||
pub ssh_config: String,
|
||||
pub root: String,
|
||||
pub host: String,
|
||||
/// The server's `std::env::consts::OS`: where the project's commands run.
|
||||
pub os: String,
|
||||
pub commands: Vec<String>,
|
||||
/// Streaming arguments by connection-wide id: the frontend channel and the id
|
||||
/// it expects (each webview numbers its own, and a settings window shares this
|
||||
/// connection with its parent).
|
||||
channels: Channels,
|
||||
next_channel: std::sync::atomic::AtomicU64,
|
||||
/// Keeps the SSH connection alive; `None` for WSL.
|
||||
session: Option<Arc<ide_ssh::Session>>,
|
||||
session: Arc<ide_ssh::Session>,
|
||||
/// Remote ports forwarded to this machine (Ports tool window), by remote port.
|
||||
forwards: Mutex<Vec<(u16, ide_ssh::Tunnel)>>,
|
||||
}
|
||||
@@ -104,13 +82,13 @@ impl Connections {
|
||||
self.0.lock().get(window).cloned()
|
||||
}
|
||||
|
||||
/// The window connected to folder `root` of `target`.
|
||||
pub fn window_of(&self, target: &RemoteTarget, root: &str) -> Option<String> {
|
||||
/// The window connected to folder `root` on the host of SSH configuration `ssh_config`.
|
||||
pub fn window_of(&self, ssh_config: &str, root: &str) -> Option<String> {
|
||||
let root = root.trim_end_matches('/');
|
||||
self.0
|
||||
.lock()
|
||||
.iter()
|
||||
.find(|(_, c)| c.target == *target && c.root.trim_end_matches('/') == root)
|
||||
.find(|(_, c)| c.ssh_config == ssh_config && c.root.trim_end_matches('/') == root)
|
||||
.map(|(label, _)| label.clone())
|
||||
}
|
||||
|
||||
@@ -145,7 +123,7 @@ pub struct RemoteProgress {
|
||||
pub fraction: Option<f64>,
|
||||
}
|
||||
|
||||
pub(crate) type Progress = dyn Fn(RemoteStage, Option<f64>) + Send + Sync;
|
||||
type Progress = dyn Fn(RemoteStage, Option<f64>) + Send + Sync;
|
||||
|
||||
/// A value for one streaming argument of a remote command (`data`: JSON text).
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -158,9 +136,9 @@ pub struct ChannelFrame {
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteProject {
|
||||
pub target: RemoteTarget,
|
||||
pub ssh_config: String,
|
||||
pub root: String,
|
||||
/// `user@host:port` of the SSH configuration; the distribution name for WSL.
|
||||
/// `user@host:port` of the SSH configuration.
|
||||
pub host: String,
|
||||
pub server_version: String,
|
||||
pub os: String,
|
||||
@@ -266,7 +244,7 @@ async fn download_server(
|
||||
}
|
||||
|
||||
/// `uname -sm` → (`linux` | `macos`, `x86_64` | `aarch64`), as Rust names them.
|
||||
pub(crate) fn platform(uname: &str) -> (String, String) {
|
||||
fn platform(uname: &str) -> (String, String) {
|
||||
let mut parts = uname.split_whitespace();
|
||||
let os = match parts.next().unwrap_or_default().to_ascii_lowercase().as_str() {
|
||||
"darwin" => "macos".to_owned(),
|
||||
@@ -280,30 +258,29 @@ pub(crate) fn platform(uname: &str) -> (String, String) {
|
||||
(os, arch)
|
||||
}
|
||||
|
||||
/// What [`local_server`] settled on.
|
||||
pub(crate) enum LocalServer {
|
||||
/// A server binary on this machine and its [`build_id`].
|
||||
Binary(std::path::PathBuf, String),
|
||||
/// No binary available (offline): this build of the version already on the host.
|
||||
Installed(String),
|
||||
}
|
||||
|
||||
/// The server binary to put on a host of `os`/`arch` whose `installed` builds are known.
|
||||
pub(crate) async fn local_server(
|
||||
state: &AppState,
|
||||
version: &str,
|
||||
os: &str,
|
||||
arch: &str,
|
||||
installed: &[String],
|
||||
progress: Arc<Progress>,
|
||||
) -> IdeResult<LocalServer> {
|
||||
let local = match local_server_binary(state, os, arch) {
|
||||
/// Makes sure this version of the server is installed on the host; returns its path.
|
||||
async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: Arc<Progress>) -> IdeResult<String> {
|
||||
progress(RemoteStage::Checking, None);
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let dir = install_dir(version);
|
||||
let q = ide_ssh::shell::tilde_quote;
|
||||
// Between markers: shell start-up files may print to stdout too.
|
||||
const MARK: &str = "__OPENIDEA_PROBE__";
|
||||
let probe = session
|
||||
.exec(&format!("echo {MARK}; uname -sm; ls -d {}/*/openidea-server 2>/dev/null", q(&dir)), None)
|
||||
.await?
|
||||
.stdout_str();
|
||||
let probe = probe.split_once(MARK).map_or(probe.as_str(), |(_, rest)| rest);
|
||||
let mut lines = probe.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
let (os, arch) = platform(lines.next().unwrap_or_default());
|
||||
let installed: Vec<&str> = lines.collect();
|
||||
let local = match local_server_binary(state, &os, &arch) {
|
||||
Some(local) => local,
|
||||
None => match download_server(state, version, os, arch, progress).await {
|
||||
None => match download_server(state, version, &os, &arch, progress.clone()).await {
|
||||
Ok(local) => local,
|
||||
// Offline: any build of this version already on the host will do.
|
||||
Err(e) => {
|
||||
return installed.first().cloned().map(LocalServer::Installed).ok_or_else(|| {
|
||||
return installed.first().map(|b| b.to_string()).ok_or_else(|| {
|
||||
IdeError::unavailable(format!(
|
||||
"no openidea-server {version} for {os}-{arch} ({}). Build it with \
|
||||
`cargo build --release -p ide-host --bin openidea-server` for that platform and put it at {} \
|
||||
@@ -327,27 +304,6 @@ pub(crate) async fn local_server(
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
Ok(LocalServer::Binary(local, build))
|
||||
}
|
||||
|
||||
/// Makes sure this version of the server is installed on the host; returns its path.
|
||||
async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: Arc<Progress>) -> IdeResult<String> {
|
||||
progress(RemoteStage::Checking, None);
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let dir = install_dir(version);
|
||||
let q = ide_ssh::shell::tilde_quote;
|
||||
let probe = session
|
||||
.exec(&format!("echo {PROBE_MARK}; uname -sm; ls -d {}/*/openidea-server 2>/dev/null", q(&dir)), None)
|
||||
.await?
|
||||
.stdout_str();
|
||||
let probe = probe.split_once(PROBE_MARK).map_or(probe.as_str(), |(_, rest)| rest);
|
||||
let mut lines = probe.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
let (os, arch) = platform(lines.next().unwrap_or_default());
|
||||
let installed: Vec<String> = lines.map(str::to_owned).collect();
|
||||
let (local, build) = match local_server(state, version, &os, &arch, &installed, progress.clone()).await? {
|
||||
LocalServer::Installed(bin) => return Ok(bin),
|
||||
LocalServer::Binary(local, build) => (local, build),
|
||||
};
|
||||
if let Some(bin) = installed.iter().find(|b| b.ends_with(&format!("/{build}/openidea-server"))) {
|
||||
return Ok(bin.to_string());
|
||||
}
|
||||
@@ -403,14 +359,14 @@ fn build_id(path: &std::path::Path) -> IdeResult<String> {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// File › Remote Development: opens `path` on `target` (an SSH host or a WSL distribution)
|
||||
/// in this window (installs / starts the server as needed).
|
||||
/// File › Remote Development: opens `path` on the host of SSH configuration
|
||||
/// `ssh_config` in this window (installs / starts the server as needed).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn remote_connect(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
target: RemoteTarget,
|
||||
ssh_config: String,
|
||||
path: String,
|
||||
on_progress: Channel<RemoteProgress>,
|
||||
) -> IdeResult<RemoteProject> {
|
||||
@@ -421,39 +377,23 @@ pub async fn remote_connect(
|
||||
let label = AppState::owner_window(window.label()).to_owned();
|
||||
state.remote_dev.disconnect(&label);
|
||||
state.host.close_project(&label);
|
||||
let config = state.ssh.config(&ssh_config)?;
|
||||
let session = state.ssh.session(&ssh_config).await?;
|
||||
let bin = ensure_server(&state, &session, progress.clone()).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let stream = session
|
||||
.exec_stream(&format!("{} --stdio", ide_ssh::shell::tilde_quote(&bin)))
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
|
||||
let (reader, writer) = tokio::io::split(stream);
|
||||
let channels: Channels = Arc::default();
|
||||
let handler =
|
||||
Arc::new(ClientHandler { app: window.app_handle().clone(), window: label.clone(), channels: channels.clone() });
|
||||
let tail = crate::remote_wsl::Tail::default();
|
||||
let (peer, session, host, title_tag) = match &target {
|
||||
RemoteTarget::Ssh { config: id } => {
|
||||
let config = state.ssh.config(id)?;
|
||||
let session = state.ssh.session(id).await?;
|
||||
let bin = ensure_server(&state, &session, progress.clone()).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let stream = session
|
||||
.exec_stream(&format!("{} --stdio", ide_ssh::shell::tilde_quote(&bin)))
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
|
||||
let (reader, writer) = tokio::io::split(stream);
|
||||
(Peer::connect(reader, writer, handler), Some(session), config.label(), config.label())
|
||||
}
|
||||
RemoteTarget::Wsl { distro } => {
|
||||
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, handler, &tail)?;
|
||||
(peer, None, distro.clone(), format!("WSL: {distro}"))
|
||||
}
|
||||
};
|
||||
// A server that dies on start-up says why on stderr (`wsl.exe` prints its own errors too).
|
||||
let with_output = |e: IdeError| match tail.text() {
|
||||
t if t.is_empty() => e,
|
||||
t => IdeError::unavailable(format!("{}: {t}", e.message)),
|
||||
};
|
||||
let peer = Peer::connect(reader, writer, handler);
|
||||
let info: ServerInfo = peer
|
||||
.request("initialize", serde_json::json!({ "version": ide_host::rpc::PROTOCOL_VERSION }), None)
|
||||
.await
|
||||
.map_err(|e| with_output(ide_host::rpc::error_from_reply(e)))?;
|
||||
.map_err(ide_host::rpc::error_from_reply)?;
|
||||
if info.protocol != ide_host::rpc::PROTOCOL_VERSION {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"openidea-server {} speaks protocol {}, this app {}",
|
||||
@@ -477,13 +417,12 @@ pub async fn remote_connect(
|
||||
peer.request("invoke", call, None).await.map_err(ide_host::rpc::error_from_reply)?;
|
||||
// As the server resolved it (symlinks, a trailing `/`): the frontend compares it with the project's.
|
||||
let root = serde_json::to_value(&project.root).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or(root);
|
||||
let _ = window.set_title(&format!("{} [{title_tag}]", project.name));
|
||||
let _ = window.set_title(&format!("{} [{}]", project.name, config.label()));
|
||||
let connection = Arc::new(Connection {
|
||||
peer,
|
||||
target: target.clone(),
|
||||
ssh_config: ssh_config.clone(),
|
||||
root: root.clone(),
|
||||
host: host.clone(),
|
||||
os: info.os.clone(),
|
||||
host: config.label(),
|
||||
commands: commands.clone(),
|
||||
channels,
|
||||
next_channel: std::sync::atomic::AtomicU64::new(1),
|
||||
@@ -496,7 +435,15 @@ pub async fn remote_connect(
|
||||
sync_plugin_languages(&plugins, &connection, &label).await;
|
||||
sync_plugin_packages(&plugins, &connection, &label).await;
|
||||
});
|
||||
Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project })
|
||||
Ok(RemoteProject {
|
||||
ssh_config,
|
||||
root,
|
||||
host: config.label(),
|
||||
server_version: info.version,
|
||||
os: info.os,
|
||||
commands,
|
||||
project,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sends the desktop's plugin languages, with the programs granted to them, to
|
||||
@@ -576,11 +523,9 @@ pub async fn sync_plugin_packages(plugins: &Arc<ide_host::plugins::PluginHost>,
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteSession {
|
||||
pub target: RemoteTarget,
|
||||
pub ssh_config: String,
|
||||
pub root: String,
|
||||
pub host: String,
|
||||
/// `linux`, `macos` or `windows`: the OS the project's commands run on.
|
||||
pub os: String,
|
||||
pub commands: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -590,10 +535,9 @@ pub struct RemoteSession {
|
||||
pub fn remote_current(window: Window, state: State<'_, AppState>) -> Option<RemoteSession> {
|
||||
let c = state.remote_dev.get(AppState::owner_window(window.label()))?;
|
||||
Some(RemoteSession {
|
||||
target: c.target.clone(),
|
||||
ssh_config: c.ssh_config.clone(),
|
||||
root: c.root.clone(),
|
||||
host: c.host.clone(),
|
||||
os: c.os.clone(),
|
||||
commands: c.commands.clone(),
|
||||
})
|
||||
}
|
||||
@@ -640,11 +584,7 @@ pub async fn remote_forward_port(
|
||||
if let Some(p) = forwarded(&c).into_iter().find(|p| p.remote_port == remote_port) {
|
||||
return Ok(p);
|
||||
}
|
||||
let session = c
|
||||
.session
|
||||
.clone()
|
||||
.ok_or_else(|| IdeError::unavailable("Forwarding ports is not supported in a WSL project yet"))?;
|
||||
let tunnel = ide_ssh::Tunnel::listen_on(session, Some(remote_port), "localhost", remote_port).await?;
|
||||
let tunnel = ide_ssh::Tunnel::listen_on(c.session.clone(), Some(remote_port), "localhost", remote_port).await?;
|
||||
let port = ForwardedPort { remote_port, local_port: tunnel.port() };
|
||||
let mut forwards = c.forwards.lock();
|
||||
if let Some(existing) = forwards.iter().find(|(remote, _)| *remote == remote_port) {
|
||||
@@ -741,13 +681,10 @@ pub async fn remote_import_local(
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let label = AppState::owner_window(window.label());
|
||||
let c = state.remote_dev.get(label).ok_or_else(|| IdeError::unavailable("Remote project is disconnected"))?;
|
||||
let Some(session) = c.session.clone() else {
|
||||
return Err(IdeError::unavailable("Importing local files is not supported in a WSL project yet"));
|
||||
};
|
||||
c.authorize_command(label, "fs_copy").await?;
|
||||
let cancel = state.host.begin_request(request);
|
||||
let result = async {
|
||||
let fs = ide_ssh::RemoteFs::new(session.sftp().await?);
|
||||
let fs = ide_ssh::RemoteFs::new(c.session.sftp().await?);
|
||||
let result = ide_remote::import::import_local(&fs, &from, &to, &cancel).await;
|
||||
fs.close().await;
|
||||
result
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
//! WSL transport of remote development: `openidea-server --stdio` started with
|
||||
//! `wsl.exe --exec` inside a distro, instead of over SSH.
|
||||
//!
|
||||
//! Every command goes through `--exec`, which runs the program directly without a shell on
|
||||
//! the Windows side; only fixed scripts reach `sh -c` inside the distro and everything variable
|
||||
//! (paths, versions) is passed as positional arguments, never spliced into the script.
|
||||
|
||||
use crate::remote_dev::{PROBE_MARK, Progress, RemoteStage, SERVER_BIN, SERVER_DIR};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::VecDeque;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
/// Bound for the short probes; `wsl.exe` can wait on a distro that is still starting.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const INSTALL_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
const UPLOAD_CHUNK: usize = 256 * 1024;
|
||||
/// Output lines of the server kept for the error shown when it dies early.
|
||||
const KEPT_LINES: usize = 20;
|
||||
|
||||
/// What the probe learned about a distro.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Probe {
|
||||
pub home: String,
|
||||
/// `uname -sm`.
|
||||
pub uname: String,
|
||||
/// Installed builds of this version (paths of `openidea-server`).
|
||||
pub installed: Vec<String>,
|
||||
}
|
||||
|
||||
fn checked(distro: &str) -> IdeResult<&str> {
|
||||
if ide_core::wsl::is_valid_distro(distro) {
|
||||
Ok(distro)
|
||||
} else {
|
||||
Err(IdeError::invalid(format!("'{distro}' is not a valid WSL distribution name")))
|
||||
}
|
||||
}
|
||||
|
||||
/// `wsl.exe -d <distro> --exec sh -c <script> sh <args>…`.
|
||||
fn sh(distro: &str, script: &str, args: &[&str]) -> IdeResult<tokio::process::Command> {
|
||||
let mut cmd = tokio::process::Command::new("wsl.exe");
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(["-d", checked(distro)?, "--exec", "sh", "-c", script, "sh"])
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
/// The reason a `wsl.exe` call failed, as text (its own messages are UTF-16).
|
||||
fn failure(distro: &str, out: &std::process::Output) -> IdeError {
|
||||
let mut text = ide_core::wsl::decode_output(&out.stderr);
|
||||
if text.trim().is_empty() {
|
||||
text = ide_core::wsl::decode_output(&out.stdout);
|
||||
}
|
||||
let text: String = text.trim().chars().filter(|c| !c.is_control() || *c == '\n').take(400).collect();
|
||||
IdeError::unavailable(format!("cannot run a command in WSL distribution '{distro}': {text}"))
|
||||
}
|
||||
|
||||
async fn output(distro: &str, mut cmd: tokio::process::Command, limit: Duration) -> IdeResult<std::process::Output> {
|
||||
let out = tokio::time::timeout(limit, cmd.output())
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable(format!("WSL distribution '{distro}' did not answer in time")))?
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))?;
|
||||
if out.status.success() { Ok(out) } else { Err(failure(distro, &out)) }
|
||||
}
|
||||
|
||||
/// Splits the probe output (after its marker) into [`Probe`].
|
||||
fn parse_probe(text: &str) -> IdeResult<Probe> {
|
||||
// Between markers: `wsl.exe` may print notices to stdout before the script runs.
|
||||
let text = text.split_once(PROBE_MARK).map_or("", |(_, rest)| rest);
|
||||
let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
let home = lines.next().unwrap_or_default().to_owned();
|
||||
// The path is spliced into nothing, but it must be one clean absolute path.
|
||||
if !home.starts_with('/') || home.chars().any(char::is_control) {
|
||||
return Err(IdeError::unavailable("cannot find the home directory in the WSL distribution"));
|
||||
}
|
||||
let uname = lines.next().unwrap_or_default().to_owned();
|
||||
Ok(Probe { home, uname, installed: lines.map(str::to_owned).collect() })
|
||||
}
|
||||
|
||||
/// Home directory, platform and installed server builds of `distro` (starts it if stopped).
|
||||
pub(crate) async fn probe(distro: &str, version: &str) -> IdeResult<Probe> {
|
||||
let script = format!(
|
||||
r#"echo {PROBE_MARK}; echo "$HOME"; uname -sm; ls -d "$HOME/{SERVER_DIR}/$1"/*/{SERVER_BIN} 2>/dev/null; true"#
|
||||
);
|
||||
let out = output(distro, sh(distro, &script, &[version])?, PROBE_TIMEOUT).await?;
|
||||
parse_probe(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// Where the builds of `version` live in a distro whose home is `home`.
|
||||
pub(crate) fn version_dir(home: &str, version: &str) -> String {
|
||||
format!("{}/{SERVER_DIR}/{version}", home.trim_end_matches('/'))
|
||||
}
|
||||
|
||||
/// Streams `data` into `<version_dir>/<build>/openidea-server` of `distro` and removes the other
|
||||
/// builds of the version. Returns the installed path.
|
||||
pub(crate) async fn install(
|
||||
distro: &str,
|
||||
version_dir: &str,
|
||||
build: &str,
|
||||
data: &[u8],
|
||||
progress: &Arc<Progress>,
|
||||
) -> IdeResult<String> {
|
||||
let build_dir = format!("{version_dir}/{build}");
|
||||
// Per install: another window may be installing the same build right now.
|
||||
let script = format!(
|
||||
r#"set -e; mkdir -p "$1"; p="$1/{SERVER_BIN}.part.$$"; trap 'rm -f "$p"' EXIT; cat > "$p"; chmod 755 "$p"; mv -f "$p" "$1/{SERVER_BIN}"; find "$2" -mindepth 1 -maxdepth 1 ! -name "$3" -exec rm -rf {{}} +"#
|
||||
);
|
||||
let mut cmd = sh(distro, &script, &[&build_dir, version_dir, build])?;
|
||||
cmd.stdin(Stdio::piped());
|
||||
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))?;
|
||||
let mut stdin = child.stdin.take().ok_or_else(|| IdeError::internal("wsl.exe stdin unavailable"))?;
|
||||
// `stdin` drops at the end of the upload: that is the EOF `cat` waits for.
|
||||
let upload = async move {
|
||||
for (i, chunk) in data.chunks(UPLOAD_CHUNK).enumerate() {
|
||||
stdin.write_all(chunk).await?;
|
||||
progress(RemoteStage::Uploading, Some(((i + 1) * UPLOAD_CHUNK).min(data.len()) as f64 / data.len() as f64));
|
||||
}
|
||||
stdin.flush().await
|
||||
};
|
||||
let result = tokio::time::timeout(INSTALL_TIMEOUT, async {
|
||||
let uploaded = upload.await;
|
||||
(uploaded, child.wait_with_output().await)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable(format!("installing {SERVER_BIN} in '{distro}' timed out")))?;
|
||||
match result {
|
||||
(Ok(()), Ok(out)) if out.status.success() => Ok(format!("{build_dir}/{SERVER_BIN}")),
|
||||
(_, Ok(out)) => Err(failure(distro, &out)),
|
||||
(_, Err(e)) => Err(IdeError::unavailable(format!("installing {SERVER_BIN} failed: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last lines the server (or `wsl.exe`) wrote outside the protocol.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Tail(Arc<Mutex<VecDeque<String>>>);
|
||||
|
||||
impl Tail {
|
||||
fn push(&self, line: String) {
|
||||
let mut lines = self.0.lock();
|
||||
if lines.len() == KEPT_LINES {
|
||||
lines.pop_front();
|
||||
}
|
||||
lines.push_back(line);
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
self.0.lock().iter().cloned().collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `bin --stdio` in `distro` and speaks the protocol over its stdio. The process dies
|
||||
/// with the connection.
|
||||
pub(crate) fn spawn(distro: &str, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, handler, tail)
|
||||
}
|
||||
|
||||
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
|
||||
fn spawn_with(launcher: &str, distro: &str, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--stdio"].map(str::to_owned).into();
|
||||
let tail = tail.clone();
|
||||
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
|
||||
}
|
||||
|
||||
/// Makes sure this version of the server is installed in `distro`; returns its path there.
|
||||
pub(crate) async fn ensure_server(
|
||||
state: &crate::state::AppState,
|
||||
distro: &str,
|
||||
progress: Arc<Progress>,
|
||||
) -> IdeResult<String> {
|
||||
use crate::remote_dev::{LocalServer, local_server, platform};
|
||||
progress(RemoteStage::Checking, None);
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let probe = probe(distro, version).await?;
|
||||
let (os, arch) = platform(&probe.uname);
|
||||
if os != "linux" {
|
||||
return Err(IdeError::unavailable(format!("'{distro}' reports {os} instead of linux")));
|
||||
}
|
||||
let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? {
|
||||
LocalServer::Installed(bin) => return Ok(bin),
|
||||
LocalServer::Binary(local, build) => (local, build),
|
||||
};
|
||||
if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) {
|
||||
return Ok(bin.clone());
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
progress(RemoteStage::Uploading, Some(0.0));
|
||||
let data = tokio::fs::read(&local).await?;
|
||||
let bin = install(distro, &version_dir(&probe.home, version), &build, &data, &progress).await?;
|
||||
tracing::info!("installed {SERVER_BIN} in WSL '{distro}' in {:?}", started.elapsed());
|
||||
Ok(bin)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const HOME: &str = "/home/me";
|
||||
const UNAME: &str = "Linux x86_64";
|
||||
|
||||
#[test]
|
||||
fn probe_output_is_read_after_the_marker() {
|
||||
let installed = format!("{}/ab/{SERVER_BIN}", version_dir(HOME, "1"));
|
||||
let text = format!("wsl: notice\n{PROBE_MARK}\n{HOME}\n{UNAME}\n{installed}\n");
|
||||
let p = parse_probe(&text).unwrap();
|
||||
assert_eq!(p, Probe { home: HOME.into(), uname: UNAME.into(), installed: vec![installed] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_probe_without_a_clean_home_is_refused() {
|
||||
assert!(parse_probe(&format!("{HOME}\n{UNAME}\n")).is_err(), "no marker");
|
||||
assert!(parse_probe(&format!("{PROBE_MARK}\nrelative\n{UNAME}\n")).is_err());
|
||||
assert!(parse_probe(&format!("{PROBE_MARK}\n")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_distro_names_never_reach_wsl_exe() {
|
||||
for bad in ["", "--exec", "a b", "a;b"] {
|
||||
assert!(sh(bad, "true", &[]).is_err(), "{bad}");
|
||||
}
|
||||
assert!(sh("Ubuntu-24.04", "true", &[]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_dir_ignores_a_trailing_slash() {
|
||||
assert_eq!(version_dir(&format!("{HOME}/"), "1.2.3"), format!("{HOME}/{SERVER_DIR}/1.2.3"));
|
||||
}
|
||||
|
||||
struct Silent;
|
||||
impl Handler for Silent {
|
||||
fn on_notification(&self, _: &str, _: serde_json::Value) {}
|
||||
fn on_request(&self, method: &str, _: serde_json::Value) -> Result<serde_json::Value, (i64, String)> {
|
||||
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A stand-in for `wsl.exe` that checks the arguments it is given, prints a UTF-16 notice
|
||||
/// the way the real one does, then answers one request.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn speaks_the_protocol_through_the_launcher_after_its_utf16_notice() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (distro, bin) = ("Debian-12", "/home/me/server");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let launcher = dir.path().join("fake-wsl");
|
||||
let script = format!(
|
||||
r#"#!/bin/sh
|
||||
[ "$*" = "-d {distro} --exec {bin} --stdio" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
|
||||
printf '\377\376N\000o\000\r\000\n\000'
|
||||
while read -r line; do
|
||||
line=${{line%?}}
|
||||
case "$line" in Content-Length:*) len=${{line#*: }} ;; "") break ;; esac
|
||||
done
|
||||
head -c "$len" >/dev/null
|
||||
body='{{"jsonrpc":"2.0","id":1,"result":"pong"}}'
|
||||
printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
"#
|
||||
);
|
||||
std::fs::write(&launcher, script).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tail = Tail::default();
|
||||
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, Arc::new(Silent), &tail).unwrap();
|
||||
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
|
||||
panic!("{e:?}; launcher said: {}", tail.text());
|
||||
});
|
||||
assert_eq!(reply, "pong");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_distro_name_never_starts_the_launcher() {
|
||||
let err = spawn_with("does-not-exist", "-d", "/x", Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
assert!(err.message.contains("not a valid"), "{}", err.message);
|
||||
}
|
||||
}
|
||||
+16
-127
@@ -10,7 +10,6 @@
|
||||
//! [`AppState::project`]). Their labels name the kind and the parent
|
||||
//! (`settings-main`, `comparison-project-2-3`); their [`Launch`] says what to show.
|
||||
|
||||
use crate::remote_dev::RemoteTarget;
|
||||
use crate::state::AppState;
|
||||
use crate::theme_frame::builtin_frame;
|
||||
use ide_core::settings::AppearanceSettings;
|
||||
@@ -102,20 +101,14 @@ pub struct FilePosition {
|
||||
pub column: u32,
|
||||
}
|
||||
|
||||
/// A project folder on an SSH host or in a WSL distribution.
|
||||
/// A project folder on the host of an SSH configuration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteLaunch {
|
||||
pub target: RemoteTarget,
|
||||
pub ssh_config: String,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// The remote launch for a folder of the `\\wsl.localhost\<distro>` share, if it is one.
|
||||
pub fn wsl_launch(path: &Path) -> Option<RemoteLaunch> {
|
||||
let w = ide_core::wsl::parse(path)?;
|
||||
Some(RemoteLaunch { target: RemoteTarget::Wsl { distro: w.distro }, path: w.path })
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct WindowsState {
|
||||
pub groups: Mutex<ide_workspace::window_groups::WindowGroups>,
|
||||
@@ -654,10 +647,6 @@ pub fn open_project_window(
|
||||
new_window: bool,
|
||||
files: Vec<PathBuf>,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
// Before touching the share: a stat on `\\wsl.localhost` is what makes it slow.
|
||||
if let Some(remote) = wsl_launch(path) {
|
||||
return open_remote_window(app, &remote.target, &remote.path, new_window);
|
||||
}
|
||||
let root = dunce::canonicalize(path).map_err(|e| IdeError::not_found(format!("{}: {e}", path.display())))?;
|
||||
tracing::info!("open_project_window {} new_window={new_window}", root.display());
|
||||
if let Some(w) = find_project_window(app, &root) {
|
||||
@@ -694,16 +683,12 @@ pub fn open_files_window(app: &AppHandle, caller: &str, files: Vec<PathBuf>) ->
|
||||
here.into_iter().map(Into::into).collect()
|
||||
}
|
||||
|
||||
/// [`open_project_window`] for folder `path` of `target` (Remote Development).
|
||||
pub fn open_remote_window(
|
||||
app: &AppHandle,
|
||||
target: &RemoteTarget,
|
||||
path: &str,
|
||||
new_window: bool,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
tracing::info!("open_remote_window {target:?}:{path} new_window={new_window}");
|
||||
/// [`open_project_window`] for folder `path` on the host of SSH configuration
|
||||
/// `ssh_config` (Remote Development).
|
||||
pub fn open_remote_window(app: &AppHandle, ssh_config: &str, path: &str, new_window: bool) -> IdeResult<OpenOutcome> {
|
||||
tracing::info!("open_remote_window {ssh_config}:{path} new_window={new_window}");
|
||||
let windows = app.webview_windows();
|
||||
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(target, path));
|
||||
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(ssh_config, path));
|
||||
if let Some(w) = open.and_then(|label| windows.get(&label)) {
|
||||
focus(w);
|
||||
return Ok(OpenOutcome::Focused { label: w.label().to_owned() });
|
||||
@@ -712,7 +697,7 @@ pub fn open_remote_window(
|
||||
return Ok(OpenOutcome::Current);
|
||||
}
|
||||
let title = path.trim_end_matches('/').rsplit('/').next().filter(|n| !n.is_empty() && *n != "~").map(str::to_owned);
|
||||
let remote = RemoteLaunch { target: target.clone(), path: path.to_owned() };
|
||||
let remote = RemoteLaunch { ssh_config: ssh_config.to_owned(), path: path.to_owned() };
|
||||
let window = create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() }, false)?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
@@ -724,41 +709,18 @@ pub enum Holds {
|
||||
Nothing,
|
||||
LightEdit,
|
||||
Project(PathBuf),
|
||||
/// A project inside a WSL distribution (`path` is the Linux path).
|
||||
Wsl {
|
||||
distro: String,
|
||||
path: String,
|
||||
},
|
||||
/// An SSH remote project.
|
||||
/// A remote project.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Holds {
|
||||
fn of_remote(remote: &RemoteLaunch) -> Self {
|
||||
match &remote.target {
|
||||
RemoteTarget::Wsl { distro } => Holds::Wsl { distro: distro.clone(), path: remote.path.clone() },
|
||||
RemoteTarget::Ssh { .. } => Holds::Other,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_wsl_folder(&self, remote: &RemoteLaunch) -> bool {
|
||||
match (self, &remote.target) {
|
||||
(Holds::Wsl { distro, path }, RemoteTarget::Wsl { distro: d }) => {
|
||||
distro.eq_ignore_ascii_case(d) && path.trim_end_matches('/') == remote.path.trim_end_matches('/')
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What window `label` holds: its open project, else what its pending launch is about to open.
|
||||
fn holds(app: &AppHandle, label: &str) -> Holds {
|
||||
let state = app.try_state::<AppState>();
|
||||
if let Some(project) = state.as_ref().and_then(|s| s.project(label).ok()) {
|
||||
return if project.light { Holds::LightEdit } else { Holds::Project(project.root.clone()) };
|
||||
}
|
||||
if let Some(c) = state.as_ref().and_then(|s| s.remote_dev.get(label)) {
|
||||
return Holds::of_remote(&RemoteLaunch { target: c.target.clone(), path: c.root.clone() });
|
||||
if state.is_some_and(|s| s.remote_dev.get(label).is_some()) {
|
||||
return Holds::Other;
|
||||
}
|
||||
pending_holds(app.state::<WindowsState>().pending(label).as_ref())
|
||||
}
|
||||
@@ -766,7 +728,7 @@ fn holds(app: &AppHandle, label: &str) -> Holds {
|
||||
fn pending_holds(launch: Option<&Launch>) -> Holds {
|
||||
match launch {
|
||||
Some(Launch { project: Some(root), .. }) => Holds::Project(root.to_path_buf()),
|
||||
Some(Launch { remote: Some(remote), .. }) => Holds::of_remote(remote),
|
||||
Some(Launch { remote: Some(_), .. }) => Holds::Other,
|
||||
Some(l) if !l.files.is_empty() => Holds::LightEdit,
|
||||
_ => Holds::Nothing,
|
||||
}
|
||||
@@ -783,8 +745,6 @@ pub enum OpenStep {
|
||||
Launch(String, Launch),
|
||||
/// A new window opens the project folder or (without one) the files in LightEdit.
|
||||
New(Option<PathBuf>, Vec<PathBuf>),
|
||||
/// A new window connects to a WSL distribution.
|
||||
NewRemote(RemoteLaunch),
|
||||
}
|
||||
|
||||
/// Where a file inside a project goes: a window with it open, or the step opening it.
|
||||
@@ -816,17 +776,6 @@ pub fn plan_open(paths: Vec<(PathBuf, bool)>, windows: &[(String, Holds)]) -> Ve
|
||||
})
|
||||
.collect();
|
||||
for dir in dirs {
|
||||
// A folder of a WSL distro opens as a WSL project, not as a network folder.
|
||||
if let Some(remote) = wsl_launch(&dir) {
|
||||
steps.push(match windows.iter().find(|(_, h)| h.is_wsl_folder(&remote)) {
|
||||
Some((label, _)) => OpenStep::Focus(label.clone()),
|
||||
None => match free.next() {
|
||||
Some(label) => OpenStep::Launch(label, Launch { remote: Some(remote), ..Default::default() }),
|
||||
None => OpenStep::NewRemote(remote),
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if let Some((label, _)) = windows.iter().find(|(_, h)| matches!(h, Holds::Project(root) if *root == dir)) {
|
||||
steps.push(OpenStep::Focus(label.clone()));
|
||||
continue;
|
||||
@@ -850,9 +799,7 @@ pub fn plan_open(paths: Vec<(PathBuf, bool)>, windows: &[(String, Holds)]) -> Ve
|
||||
Some(ProjectTarget::Step(i)) => match &mut steps[*i] {
|
||||
OpenStep::Launch(_, launch) => launch.files.push(file.into()),
|
||||
OpenStep::New(_, list) => list.push(file),
|
||||
OpenStep::Focus(_) | OpenStep::Files(..) | OpenStep::NewRemote(_) => {
|
||||
unreachable!("folders opened by the plan launch or open")
|
||||
}
|
||||
OpenStep::Focus(_) | OpenStep::Files(..) => unreachable!("folders opened by the plan launch or open"),
|
||||
},
|
||||
None => loose.push(file),
|
||||
}
|
||||
@@ -964,17 +911,6 @@ fn run_open(app: &AppHandle, steps: Vec<OpenStep>) {
|
||||
}
|
||||
}
|
||||
OpenStep::New(project, files) => spawn_window_with(app, project, files),
|
||||
OpenStep::NewRemote(remote) => {
|
||||
let app = app.clone();
|
||||
// Off the event-loop thread, like `spawn_window`.
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let title = remote.path.trim_end_matches('/').rsplit('/').next().map(str::to_owned);
|
||||
let launch = Launch { remote: Some(remote), ..Default::default() };
|
||||
if let Err(e) = create_window_for(&app, title, launch, false) {
|
||||
tracing::warn!("cannot open window: {}", e.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -987,19 +923,10 @@ pub fn opened_paths(urls: &[tauri::Url]) -> Vec<PathBuf> {
|
||||
|
||||
/// What a window opens for a command-line path: a folder as its project, a file in LightEdit.
|
||||
pub fn path_launch(path: PathBuf) -> Launch {
|
||||
let is_dir = path.is_dir();
|
||||
launch_for(path, is_dir)
|
||||
}
|
||||
|
||||
/// [`path_launch`] once the path is known to be a folder or not: only a WSL *folder* is a
|
||||
/// remote project, a file of the share stays a LightEdit file.
|
||||
fn launch_for(path: PathBuf, is_dir: bool) -> Launch {
|
||||
if !is_dir {
|
||||
Launch { files: vec![path.into()], ..Default::default() }
|
||||
} else if let Some(remote) = wsl_launch(&path) {
|
||||
Launch { remote: Some(remote), ..Default::default() }
|
||||
} else {
|
||||
if path.is_dir() {
|
||||
Launch { project: Some(path.into()), ..Default::default() }
|
||||
} else {
|
||||
Launch { files: vec![path.into()], ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1455,17 +1382,6 @@ mod tests {
|
||||
assert_eq!((launch.project, launch.files), (None, vec![file.into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_launch_keeps_wsl_files_apart_from_wsl_folders() {
|
||||
let share = PathBuf::from(r"\\wsl.localhost\Ubuntu\home\me\app");
|
||||
let folder = launch_for(share.clone(), true);
|
||||
let remote =
|
||||
RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() };
|
||||
assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote), None, 0));
|
||||
let file = launch_for(share.join("main.py"), false);
|
||||
assert_eq!((file.remote, file.project, file.files.len()), (None, None, 1));
|
||||
}
|
||||
|
||||
fn p(s: &str) -> PathBuf {
|
||||
PathBuf::from(s)
|
||||
}
|
||||
@@ -1562,33 +1478,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_folders_open_as_wsl_projects() {
|
||||
let (distro, linux_path) = ("Debian-12", "/srv/app");
|
||||
let share = format!(r"\\wsl.localhost\{distro}{}", linux_path.replace('/', r"\"));
|
||||
let share = share.as_str();
|
||||
let remote = wsl_launch(&p(share)).unwrap();
|
||||
assert_eq!(
|
||||
remote,
|
||||
RemoteLaunch { target: RemoteTarget::Wsl { distro: distro.into() }, path: linux_path.into() }
|
||||
);
|
||||
assert!(wsl_launch(&p(linux_path)).is_none());
|
||||
let launch = Launch { remote: Some(remote.clone()), ..Default::default() };
|
||||
let folder = vec![(p(share), true)];
|
||||
// A free window connects, else a new one; the window that has it open is focused.
|
||||
assert_eq!(plan_open(folder.clone(), &[w("main", Holds::Nothing)]), [OpenStep::Launch("main".into(), launch)]);
|
||||
assert_eq!(plan_open(folder.clone(), &[w("main", Holds::LightEdit)]), [OpenStep::NewRemote(remote.clone())]);
|
||||
let open = Holds::Wsl { distro: distro.to_lowercase(), path: format!("{linux_path}/") };
|
||||
assert_eq!(
|
||||
plan_open(folder, &[w("main", Holds::Nothing), w("project-1", open)]),
|
||||
[OpenStep::Focus("project-1".into())]
|
||||
);
|
||||
// Another distro's folder is a different project.
|
||||
let other = Holds::Wsl { distro: format!("{distro}-other"), path: linux_path.into() };
|
||||
assert!(!other.is_wsl_folder(&remote));
|
||||
assert_eq!(launch_for(p(share), true).remote, Some(remote));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_opened_from_a_window_go_to_their_project_window_else_light_edit() {
|
||||
let windows = [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.37",
|
||||
"version": "0.1.36",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+14
-38
@@ -802,10 +802,10 @@ export const commands = {
|
||||
*/
|
||||
windowOpenFileInNewWindow: (project: string | null, file: string) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_file_in_new_window", { project, file })),
|
||||
/**
|
||||
* [`window_open_project`] for folder `path` of `target` (an SSH host or a WSL distribution;
|
||||
* Remote Development); a new window connects itself.
|
||||
* [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
* `ssh_config` (Remote Development); a new window connects itself.
|
||||
*/
|
||||
windowOpenRemote: (target: RemoteTarget, path: string, newWindow: boolean) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_remote", { target, path, newWindow })),
|
||||
windowOpenRemote: (sshConfig: string, path: string, newWindow: boolean) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_remote", { sshConfig, path, newWindow })),
|
||||
/** Opens an empty (welcome) window; returns its label. */
|
||||
windowNew: () => typedError<string, IdeError>(__TAURI_INVOKE("window_new")),
|
||||
/**
|
||||
@@ -1149,19 +1149,6 @@ export const commands = {
|
||||
dbTrustSshHost: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_trust_ssh_host", { id })),
|
||||
/** Test Connection: connects with `config` as edited (not necessarily saved). */
|
||||
sshTest: (config: SshConfiguration, secret: string | null) => typedError<string, IdeError>(__TAURI_INVOKE("ssh_test", { config, secret })),
|
||||
/**
|
||||
* Installed WSL distros, for the "Connect to WSL" picker. `wsl.exe` can stall while the WSL
|
||||
* service starts, so the wait is bounded.
|
||||
*/
|
||||
wslDistros: () => typedError<string[], IdeError>(__TAURI_INVOKE("wsl_distros")),
|
||||
/**
|
||||
* The WSL project a `\\wsl.localhost\<distro>\…` folder stands for, so the frontend opens it
|
||||
* through the distro and not as a network folder. `None` for any other path.
|
||||
*/
|
||||
wslResolve: (path: string) => __TAURI_INVOKE<{
|
||||
target: RemoteTarget,
|
||||
path: string,
|
||||
} | null>("wsl_resolve", { path }),
|
||||
/** Remembers the password / passphrase of configuration `id` (`None` forgets it). */
|
||||
sshSetSecret: (id: string, secret: string | null, save: boolean) => __TAURI_INVOKE<void>("ssh_set_secret", { id, secret, save }),
|
||||
/** Whether connecting with configuration `id` needs a password first. */
|
||||
@@ -1204,17 +1191,15 @@ export const commands = {
|
||||
/** Browse before connecting, using the desktop's SSH configuration even in a remote window. */
|
||||
remoteBootstrapList: (ssh: string, path: string) => typedError<RemoteEntry[], IdeError>(__TAURI_INVOKE("remote_bootstrap_list", { ssh, path })),
|
||||
/**
|
||||
* File › Remote Development: opens `path` on `target` (an SSH host or a WSL distribution)
|
||||
* in this window (installs / starts the server as needed).
|
||||
* File › Remote Development: opens `path` on the host of SSH configuration
|
||||
* `ssh_config` in this window (installs / starts the server as needed).
|
||||
*/
|
||||
remoteConnect: (target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, onProgress })),
|
||||
remoteConnect: (sshConfig: string, path: string, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { sshConfig, path, onProgress })),
|
||||
/** The remote session of this window (a settings window: its parent's), if any. */
|
||||
remoteCurrent: () => __TAURI_INVOKE<{
|
||||
target: RemoteTarget,
|
||||
sshConfig: string,
|
||||
root: string,
|
||||
host: string,
|
||||
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
|
||||
os: string,
|
||||
commands: string[],
|
||||
} | null>("remote_current"),
|
||||
remoteDisconnect: () => __TAURI_INVOKE<void>("remote_disconnect"),
|
||||
@@ -6125,9 +6110,9 @@ export type RemoteEntry = {
|
||||
permissions: string,
|
||||
};
|
||||
|
||||
/** A project folder on an SSH host or in a WSL distribution. */
|
||||
/** A project folder on the host of an SSH configuration. */
|
||||
export type RemoteLaunch = {
|
||||
target: RemoteTarget,
|
||||
sshConfig: string,
|
||||
path: string,
|
||||
};
|
||||
|
||||
@@ -6155,9 +6140,9 @@ export type RemoteProgress = {
|
||||
export type RemoteProject = RemoteProject_Serialize | RemoteProject_Deserialize;
|
||||
|
||||
export type RemoteProject_Deserialize = {
|
||||
target: RemoteTarget,
|
||||
sshConfig: string,
|
||||
root: string,
|
||||
/** `user@host:port` of the SSH configuration; the distribution name for WSL. */
|
||||
/** `user@host:port` of the SSH configuration. */
|
||||
host: string,
|
||||
serverVersion: string,
|
||||
os: string,
|
||||
@@ -6167,9 +6152,9 @@ export type RemoteProject_Deserialize = {
|
||||
};
|
||||
|
||||
export type RemoteProject_Serialize = {
|
||||
target: RemoteTarget,
|
||||
sshConfig: string,
|
||||
root: string,
|
||||
/** `user@host:port` of the SSH configuration; the distribution name for WSL. */
|
||||
/** `user@host:port` of the SSH configuration. */
|
||||
host: string,
|
||||
serverVersion: string,
|
||||
os: string,
|
||||
@@ -6179,24 +6164,15 @@ export type RemoteProject_Serialize = {
|
||||
};
|
||||
|
||||
export type RemoteSession = {
|
||||
target: RemoteTarget,
|
||||
sshConfig: string,
|
||||
root: string,
|
||||
host: string,
|
||||
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
|
||||
os: string,
|
||||
commands: string[],
|
||||
};
|
||||
|
||||
/** Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload). */
|
||||
export type RemoteStage = "connecting" | "checking" | "downloading" | "uploading" | "starting" | "opening";
|
||||
|
||||
/** Where a remote project lives and how the server there is reached. */
|
||||
export type RemoteTarget =
|
||||
/** The host of SSH configuration `config`. */
|
||||
{ kind: "ssh"; config: string } |
|
||||
/** A WSL distribution on this machine. */
|
||||
{ kind: "wsl"; distro: string };
|
||||
|
||||
export type Renamed = {
|
||||
edit: WorkspaceEdit,
|
||||
incomplete: ReferencesIncomplete | null,
|
||||
|
||||
@@ -24,30 +24,6 @@ describe("language modes", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses YAML into large tree buffers and highlights mappings after comment lines", async () => {
|
||||
for (const path of ["/p/application.yml", "/p/compose.yaml"]) {
|
||||
const support = await loadSupport(findLanguageDescription("YAML", path)!);
|
||||
// @lezer/yaml can invert a node's range on a tree buffer boundary; one buffer avoids it.
|
||||
expect((support!.language.parser as unknown as { bufferLength: number }).bufferLength).toBe(1 << 16);
|
||||
}
|
||||
const support = await loadSupport(findLanguageDescription("YAML", "/p/application.yml")!);
|
||||
const source = "spring:\n datasource:\n # driver: a\n # url: b\n driver: c # d\n url: e\n";
|
||||
const found: Array<[string, string]> = [];
|
||||
highlightTree(
|
||||
support!.language.parser.parse(source),
|
||||
tagHighlighter([
|
||||
{ tag: t.lineComment, class: "comment" },
|
||||
{ tag: t.definition(t.propertyName), class: "key" },
|
||||
]),
|
||||
(from, to, style) => found.push([source.slice(from, to), style]),
|
||||
);
|
||||
expect(found.filter(([, style]) => style === "comment").map(([text]) => text)).toEqual([
|
||||
"# driver: a",
|
||||
"# url: b",
|
||||
"# d",
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes AsciiDoc files and loads their lightweight syntax mode", async () => {
|
||||
for (const path of ["/docs/guide.adoc", "/docs/guide.asciidoc"]) {
|
||||
const description = findLanguageDescription("AsciiDoc", path);
|
||||
|
||||
@@ -115,21 +115,6 @@ const OWN_MODES = [
|
||||
load: () => import("./erb").then((m) => m.erb()),
|
||||
}),
|
||||
LanguageDescription.of({ name: "JSP", load: () => import("./jsp").then((m) => m.jsp()) }),
|
||||
LanguageDescription.of({
|
||||
name: "YAML",
|
||||
alias: ["yml"],
|
||||
extensions: ["yaml", "yml"],
|
||||
load: async () => {
|
||||
const support = await languageData.find((l) => l.name === "YAML")!.load();
|
||||
// @lezer/yaml can give a mapping that follows comment lines an inverted range when it
|
||||
// lands on a tree buffer boundary (1024 entries by default); highlighting then skips
|
||||
// the whole mapping. Larger buffers keep ordinary YAML files in one.
|
||||
return new LanguageSupport(
|
||||
(support.language as LRLanguage).configure({ bufferLength: 1 << 16 }),
|
||||
support.support,
|
||||
);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const BATCH_KEYWORDS = new Set([
|
||||
|
||||
@@ -6,13 +6,11 @@ const projectCurrent = vi.fn();
|
||||
const windowOpenProject = vi.fn();
|
||||
const windowOpenFiles = vi.fn();
|
||||
const windowTakeLaunch = vi.fn();
|
||||
const wslResolve = vi.fn();
|
||||
const cancelClose = vi.fn();
|
||||
const notify = vi.fn();
|
||||
vi.mock("@/platform/remote", async (original) => ({
|
||||
...(await original<typeof import("@/platform/remote")>()),
|
||||
isRemoteWindow: vi.fn(() => false),
|
||||
connectRemote: vi.fn(async () => {}),
|
||||
}));
|
||||
// The backend answers with the global settings, here: whatever the test set up.
|
||||
const lightEditOpen = vi.fn(async (_path: string) => ({ status: "ok", data: useProject.getState().settings ?? {} }));
|
||||
@@ -36,7 +34,6 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
windowOpenProject: (...a: unknown[]) => windowOpenProject(...a),
|
||||
windowOpenFiles: (...a: unknown[]) => windowOpenFiles(...a),
|
||||
windowTakeLaunch: () => windowTakeLaunch(),
|
||||
wslResolve: (p: string) => wslResolve(p),
|
||||
lightEditOpen: (p: string) => lightEditOpen(p),
|
||||
fsReadDir: (p: string) => fsReadDir(p),
|
||||
},
|
||||
@@ -58,7 +55,7 @@ const {
|
||||
} = await import("../windows");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { provideEditorService, provideNotificationService } = await import("@/workbench/contributions");
|
||||
const { isRemoteWindow, connectRemote } = await import("@/platform/remote");
|
||||
const { isRemoteWindow } = await import("@/platform/remote");
|
||||
const { IpcError } = await import("@/platform/ipc");
|
||||
provideNotificationService({ notify });
|
||||
|
||||
@@ -80,9 +77,7 @@ const ok = (data: unknown) => ({ status: "ok", data });
|
||||
const projectState = (root: string) => ({ project: { root, name: root, trusted: true, isGit: false, settings: {} } });
|
||||
|
||||
beforeEach(() => {
|
||||
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch, wslResolve]) f.mockReset();
|
||||
wslResolve.mockResolvedValue(null);
|
||||
vi.mocked(connectRemote).mockClear();
|
||||
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch]) f.mockReset();
|
||||
for (const f of [lightEditOpen, fsReadDir, openProject]) f.mockClear();
|
||||
cancelClose.mockClear();
|
||||
notify.mockClear();
|
||||
@@ -100,18 +95,6 @@ describe("openProjectInWindow", () => {
|
||||
expect(openProject).toHaveBeenCalledWith("/p/a");
|
||||
});
|
||||
|
||||
it("connects to the distribution when the folder is on the WSL share", async () => {
|
||||
const [distro, linuxPath] = ["Debian", "/srv/app"];
|
||||
const share = `\\\\wsl.localhost\\${distro}${linuxPath.replaceAll("/", "\\")}`;
|
||||
const target = { kind: "wsl", distro };
|
||||
wslResolve.mockResolvedValue({ target, path: linuxPath });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectInWindow(share, false);
|
||||
expect(wslResolve).toHaveBeenCalledWith(share);
|
||||
expect(connectRemote).toHaveBeenCalledWith(target, linuxPath);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("asks for a new window when this one already has a project", async () => {
|
||||
useProject.setState(projectState("/p/b") as never);
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
|
||||
@@ -53,10 +53,7 @@ async function openHere(path: string): Promise<boolean> {
|
||||
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
|
||||
if (!(await confirmLeaveProject())) return false;
|
||||
try {
|
||||
// A folder of a WSL distro runs there, not as a network folder.
|
||||
const wsl = await commands.wslResolve(path).catch(() => null);
|
||||
if (wsl) await connectRemote(wsl.target, wsl.path);
|
||||
else await openProject(path);
|
||||
await openProject(path);
|
||||
return true;
|
||||
} catch (e) {
|
||||
maybeEditorService()?.cancelClose?.();
|
||||
@@ -222,8 +219,8 @@ export async function consumeLaunch(): Promise<void> {
|
||||
if (await openHere(launch.project)) await openInEditor(files, positions);
|
||||
} else if (files.length) await openFilesHere(files, positions);
|
||||
else if (launch?.remote) {
|
||||
const { target, path } = launch.remote;
|
||||
await connectRemote(target, path).catch((e) =>
|
||||
const { sshConfig, path } = launch.remote;
|
||||
await connectRemote(sshConfig, path).catch((e) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.window.openFailed", { name: basename(path) }),
|
||||
|
||||
@@ -109,32 +109,6 @@ describe("deployment eligibility", () => {
|
||||
expect(useDeployment.getState().sync).toBeNull();
|
||||
expect(mocks.compare).not.toHaveBeenCalled();
|
||||
});
|
||||
it("opens default-server synchronization in a native window on desktop too", async () => {
|
||||
mocks.desktop = true;
|
||||
// The default server needs no choice, and on desktop nothing opens in the page.
|
||||
mocks.actions
|
||||
.find((action) => action.id === "deployment.syncWithDefault")!
|
||||
.run({ arg: ["/project/a", "/project/b"] });
|
||||
await vi.waitFor(() => expect(mocks.openWindow).toHaveBeenCalledWith("one", ["/project/a", "/project/b"]));
|
||||
expect(mocks.choose).not.toHaveBeenCalled();
|
||||
expect(useDeployment.getState().sync).toBeNull();
|
||||
expect(mocks.compare).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["deployment.syncWith", "deployment.syncWithDefault"])(
|
||||
"reports a comparison window that cannot open (%s)",
|
||||
async (action) => {
|
||||
mocks.desktop = true;
|
||||
mocks.choose.mockResolvedValue("one");
|
||||
mocks.openWindow.mockRejectedValueOnce(new Error("window failed"));
|
||||
await run(action);
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: expect.stringContaining("Cannot open comparison") }),
|
||||
),
|
||||
);
|
||||
expect(useDeployment.getState().sync).toBeNull();
|
||||
},
|
||||
);
|
||||
it("saves edits made in the local diff before synchronization and stops if saving fails", async () => {
|
||||
await run("deployment.syncWith");
|
||||
mocks.choose.mockResolvedValue("one");
|
||||
|
||||
@@ -225,16 +225,6 @@ async function deleteRemote(paths: string[]) {
|
||||
}
|
||||
|
||||
/** Compares every covered selection with `server`. */
|
||||
/** Sync with Deployed to: its own window on desktop (the browser build keeps the in-page dialog). */
|
||||
async function openComparison(server: DeploymentServerValid, paths: string[]) {
|
||||
if (!isTauri()) return openSync(server, paths);
|
||||
try {
|
||||
await showDeploymentComparison(server.id, paths);
|
||||
} catch (error) {
|
||||
showFailure("Cannot open comparison for {server}", server, error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function openSync(server: DeploymentServerValid, paths: string[]) {
|
||||
const coverage = (await serverCoverage(paths))?.find((c) => c.server === server.id);
|
||||
if (!coverage) return;
|
||||
@@ -463,7 +453,15 @@ export function registerDeploymentActions(): () => void {
|
||||
const target = paths[0] ?? projectRoot();
|
||||
if (!target) return;
|
||||
const targets = paths.length ? paths : [target];
|
||||
void pickServer("Sync with Deployed to", targets).then((server) => server && openComparison(server, targets));
|
||||
void pickServer("Sync with Deployed to", targets).then(async (server) => {
|
||||
if (!server) return;
|
||||
if (!isTauri()) return openSync(server, targets);
|
||||
try {
|
||||
await showDeploymentComparison(server.id, targets);
|
||||
} catch (error) {
|
||||
showFailure("Cannot open comparison for {server}", server, error);
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -475,7 +473,7 @@ export function registerDeploymentActions(): () => void {
|
||||
keywords: ["deploy", "sftp", "compare", "synchronize", "remote", "diff"],
|
||||
run: withTargets(async (paths) => {
|
||||
const server = await defaultServer("Sync with Deployed to", paths);
|
||||
if (server) await openComparison(server, paths);
|
||||
if (server) await openSync(server, paths);
|
||||
}),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -144,9 +144,8 @@ function actions(): Action[] {
|
||||
id: "github.changeRepository",
|
||||
title: "Change Repository or Account…",
|
||||
category: "GitHub",
|
||||
when: WHEN,
|
||||
// Not connected yet: the tool window offers the repository selector, or explains how to log in.
|
||||
run: () => (useGhRepository.getState().connection ? changeRepository() : void showPullRequests()),
|
||||
when: CONNECTED,
|
||||
run: () => changeRepository(),
|
||||
},
|
||||
{
|
||||
// pull.request.select.action
|
||||
|
||||
@@ -3,7 +3,7 @@ import { act, render, screen } from "@testing-library/react";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { provideToolWindowService, useContributions, type ToolWindowService } from "@/workbench/contributions";
|
||||
import { useContributions } from "@/workbench/contributions";
|
||||
import { activate } from "../index";
|
||||
import { setCurrentRepository } from "../api/client";
|
||||
import type { GHRepository, GHUser } from "../api/types";
|
||||
@@ -114,14 +114,6 @@ describe("tool window", () => {
|
||||
expect(getAction(id), id).toBeDefined();
|
||||
});
|
||||
|
||||
it("opens the tool window for Change Repository or Account while not connected", async () => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
useGhRepository.setState({ availability: { kind: "notInstalled" } });
|
||||
await getAction("github.changeRepository")!.run({ arg: undefined, ctx: { projectOpen: true } });
|
||||
expect(show).toHaveBeenCalledWith("pullRequests", true);
|
||||
});
|
||||
|
||||
it("shows gh's state when it is not ready", () => {
|
||||
useGhRepository.setState({ availability: { kind: "notInstalled" } });
|
||||
render(<PullRequestsToolWindow />);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* Import Theme from JetBrains IDE: the theme plugins installed in the JetBrains
|
||||
* IDEs (and Android Studio) on this machine, one row per plugin of each IDE, the
|
||||
* plugins of the themes in use first. Importing installs the plugin with all its
|
||||
* themes, as installing it in the IDE does (`importIntellijTheme`); which theme
|
||||
* to use stays a choice in Settings › Appearance. A file can be chosen instead.
|
||||
* Import Theme from IntelliJ IDE: the theme plugins installed in the JetBrains
|
||||
* IDEs on this machine, each under its plugin's heading, the plugin of the
|
||||
* theme in use first. Importing a theme brings every theme of its plugin, as
|
||||
* installing the plugin in IntelliJ does, and applies the chosen one
|
||||
* (`importIntellijTheme`). A file can be chosen instead.
|
||||
*/
|
||||
import { useEffect, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { InstalledIntellijTheme } from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Badge, Dialog, List, Spinner, T } from "@/ui";
|
||||
@@ -14,30 +15,28 @@ import { closeInstalledIntellijThemes, importIntellijTheme, useIntellijThemesDia
|
||||
import { errorText } from "./store";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
|
||||
interface PluginRow {
|
||||
key: string;
|
||||
plugin: string;
|
||||
ide: string;
|
||||
path: string;
|
||||
themes: InstalledIntellijTheme[];
|
||||
}
|
||||
type Row =
|
||||
| { kind: "plugin"; key: string; plugin: string; ide: string; count: number; first: boolean }
|
||||
| { kind: "theme"; key: string; theme: InstalledIntellijTheme };
|
||||
|
||||
/** A row per plugin (of an IDE), in the order found (the one in use first). */
|
||||
function pluginRows(themes: readonly InstalledIntellijTheme[]): PluginRow[] {
|
||||
const plugins = new Map<string, PluginRow>();
|
||||
/** A heading per plugin (of an IDE) with its themes under it, in the order found (the one in use first). */
|
||||
function themeRows(themes: readonly InstalledIntellijTheme[]): Row[] {
|
||||
const plugins = new Map<string, InstalledIntellijTheme[]>();
|
||||
for (const t of themes) {
|
||||
const key = `${t.ide}\n${t.path}`;
|
||||
const row = plugins.get(key) ?? { key, plugin: t.plugin, ide: t.ide, path: t.path, themes: [] };
|
||||
plugins.set(key, row);
|
||||
row.themes.push(t);
|
||||
plugins.set(key, [...(plugins.get(key) ?? []), t]);
|
||||
}
|
||||
return [...plugins.values()];
|
||||
return [...plugins].flatMap(([key, list], i): Row[] => [
|
||||
{ kind: "plugin", key, plugin: list[0]!.plugin, ide: list[0]!.ide, count: list.length, first: i === 0 },
|
||||
...list.map((theme): Row => ({ kind: "theme", key: `${key}\n${theme.themeId}`, theme })),
|
||||
]);
|
||||
}
|
||||
|
||||
function IntellijThemesDialog() {
|
||||
const [themes, setThemes] = useState<InstalledIntellijTheme[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
// The first theme, under the first heading.
|
||||
const [active, setActive] = useState(1);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
pluginsBackend()
|
||||
@@ -55,48 +54,50 @@ function IntellijThemesDialog() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const run = (path?: string) => {
|
||||
const run = (theme?: InstalledIntellijTheme) => {
|
||||
const { onImported } = useIntellijThemesDialog.getState();
|
||||
closeInstalledIntellijThemes();
|
||||
void importIntellijTheme(path).then((id) => id && onImported?.(id));
|
||||
void importIntellijTheme(theme?.path, theme?.themeId).then((id) => id && onImported?.(id));
|
||||
};
|
||||
const rows = pluginRows(themes ?? []);
|
||||
const chosen = rows[active];
|
||||
const rows = themeRows(themes ?? []);
|
||||
const row = rows[active];
|
||||
const chosen = row?.kind === "theme" ? row.theme : undefined;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title="Import Theme from JetBrains IDE"
|
||||
title="Import Theme from IntelliJ IDE"
|
||||
width={640}
|
||||
onClose={closeInstalledIntellijThemes}
|
||||
buttons={[
|
||||
{ label: "Choose File…", role: "extra", onClick: () => run() },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Import", role: "default", disabled: !chosen, onClick: () => chosen && run(chosen.path) },
|
||||
{ label: "Import", role: "default", disabled: !chosen, onClick: () => chosen && run(chosen) },
|
||||
]}
|
||||
>
|
||||
<div className={styles.intellijThemes}>
|
||||
<p className={styles.muted}>
|
||||
<T>
|
||||
Theme plugins installed in the JetBrains IDEs on this computer. Importing one installs it with all its
|
||||
themes; choose the theme to use in Settings › Appearance. Colours without an OpenIDEA counterpart keep the
|
||||
default theme colours.
|
||||
Theme plugins installed in the JetBrains IDEs on this computer. Importing a theme brings every theme of its
|
||||
plugin and applies the chosen one. Colours without an OpenIDEA counterpart keep the default theme colours.
|
||||
</T>
|
||||
</p>
|
||||
{themes === null ? (
|
||||
<div className={styles.intellijThemesStatus}>
|
||||
<Spinner size={14} label="Looking for JetBrains themes" />
|
||||
<T>Looking for JetBrains themes…</T>
|
||||
<Spinner size={14} label="Looking for IntelliJ themes" />
|
||||
<T>Looking for IntelliJ themes…</T>
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
items={rows}
|
||||
getKey={(r) => r.key}
|
||||
isSection={(r) => r.kind === "plugin"}
|
||||
activeIndex={chosen ? active : -1}
|
||||
onActiveChange={setActive}
|
||||
rowHeight={44}
|
||||
rowHeight={28}
|
||||
sectionHeight={30}
|
||||
className={styles.intellijThemesList}
|
||||
aria-label={tx("JetBrains theme plugins")}
|
||||
aria-label={tx("IntelliJ themes")}
|
||||
empty={
|
||||
<div className={styles.intellijThemesStatus} role="note">
|
||||
{error ?? (
|
||||
@@ -107,21 +108,24 @@ function IntellijThemesDialog() {
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
renderItem={(r) => {
|
||||
const count = r.themes.length;
|
||||
return (
|
||||
<div className={styles.intellijPlugin}>
|
||||
<div className={styles.intellijPluginHead}>
|
||||
<span className={styles.itemMain}>{r.plugin}</span>
|
||||
{r.themes.some((t) => t.active) && <Badge tone="accent">{tx("In use")}</Badge>}
|
||||
<span className={styles.intellijPluginIde}>
|
||||
{count === 1 ? tx("1 theme") : tx`${count} themes`} · {r.ide}
|
||||
</span>
|
||||
</div>
|
||||
<span className={styles.intellijPluginThemes}>{r.themes.map((t) => t.themeName).join(", ")}</span>
|
||||
renderSection={(r) =>
|
||||
r.kind === "plugin" && (
|
||||
<div className={clsx(styles.intellijPlugin, !r.first && styles.intellijPluginNext)}>
|
||||
<span className={styles.intellijPluginName}>{r.plugin}</span>
|
||||
<span>{r.count === 1 ? tx("1 theme") : tx`${r.count} themes`}</span>
|
||||
<span className={styles.intellijPluginIde}>{r.ide}</span>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
)
|
||||
}
|
||||
renderItem={(r) =>
|
||||
r.kind === "theme" && (
|
||||
<div className={styles.intellijTheme}>
|
||||
<span className={styles.itemMain}>{r.theme.themeName}</span>
|
||||
{r.theme.active && <Badge tone="accent">{tx("In use")}</Badge>}
|
||||
<span className={styles.muted}>{r.theme.dark ? tx("Dark") : tx("Light")}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -407,30 +407,37 @@
|
||||
padding: 8px 10px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.intellijPlugin {
|
||||
.intellijTheme {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.intellijPluginHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.intellijPluginThemes {
|
||||
overflow: hidden;
|
||||
color: var(--fg-muted);
|
||||
.intellijTheme > .muted {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.intellijPlugin {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
align-self: stretch;
|
||||
min-width: 0;
|
||||
}
|
||||
/* A line above each plugin but the first, as in IDEA's Theme list. */
|
||||
.intellijPluginNext {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.intellijPluginName {
|
||||
overflow: hidden;
|
||||
color: var(--fg-secondary);
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.intellijPluginIde {
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -569,7 +569,7 @@ function gearMenu(plugins: readonly PluginInfo[], updates: number, actions: Gear
|
||||
...(actions.canImport
|
||||
? [
|
||||
{ kind: "separator" as const },
|
||||
{ label: "Import Theme from JetBrains IDE…", run: actions.importInstalledIntellij },
|
||||
{ label: "Import Theme from IntelliJ IDE…", run: actions.importInstalledIntellij },
|
||||
{ label: "Import IntelliJ Theme from File…", run: actions.importIntellijFile },
|
||||
]
|
||||
: []),
|
||||
|
||||
@@ -41,15 +41,6 @@ const INSTALLED: InstalledIntellijTheme[] = [
|
||||
dark: true,
|
||||
active: false,
|
||||
},
|
||||
{
|
||||
ide: "DataGrip 2026.2",
|
||||
plugin: "Night Owl",
|
||||
path: "/dg/plugins/NightOwl",
|
||||
themeId: "owl-id",
|
||||
themeName: "Night Owl",
|
||||
dark: true,
|
||||
active: false,
|
||||
},
|
||||
];
|
||||
|
||||
let notes: Note[];
|
||||
@@ -109,8 +100,8 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("IntelliJ theme import", () => {
|
||||
it("installs the converted plugin through the install page and leaves the theme in use as it is", async () => {
|
||||
expect(await importIntellijTheme("/downloads/DeepSea.zip")).toBe(ID);
|
||||
it("installs the converted plugin through the install page and applies the chosen theme", async () => {
|
||||
expect(await importIntellijTheme("/downloads/DeepSea.zip", "shallow-id")).toBe(ID);
|
||||
expect(read).toHaveBeenCalledWith("/downloads/DeepSea.zip");
|
||||
const [name, files] = stage.mock.calls[0]!;
|
||||
expect(name).toBe(ID);
|
||||
@@ -120,11 +111,14 @@ describe("IntelliJ theme import", () => {
|
||||
"themes/shallow.theme.json",
|
||||
]);
|
||||
expect(installed).toEqual(["/app/plugins/.downloads/generated"]);
|
||||
// Which of its themes to use is the user's choice.
|
||||
expect(useThemeOverride.getState().theme).toBeNull();
|
||||
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/shallow`);
|
||||
});
|
||||
|
||||
it("returns nothing when the install is declined", async () => {
|
||||
it("applies the first theme without a choice, and nothing when the install is declined", async () => {
|
||||
expect(await importIntellijTheme("/downloads/DeepSea.jar")).toBe(ID);
|
||||
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/deep-sea`);
|
||||
|
||||
useThemeOverride.setState({ theme: null });
|
||||
setConsentPrompt(async () => null);
|
||||
expect(await importIntellijTheme("/downloads/DeepSea.jar")).toBeNull();
|
||||
expect(useThemeOverride.getState().theme).toBeNull();
|
||||
@@ -158,33 +152,33 @@ describe("IntelliJ theme import", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Import Theme from JetBrains IDE", () => {
|
||||
it("lists one row per theme plugin, the one in use first, and imports the chosen plugin", async () => {
|
||||
describe("Import Theme from IntelliJ IDE", () => {
|
||||
it("lists the installed themes by plugin, the one in use first, and imports the chosen one", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onImported = vi.fn();
|
||||
render(<IntellijThemesDialogHost />);
|
||||
act(() => showInstalledIntellijThemes(onImported));
|
||||
const list = await screen.findByRole("listbox", { name: "JetBrains theme plugins" });
|
||||
const list = await screen.findByRole("listbox", { name: "IntelliJ themes" });
|
||||
const options = await waitFor(() => {
|
||||
const found = Array.from(list.querySelectorAll('[role="option"]'));
|
||||
expect(found).toHaveLength(2);
|
||||
return found;
|
||||
});
|
||||
// A plugin brings all its themes: they are listed in its row, not offered one by one.
|
||||
expect(options[0]).toHaveTextContent("Deep Sea Themes");
|
||||
// Both under their plugin's heading: importing one brings the plugin's every theme.
|
||||
expect(within(list).getByText("Deep Sea Themes")).toBeInTheDocument();
|
||||
expect(within(list).getByText("2 themes")).toBeInTheDocument();
|
||||
expect(within(list).getByText("IntelliJ IDEA 2025.2")).toBeInTheDocument();
|
||||
expect(options[0]).toHaveTextContent("Shallow");
|
||||
expect(options[0]).toHaveTextContent("In use");
|
||||
expect(options[0]).toHaveTextContent("2 themes · IntelliJ IDEA 2025.2");
|
||||
expect(options[0]).toHaveTextContent("Shallow, Deep Sea");
|
||||
expect(options[1]).toHaveTextContent("Night Owl");
|
||||
expect(options[1]).toHaveTextContent("1 theme · DataGrip 2026.2");
|
||||
expect(options[1]).toHaveTextContent("Deep Sea");
|
||||
expect(options[1]).not.toHaveTextContent("In use");
|
||||
|
||||
await user.click(within(list).getByText("1 theme · DataGrip 2026.2"));
|
||||
await user.click(screen.getByText("Deep Sea"));
|
||||
await user.click(screen.getByRole("button", { name: "Import" }));
|
||||
await waitFor(() => expect(onImported).toHaveBeenCalledWith(ID));
|
||||
expect(read).toHaveBeenCalledWith("/dg/plugins/NightOwl");
|
||||
expect(useThemeOverride.getState().theme).toBeNull();
|
||||
expect(screen.queryByRole("listbox", { name: "JetBrains theme plugins" })).toBeNull();
|
||||
expect(read).toHaveBeenCalledWith("/ij/plugins/DeepSea");
|
||||
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/deep-sea`);
|
||||
expect(screen.queryByRole("listbox", { name: "IntelliJ themes" })).toBeNull();
|
||||
});
|
||||
|
||||
it("offers a file when no IDE has theme plugins", async () => {
|
||||
|
||||
@@ -517,7 +517,7 @@ describe("PluginsPage", () => {
|
||||
);
|
||||
const imports = async () => {
|
||||
await user.click(screen.getByRole("button", { name: "Manage Plugins" }));
|
||||
const found = ["Import Theme from JetBrains IDE…", "Import IntelliJ Theme from File…"].filter((name) =>
|
||||
const found = ["Import Theme from IntelliJ IDE…", "Import IntelliJ Theme from File…"].filter((name) =>
|
||||
screen.queryByRole("menuitem", { name }),
|
||||
);
|
||||
act(() => hideContextMenu());
|
||||
|
||||
@@ -113,19 +113,10 @@ export function activate(): () => void {
|
||||
},
|
||||
{
|
||||
id: "plugins.importInstalledIntellijTheme",
|
||||
title: "Import Theme from JetBrains IDE…",
|
||||
title: "Import Theme from IntelliJ IDE…",
|
||||
category: "Plugins",
|
||||
icon: "plugin",
|
||||
keywords: [
|
||||
"intellij",
|
||||
"jetbrains",
|
||||
"pycharm",
|
||||
"webstorm",
|
||||
"android studio",
|
||||
"theme",
|
||||
"color scheme",
|
||||
"migrate",
|
||||
],
|
||||
keywords: ["intellij", "jetbrains", "theme", "color scheme", "migrate"],
|
||||
when: "projectOpen",
|
||||
run: () => showInstalledIntellijThemes(),
|
||||
},
|
||||
|
||||
@@ -2,26 +2,30 @@
|
||||
* Settings › Plugins › Import IntelliJ Theme: an IntelliJ theme plugin (a
|
||||
* Marketplace `.jar` / `.zip`, a plugin folder of an installed IDE) or a
|
||||
* `.theme.json` becomes an OpenIDEA theme plugin — read by the host, converted
|
||||
* here (`intellijTheme.ts`), installed through the usual install page. Its
|
||||
* themes join the others; which one to use is chosen in Settings › Appearance.
|
||||
* here (`intellijTheme.ts`), installed through the usual install page — and
|
||||
* its theme is applied.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { pluginThemeRef } from "@/platform/themes";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { setTheme } from "@/workbench/theme";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { intellijThemePackage } from "./intellijTheme";
|
||||
import { intellijThemePackage, type ThemePackage } from "./intellijTheme";
|
||||
import { errorText, installFromDisk } from "./store";
|
||||
|
||||
/**
|
||||
* Imports the IntelliJ theme plugin at `path` (asks for a file without one).
|
||||
* Returns the installed plugin's id; the theme in use stays as it is.
|
||||
* Imports the IntelliJ theme plugin at `path` (asks for a file without one)
|
||||
* and applies its theme `themeId` (an IntelliJ theme id), or its first.
|
||||
* Returns the installed plugin's id.
|
||||
*/
|
||||
export async function importIntellijTheme(path?: string): Promise<string | null> {
|
||||
export async function importIntellijTheme(path?: string, themeId?: string): Promise<string | null> {
|
||||
const backend = pluginsBackend();
|
||||
let pkg: ThemePackage;
|
||||
let dir: string;
|
||||
try {
|
||||
const picked = path ?? (await backend.pickIntellijTheme());
|
||||
if (!picked) return null;
|
||||
const pkg = intellijThemePackage(await backend.readIntellijTheme(picked));
|
||||
pkg = intellijThemePackage(await backend.readIntellijTheme(picked));
|
||||
dir = await backend.stagePackage(pkg.id, pkg.files);
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
@@ -32,7 +36,11 @@ export async function importIntellijTheme(path?: string): Promise<string | null>
|
||||
});
|
||||
return null;
|
||||
}
|
||||
return installFromDisk(dir);
|
||||
const id = await installFromDisk(dir);
|
||||
if (!id) return null;
|
||||
const theme = pkg.themes.find((t) => t.sourceId === themeId) ?? pkg.themes[0];
|
||||
if (theme) await setTheme(pluginThemeRef(id, theme.id));
|
||||
return id;
|
||||
}
|
||||
|
||||
interface DialogState {
|
||||
|
||||
@@ -384,6 +384,8 @@ export interface ThemePackage {
|
||||
id: string;
|
||||
name: string;
|
||||
files: { path: string; text: string }[];
|
||||
/** The package's themes: their id here and in the IntelliJ plugin (`sourceId`). */
|
||||
themes: { id: string; sourceId: string; name: string }[];
|
||||
}
|
||||
|
||||
/** `2.3` → `2.3.0`; IntelliJ plugin versions are not always semver. */
|
||||
@@ -395,15 +397,16 @@ function semver(version: string | null): string {
|
||||
/** An OpenIDEA theme plugin (`intellij.<plugin>`) with every theme of an IntelliJ theme plugin. */
|
||||
export function intellijThemePackage(source: IntellijThemeSource): ThemePackage {
|
||||
const ids = new Set<string>();
|
||||
const themes = source.themes.map((t) => {
|
||||
const converted = source.themes.map((t) => {
|
||||
const c = convertIntellijTheme(t.theme, t.editorScheme ?? undefined);
|
||||
let id = c.theme.id;
|
||||
for (let n = 2; ids.has(id); n++) id = `${c.theme.id.slice(0, 44)}-${n}`;
|
||||
ids.add(id);
|
||||
c.theme.id = id;
|
||||
return c;
|
||||
return { sourceId: t.id, converted: c };
|
||||
});
|
||||
if (themes.length === 0) throw new Error("The plugin has no themes");
|
||||
if (converted.length === 0) throw new Error("The plugin has no themes");
|
||||
const themes = converted.map((c) => c.converted);
|
||||
// Package metadata, not UI text: the plugin list shows it as written.
|
||||
const description = `${source.name}, imported from an IntelliJ theme plugin.`;
|
||||
const info: ThemePackageInfo = {
|
||||
@@ -424,5 +427,6 @@ export function intellijThemePackage(source: IntellijThemeSource): ThemePackage
|
||||
...(c.scheme ? [{ path: `themes/${c.theme.id}.scheme.json`, text: json(c.scheme) }] : []),
|
||||
]),
|
||||
],
|
||||
themes: converted.map(({ sourceId, converted: c }) => ({ id: c.theme.id, sourceId, name: c.theme.name })),
|
||||
};
|
||||
}
|
||||
@@ -13,13 +13,7 @@ vi.mock("@/platform/tauriCore", async (original) => ({
|
||||
beforeEach(() => {
|
||||
useTasks.setState({ tasks: [] });
|
||||
useRemote.setState({
|
||||
session: {
|
||||
target: { kind: "ssh", config: "s" },
|
||||
root: "/remote",
|
||||
host: "host",
|
||||
os: "linux",
|
||||
commands: ["fs_copy", "cancel_request"],
|
||||
},
|
||||
session: { sshConfig: "s", root: "/remote", host: "host", commands: ["fs_copy", "cancel_request"] },
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MEMBER_PREFIX, type ProjectNode } from "./model";
|
||||
import {
|
||||
canPaste,
|
||||
checkEditingName,
|
||||
copySelection,
|
||||
importExternal,
|
||||
paste,
|
||||
@@ -14,7 +13,6 @@ import {
|
||||
import { IpcError } from "@/platform/ipc";
|
||||
import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import { MemoryFs, setProjectFsForTests } from "./fs";
|
||||
import { initProjectTree, loadDir, setClipboard, setSelection, useProjectTree } from "./store";
|
||||
@@ -23,30 +21,6 @@ import { setOsClipboardForTests } from "./clipboard";
|
||||
let fs: MemoryFs;
|
||||
const notify = vi.fn();
|
||||
|
||||
describe("file names follow the execution host", () => {
|
||||
const platform = usePlatform.getState();
|
||||
afterEach(() => {
|
||||
usePlatform.setState(platform);
|
||||
useRemote.setState({ session: null });
|
||||
setProjectFsForTests(null);
|
||||
initProjectTree(null);
|
||||
});
|
||||
|
||||
it.each(["linux", "windows", "macos"])("validates names on a %s host from a Windows desktop", async (os) => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "ssh", config: "host" }, root: "/p", host: "host", os, commands: [] },
|
||||
});
|
||||
fs = new MemoryFs({ "/p/readme.txt": "" }, "/p");
|
||||
setProjectFsForTests(fs, "/p");
|
||||
initProjectTree("/p", "p");
|
||||
await loadDir("/p");
|
||||
useProjectTree.setState({ editing: { kind: "new", parent: "/p", nodeKind: "file" } });
|
||||
expect(checkEditingName("con").error !== null).toBe(os === "windows");
|
||||
expect(checkEditingName("README.txt").error !== null).toBe(os !== "linux");
|
||||
});
|
||||
});
|
||||
|
||||
const node = (path: string, dir = false): ProjectNode => ({
|
||||
key: path,
|
||||
path,
|
||||
@@ -128,9 +102,7 @@ describe("OS file imports", () => {
|
||||
setProjectFsForTests(fs, "/p");
|
||||
initProjectTree("/p", "p");
|
||||
await loadDir("/p");
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "ssh", config: "ssh" }, root: "/p", host: "host", os: "linux", commands: ["fs_copy"] },
|
||||
});
|
||||
useRemote.setState({ session: { sshConfig: "ssh", root: "/p", host: "host", commands: ["fs_copy"] } });
|
||||
provideNotificationService({ notify });
|
||||
notify.mockClear();
|
||||
});
|
||||
@@ -320,15 +292,7 @@ describe("project clipboard ownership", () => {
|
||||
it.each(remoteCases)(
|
||||
"remote hand-off=$handedOff OS=$osList cut=$cut on $entry",
|
||||
async ({ handedOff, osList, cut, entry }) => {
|
||||
useRemote.setState({
|
||||
session: {
|
||||
target: { kind: "ssh", config: "ssh" },
|
||||
root: "/p",
|
||||
host: "host",
|
||||
os: "linux",
|
||||
commands: ["fs_copy"],
|
||||
},
|
||||
});
|
||||
useRemote.setState({ session: { sshConfig: "ssh", root: "/p", host: "host", commands: ["fs_copy"] } });
|
||||
const writeText = vi.fn(async () => {
|
||||
if (!handedOff) throw new Error("unavailable");
|
||||
});
|
||||
@@ -374,9 +338,7 @@ describe("project clipboard ownership", () => {
|
||||
);
|
||||
|
||||
it("writes multiple remote paths as newline-joined text", async () => {
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "ssh", config: "ssh" }, root: "/p", host: "host", os: "linux", commands: ["fs_copy"] },
|
||||
});
|
||||
useRemote.setState({ session: { sshConfig: "ssh", root: "/p", host: "host", commands: ["fs_copy"] } });
|
||||
await fs.createFile("/p/second.txt");
|
||||
await loadDir("/p", true);
|
||||
setSelection(new Set(["/p/source.txt", "/p/second.txt"]), "/p/source.txt");
|
||||
@@ -388,9 +350,7 @@ describe("project clipboard ownership", () => {
|
||||
});
|
||||
|
||||
it("waits for a pending remote text write before reading file URLs", async () => {
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "ssh", config: "ssh" }, root: "/p", host: "host", os: "linux", commands: ["fs_copy"] },
|
||||
});
|
||||
useRemote.setState({ session: { sshConfig: "ssh", root: "/p", host: "host", commands: ["fs_copy"] } });
|
||||
let finish!: () => void;
|
||||
vi.stubGlobal("navigator", {
|
||||
clipboard: {
|
||||
|
||||
@@ -39,14 +39,17 @@ import {
|
||||
useProjectTree,
|
||||
} from "./store";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { hostOs, isRemoteWindow } from "@/platform/remote";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
|
||||
/** Nodes that may be renamed, moved or deleted (not roots, groups or library sources). */
|
||||
const mutable = (n: ProjectNode) => !n.root && !n.placeholder && !n.readOnly;
|
||||
|
||||
const get = () => useProjectTree.getState();
|
||||
const caseInsensitiveOs = (os: string) => os === "windows" || os === "macos";
|
||||
|
||||
const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
|
||||
const isWindows = /Win/i.test(ua);
|
||||
/** macOS and Windows file systems are case-insensitive by default. */
|
||||
const caseInsensitive = /Mac|Win/i.test(ua);
|
||||
|
||||
function errorMessage(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
@@ -233,9 +236,6 @@ export function cancelEditing() {
|
||||
export function checkEditingName(name: string) {
|
||||
const { editing } = get();
|
||||
if (!editing) return { error: null };
|
||||
const os = hostOs();
|
||||
const isWindows = os === "windows";
|
||||
const caseInsensitive = caseInsensitiveOs(os);
|
||||
if (editing.kind === "new" && editing.pkg) {
|
||||
const { segments, error } = packageSegments(name, editing.pkg);
|
||||
if (!segments) return { error };
|
||||
@@ -645,7 +645,6 @@ async function pasteFromOsClipboard(paths: string[], target: string) {
|
||||
/** The same files, as the clipboard keeps them (`/`-separated, any order). */
|
||||
function sameFiles(files: string[], paths: string[] | undefined): boolean {
|
||||
if (!paths || files.length !== paths.length) return false;
|
||||
const caseInsensitive = caseInsensitiveOs(usePlatform.getState().os);
|
||||
const key = (list: string[]) =>
|
||||
list
|
||||
.map((p) => (caseInsensitive ? p.toLowerCase() : p))
|
||||
@@ -688,7 +687,6 @@ export async function transfer(
|
||||
if (!root) return false;
|
||||
const fs = projectFs(root);
|
||||
await loadDir(target);
|
||||
const caseInsensitive = caseInsensitiveOs(hostOs());
|
||||
const taken = new Set(siblingsOf(target).map((n) => (caseInsensitive ? n.toLowerCase() : n)));
|
||||
const hasName = (n: string) => taken.has(caseInsensitive ? n.toLowerCase() : n);
|
||||
const isTaken = (n: string) => hasName(n) || (isUnityAssetFolder(target) && hasName(`${n}.meta`));
|
||||
@@ -746,7 +744,6 @@ export async function transfer(
|
||||
async function moveInto(paths: string[], target: string): Promise<boolean> {
|
||||
paths = assetPaths(paths);
|
||||
await loadDir(target);
|
||||
const caseInsensitive = caseInsensitiveOs(hostOs());
|
||||
const taken = new Set(siblingsOf(target).map((n) => (caseInsensitive ? n.toLowerCase() : n)));
|
||||
const errors: string[] = [];
|
||||
const moves: { from: string; to: string }[] = [];
|
||||
|
||||
@@ -6,9 +6,8 @@ import { useRemoteProgress } from "@/platform/remote";
|
||||
import { ConnectHost } from "./ConnectDialog";
|
||||
import { closeConnectDialog, openConnectDialog, useConnectDialog } from "./model";
|
||||
|
||||
const { list, distros, globalSettings, openRemote, executeAction } = vi.hoisted(() => ({
|
||||
const { list, globalSettings, openRemote, executeAction } = vi.hoisted(() => ({
|
||||
list: vi.fn(),
|
||||
distros: vi.fn(),
|
||||
globalSettings: vi.fn(),
|
||||
openRemote: vi.fn(),
|
||||
executeAction: vi.fn(),
|
||||
@@ -16,10 +15,7 @@ const { list, distros, globalSettings, openRemote, executeAction } = vi.hoisted(
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: { ...real.commands, remoteBootstrapList: list, wslDistros: distros, settingsGetGlobal: globalSettings },
|
||||
};
|
||||
return { ...real, commands: { ...real.commands, remoteBootstrapList: list, settingsGetGlobal: globalSettings } };
|
||||
});
|
||||
vi.mock("@/workbench/projectWindow", () => ({ openRemoteProject: openRemote }));
|
||||
vi.mock("@/platform/actions", async (importOriginal) => ({
|
||||
@@ -39,7 +35,6 @@ const entry = (path: string, isDir = true): RemoteEntry => ({
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
distros.mockResolvedValue({ status: "ok", data: [] });
|
||||
// A remote project's window: its settings are the remote host's, without this machine's SSH configurations.
|
||||
useProject.setState({ project: null, opening: false, settings: { ssh: { configs: [] } } as unknown as Settings });
|
||||
globalSettings.mockResolvedValue({
|
||||
@@ -92,9 +87,7 @@ it("browses the selected SSH host, navigates folders and opens one without a cur
|
||||
await waitFor(() => expect(screen.getByLabelText("Project directory:")).toHaveValue("/home/dev/projects"));
|
||||
expect(within(folders).getAllByRole("button")).toHaveLength(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Open" }));
|
||||
await waitFor(() =>
|
||||
expect(openRemote).toHaveBeenCalledWith({ kind: "ssh", config: "selected" }, "/home/dev/projects"),
|
||||
);
|
||||
await waitFor(() => expect(openRemote).toHaveBeenCalledWith("selected", "/home/dev/projects"));
|
||||
expect(useConnectDialog.getState().open).toBe(false);
|
||||
expect(useProject.getState().project).toBeNull();
|
||||
});
|
||||
@@ -132,24 +125,3 @@ it("offers SSH configuration and disables Browse until one exists, then lists th
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Browse" })).toBeEnabled());
|
||||
expect(screen.getByRole("button", { name: "SSH configuration" })).toHaveTextContent("dev");
|
||||
});
|
||||
|
||||
it("hides the WSL choice when no distribution is installed", async () => {
|
||||
render(<ConnectHost />);
|
||||
await waitFor(() => expect(distros).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("button", { name: "Connect through" })).toBeNull();
|
||||
});
|
||||
|
||||
it("opens a folder of the chosen WSL distribution, without browsing over SFTP", async () => {
|
||||
const installed = ["Ubuntu-24.04", "Debian"];
|
||||
distros.mockResolvedValue({ status: "ok", data: installed });
|
||||
openRemote.mockResolvedValue(true);
|
||||
render(<ConnectHost />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Connect through" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "WSL" }));
|
||||
expect(screen.queryByRole("button", { name: "Browse" })).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "WSL distribution" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: installed[1] }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Open" }));
|
||||
await waitFor(() => expect(openRemote).toHaveBeenCalledWith({ kind: "wsl", distro: installed[1] }, "~"));
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { call, commands, isCancelled, onIdeEvent, type RemoteEntry, type RemoteTarget } from "@/platform/ipc";
|
||||
import { call, commands, isCancelled, onIdeEvent, type RemoteEntry } from "@/platform/ipc";
|
||||
import { useRemoteProgress } from "@/platform/remote";
|
||||
import { sshLabel, type SshConfigValid, validateRemote } from "@/platform/remoteSettings";
|
||||
import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner } from "@/ui";
|
||||
@@ -52,34 +52,11 @@ function ConnectDialog() {
|
||||
const configs = useLocalSshConfigs();
|
||||
const [picked, setSsh] = useState("");
|
||||
const ssh = configs.some((c) => c.id === picked) ? picked : (configs[0]?.id ?? "");
|
||||
const [kind, setKind] = useState<RemoteTarget["kind"]>("ssh");
|
||||
// Installed WSL distributions; none (or no WSL at all) hides the WSL choice.
|
||||
const [distros, setDistros] = useState<string[]>([]);
|
||||
const [distro, setDistro] = useState("");
|
||||
const [path, setPath] = useState("~");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [browse, setBrowse] = useState<{ dir: string; folders: RemoteEntry[] } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
// Detection is a convenience: any failure just leaves SSH as the only choice.
|
||||
void call(commands.wslDistros())
|
||||
.then((found) => {
|
||||
if (!live) return;
|
||||
setDistros(found);
|
||||
setDistro((d) => d || (found[0] ?? ""));
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const wsl = kind === "wsl";
|
||||
const name = wsl ? distro : ssh;
|
||||
const target: RemoteTarget = wsl ? { kind: "wsl", distro } : { kind: "ssh", config: ssh };
|
||||
|
||||
const list = async (dir: string) => {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
@@ -99,7 +76,8 @@ function ConnectDialog() {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
if (await openRemoteProject(target, path.trim() || "~")) closeConnectDialog();
|
||||
const target = path.trim() || "~";
|
||||
if (await openRemoteProject(ssh, target)) closeConnectDialog();
|
||||
else setBusy(false);
|
||||
} catch (e) {
|
||||
if (!isCancelled(e)) setError(e instanceof Error ? e.message : String(e));
|
||||
@@ -108,7 +86,7 @@ function ConnectDialog() {
|
||||
};
|
||||
|
||||
const options = configs.map((c) => ({ value: c.id, label: c.name.trim() || sshLabel(c), detail: sshLabel(c) }));
|
||||
const ready = !!name && !busy && !!path.trim();
|
||||
const ready = !!ssh && !busy && !!path.trim();
|
||||
const connecting = useRemoteProgress((s) => s.progress !== null);
|
||||
|
||||
return (
|
||||
@@ -137,52 +115,21 @@ function ConnectDialog() {
|
||||
<p className={styles.hint}>
|
||||
{tx("The project runs on the remote host; the IDE backend is installed there on first use.")}
|
||||
</p>
|
||||
{distros.length > 0 && (
|
||||
<>
|
||||
<label className={styles.label}>{tx("Connect through:")}</label>
|
||||
<Select
|
||||
value={kind}
|
||||
options={[
|
||||
{ value: "ssh", label: "SSH" },
|
||||
{ value: "wsl", label: "WSL" },
|
||||
]}
|
||||
onChange={(k) => {
|
||||
setKind(k as RemoteTarget["kind"]);
|
||||
setBrowse(null);
|
||||
}}
|
||||
aria-label={tx("Connect through")}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{wsl ? (
|
||||
<>
|
||||
<label className={styles.label}>{tx("WSL distribution:")}</label>
|
||||
<Select
|
||||
value={distro || null}
|
||||
options={distros.map((d) => ({ value: d, label: d }))}
|
||||
onChange={setDistro}
|
||||
aria-label={tx("WSL distribution")}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label className={styles.label}>{tx("SSH configuration:")}</label>
|
||||
<div className={styles.row}>
|
||||
<Select
|
||||
className={styles.grow}
|
||||
value={ssh || null}
|
||||
options={options}
|
||||
placeholder={tx("No SSH configurations")}
|
||||
onChange={(id) => {
|
||||
setSsh(id);
|
||||
setBrowse(null);
|
||||
}}
|
||||
aria-label={tx("SSH configuration")}
|
||||
/>
|
||||
<Button onClick={() => void executeAction("file.settings", SSH_SETTINGS_PAGE)}>{tx("Configure…")}</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label className={styles.label}>{tx("SSH configuration:")}</label>
|
||||
<div className={styles.row}>
|
||||
<Select
|
||||
className={styles.grow}
|
||||
value={ssh || null}
|
||||
options={options}
|
||||
placeholder={tx("No SSH configurations")}
|
||||
onChange={(id) => {
|
||||
setSsh(id);
|
||||
setBrowse(null);
|
||||
}}
|
||||
aria-label={tx("SSH configuration")}
|
||||
/>
|
||||
<Button onClick={() => void executeAction("file.settings", SSH_SETTINGS_PAGE)}>{tx("Configure…")}</Button>
|
||||
</div>
|
||||
<label className={styles.label} htmlFor="remote-dev-path">
|
||||
{tx("Project directory:")}
|
||||
</label>
|
||||
@@ -195,12 +142,9 @@ function ConnectDialog() {
|
||||
spellCheck={false}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
/>
|
||||
{/* Browsing lists over SFTP; a WSL distribution has no such session before connecting. */}
|
||||
{!wsl && (
|
||||
<Button disabled={!ssh || busy} onClick={() => void list(path.trim() || "~")}>
|
||||
{tx("Browse")}
|
||||
</Button>
|
||||
)}
|
||||
<Button disabled={!ssh || busy} onClick={() => void list(path.trim() || "~")}>
|
||||
{tx("Browse")}
|
||||
</Button>
|
||||
</div>
|
||||
{browse && (
|
||||
<ul className={styles.folders} aria-label={tx("Remote folders")}>
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { RemoteSession } from "@/platform/ipc";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { BarButton } from "@/ui";
|
||||
|
||||
/** Status bar label of a remote window: where its project runs. */
|
||||
export function remoteBadge(session: Pick<RemoteSession, "target" | "host">): string {
|
||||
return `${session.target.kind === "wsl" ? "WSL" : "SSH"}: ${session.host}`;
|
||||
}
|
||||
|
||||
export function RemoteStatus() {
|
||||
const session = useRemote((s) => s.session);
|
||||
if (!session) return null;
|
||||
const label = remoteBadge(session);
|
||||
return (
|
||||
<BarButton
|
||||
tooltip={tx`Project runs on ${label}`}
|
||||
aria-label={label}
|
||||
onClick={() => void executeAction("remote.connect")}
|
||||
>
|
||||
{label}
|
||||
</BarButton>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,19 @@
|
||||
/**
|
||||
* Remote development: a window whose project lives on an SSH host or in a WSL distribution. The backend
|
||||
* Remote development: a window whose project lives on an SSH host. The backend
|
||||
* (`openidea-server`) runs there and this window routes its commands to it
|
||||
* (platform/remote.ts).
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { disconnectRemote, useRemote } from "@/platform/remote";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
|
||||
import { maybeEditorService, registerOverlay, registerToolWindow } from "@/workbench/contributions";
|
||||
import { confirmLeaveProject } from "@/platform/project";
|
||||
import { ConnectHost } from "./ConnectDialog";
|
||||
import { reloadEnvironment } from "./environment";
|
||||
import { RemoteStatus } from "./RemoteStatus";
|
||||
import { closeConnectDialog, openConnectDialog } from "./model";
|
||||
import { restorePorts, usePorts } from "./ports";
|
||||
|
||||
/** SSH tunnels are available while this window is connected to an SSH host. */
|
||||
/** The Ports tool window, while this window is connected to a remote host. */
|
||||
function trackPortsWindow(): () => void {
|
||||
let off: (() => void) | null = null;
|
||||
const sync = (connected: boolean) => {
|
||||
@@ -35,8 +34,8 @@ function trackPortsWindow(): () => void {
|
||||
usePorts.setState({ ports: [] });
|
||||
}
|
||||
};
|
||||
sync(useRemote.getState().session?.target.kind === "ssh");
|
||||
const unsubscribe = useRemote.subscribe((s) => sync(s.session?.target.kind === "ssh"));
|
||||
sync(useRemote.getState().session !== null);
|
||||
const unsubscribe = useRemote.subscribe((s) => sync(s.session !== null));
|
||||
return () => {
|
||||
unsubscribe();
|
||||
off?.();
|
||||
@@ -47,13 +46,6 @@ export function activate(): () => void {
|
||||
const disposers = [
|
||||
trackPortsWindow(),
|
||||
registerOverlay({ id: "remote.connect", component: ConnectHost }),
|
||||
registerStatusItem({
|
||||
id: "remote.location",
|
||||
title: "Remote Host",
|
||||
align: "left",
|
||||
priority: 100,
|
||||
component: RemoteStatus,
|
||||
}),
|
||||
registerActions([
|
||||
{
|
||||
id: "remote.connect",
|
||||
|
||||
@@ -63,9 +63,7 @@ describe("restoring forwarded ports", () => {
|
||||
it("forwards the ports of this host and folder again after reconnecting", async () => {
|
||||
const { useRemote } = await import("@/platform/remote");
|
||||
const { forwardPort, restorePorts, savedPorts } = await import("./ports");
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "ssh", config: "lh" }, root: "/srv/app", host: "h", os: "linux", commands: [] },
|
||||
});
|
||||
useRemote.setState({ session: { sshConfig: "lh", root: "/srv/app", host: "h", commands: [] } });
|
||||
await forwardPort(8080);
|
||||
expect(savedPorts()).toEqual([8080]);
|
||||
// Reconnected: the new connection forwards nothing yet.
|
||||
@@ -75,13 +73,7 @@ describe("restoring forwarded ports", () => {
|
||||
expect(ipc.remoteForwardPort).toHaveBeenCalledWith(8080);
|
||||
expect(usePorts.getState().ports).toEqual([{ remotePort: 8080, localPort: 8080 }]);
|
||||
// Another folder on the same host has its own list.
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "ssh", config: "lh" }, root: "/srv/other", host: "h", os: "linux", commands: [] },
|
||||
});
|
||||
expect(savedPorts()).toEqual([]);
|
||||
useRemote.setState({
|
||||
session: { target: { kind: "wsl", distro: "lh" }, root: "/srv/app", host: "lh", os: "linux", commands: [] },
|
||||
});
|
||||
useRemote.setState({ session: { sshConfig: "lh", root: "/srv/other", host: "h", commands: [] } });
|
||||
expect(savedPorts()).toEqual([]);
|
||||
useRemote.setState({ session: null });
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ const SAVED_KEY = "openidea.remote.ports:";
|
||||
|
||||
function savedKey(): string | null {
|
||||
const session = useRemote.getState().session;
|
||||
return session?.target.kind === "ssh" ? `${SAVED_KEY}${session.target.config}:${session.root}` : null;
|
||||
return session ? `${SAVED_KEY}${session.sshConfig}:${session.root}` : null;
|
||||
}
|
||||
|
||||
export function savedPorts(): number[] {
|
||||
@@ -53,14 +53,6 @@ export function parsePort(text: string): number | null {
|
||||
}
|
||||
|
||||
export async function forwardPort(port: number): Promise<ForwardedPort | null> {
|
||||
if (useRemote.getState().session?.target.kind === "wsl") {
|
||||
notifications().notify({
|
||||
group: "remote",
|
||||
level: "error",
|
||||
title: tx("Forwarding ports is not supported in a WSL project yet"),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const forwarded = await call(commands.remoteForwardPort(port));
|
||||
await refreshPorts(true);
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
remoteLocation,
|
||||
} from "@/platform/remote";
|
||||
import { browsableFolders, listedDirectory, remoteParent } from "./model";
|
||||
import { remoteBadge } from "./RemoteStatus";
|
||||
|
||||
const entry = (path: string, isDir = true): RemoteEntry => ({
|
||||
name: path.slice(path.lastIndexOf("/") + 1),
|
||||
@@ -48,79 +47,33 @@ describe("remote folder browser", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const ssh = (config: string) => ({ kind: "ssh", config }) as const;
|
||||
const wsl = (distro: string) => ({ kind: "wsl", distro }) as const;
|
||||
|
||||
describe("remote project locations", () => {
|
||||
it("round-trip the configuration id and the path", () => {
|
||||
const loc = remoteLocation(ssh("mac mini/1"), "/Users/me/repo");
|
||||
const loc = remoteLocation("mac mini/1", "/Users/me/repo");
|
||||
expect(loc).toBe("ssh://mac%20mini%2F1/Users/me/repo");
|
||||
expect(parseRemoteLocation(loc)).toEqual({ target: ssh("mac mini/1"), path: "/Users/me/repo" });
|
||||
expect(parseRemoteLocation(loc)).toEqual({ sshConfig: "mac mini/1", path: "/Users/me/repo" });
|
||||
expect(parseRemoteLocation("/Users/me/repo")).toBeNull();
|
||||
});
|
||||
|
||||
it("round-trip a WSL distribution and the path", () => {
|
||||
const loc = remoteLocation(wsl("Ubuntu-24.04"), "/home/me/app");
|
||||
expect(loc).toBe("wsl://Ubuntu-24.04/home/me/app");
|
||||
expect(parseRemoteLocation(loc)).toEqual({ target: wsl("Ubuntu-24.04"), path: "/home/me/app" });
|
||||
expect(parseRemoteLocation("wsl://Ubuntu")).toBeNull();
|
||||
});
|
||||
|
||||
it("remembers recent remote projects most recent first, once each", () => {
|
||||
localStorage.clear();
|
||||
rememberRemote({ target: ssh("a"), path: "/p", name: "p", host: "me@a", openedAtMs: 1 });
|
||||
rememberRemote({ target: ssh("b"), path: "/q", name: "q", host: "me@b", openedAtMs: 2 });
|
||||
rememberRemote({ target: ssh("a"), path: "/p", name: "p", host: "me@a", openedAtMs: 3 });
|
||||
rememberRemote({ sshConfig: "a", path: "/p", name: "p", host: "me@a", openedAtMs: 1 });
|
||||
rememberRemote({ sshConfig: "b", path: "/q", name: "q", host: "me@b", openedAtMs: 2 });
|
||||
rememberRemote({ sshConfig: "a", path: "/p", name: "p", host: "me@a", openedAtMs: 3 });
|
||||
expect(recentRemotes().map((r) => r.path)).toEqual(["/p", "/q"]);
|
||||
forgetRemote(ssh("a"), "/p");
|
||||
forgetRemote("a", "/p");
|
||||
expect(recentRemotes().map((r) => r.path)).toEqual(["/q"]);
|
||||
});
|
||||
|
||||
it("keeps an SSH host and a WSL distribution of the same name apart", () => {
|
||||
localStorage.clear();
|
||||
rememberRemote({ target: ssh("dev"), path: "/p", name: "p", host: "me@dev", openedAtMs: 1 });
|
||||
rememberRemote({ target: wsl("dev"), path: "/p", name: "p", host: "dev", openedAtMs: 2 });
|
||||
expect(recentRemotes()).toHaveLength(2);
|
||||
forgetRemote(wsl("dev"), "/p");
|
||||
expect(recentRemotes().map((r) => r.target)).toEqual([ssh("dev")]);
|
||||
});
|
||||
|
||||
it("reads recents saved before WSL support, which carried `sshConfig`", () => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem(
|
||||
"openidea.remote.recent",
|
||||
JSON.stringify([
|
||||
{ sshConfig: "old", path: "/p", name: "p", host: "me@old", openedAtMs: 1 },
|
||||
{ path: "/no-target" },
|
||||
]),
|
||||
);
|
||||
expect(recentRemotes().map((r) => r.target)).toEqual([ssh("old")]);
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates only the original remote recents once, scoped to the saved host", () => {
|
||||
localStorage.clear();
|
||||
rememberRemote({ target: ssh("a"), path: "/old", host: "me@old", name: "old", openedAtMs: 1 });
|
||||
rememberRemote({ sshConfig: "a", path: "/old", host: "me@old", name: "old", openedAtMs: 1 });
|
||||
initializeRemoteTrustMigration();
|
||||
rememberRemote({ target: ssh("a"), path: "/new", host: "me@old", name: "new", openedAtMs: 2 });
|
||||
rememberRemote({ sshConfig: "a", path: "/new", host: "me@old", name: "new", openedAtMs: 2 });
|
||||
initializeRemoteTrustMigration();
|
||||
expect(takeLegacyRemoteTrust(ssh("a"), "/new", "me@old")).toBe(false);
|
||||
expect(takeLegacyRemoteTrust(ssh("a"), "/old", "me@other")).toBe(false);
|
||||
expect(takeLegacyRemoteTrust(ssh("a"), "/old", "me@old")).toBe(true);
|
||||
expect(takeLegacyRemoteTrust(ssh("a"), "/old", "me@old")).toBe(false);
|
||||
});
|
||||
|
||||
it("migrates a snapshot taken before WSL support, and never trusts a WSL distribution", () => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem(
|
||||
"openidea.remote.trustMigration",
|
||||
JSON.stringify([{ sshConfig: "a", path: "/old", host: "me@old", name: "old", openedAtMs: 1 }]),
|
||||
);
|
||||
expect(takeLegacyRemoteTrust(wsl("a"), "/old", "me@old")).toBe(false);
|
||||
expect(takeLegacyRemoteTrust(ssh("a"), "/old", "me@old")).toBe(true);
|
||||
});
|
||||
|
||||
it("labels the status bar with the transport and where the project runs", () => {
|
||||
expect(remoteBadge({ target: wsl("Ubuntu"), host: "Ubuntu" })).toBe("WSL: Ubuntu");
|
||||
expect(remoteBadge({ target: ssh("a"), host: "me@a:22" })).toBe("SSH: me@a:22");
|
||||
expect(takeLegacyRemoteTrust("a", "/new", "me@old")).toBe(false);
|
||||
expect(takeLegacyRemoteTrust("a", "/old", "me@other")).toBe(false);
|
||||
expect(takeLegacyRemoteTrust("a", "/old", "me@old")).toBe(true);
|
||||
expect(takeLegacyRemoteTrust("a", "/old", "me@old")).toBe(false);
|
||||
});
|
||||
@@ -16,7 +16,6 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
};
|
||||
});
|
||||
|
||||
const { usePlatform } = await import("@/platform/platformInfo");
|
||||
const { parseJavaArgs, joinJavaArgs } = await import("@/platform/javaLaunch");
|
||||
const { parseArgs } = await import("./configs");
|
||||
const { jdwpLaunch } = await import("./javaDebug");
|
||||
@@ -248,34 +247,3 @@ describe("Maven / Gradle: VM options of the forked JVM", () => {
|
||||
await expect(gradle().prepareLaunch!(remote)).rejects.toThrow(/run targets/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("build wrapper per execution host", () => {
|
||||
const wrapperCommands = () =>
|
||||
(["gradle", "maven"] as const).map((t) => typeFor(t)!.commandLine({ wrapper: "true", tasks: "test" })!.command);
|
||||
const WINDOWS = ["gradlew.bat", "mvnw.cmd"];
|
||||
const UNIX = ["./gradlew", "./mvnw"];
|
||||
|
||||
beforeEach(() => registerBuiltinTypes());
|
||||
afterEach(async () => {
|
||||
(await import("@/platform/remote")).disableRemote();
|
||||
usePlatform.setState({ os: "macos" });
|
||||
});
|
||||
|
||||
it("follows the desktop OS in a local window", () => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
expect(wrapperCommands()).toEqual(WINDOWS);
|
||||
usePlatform.setState({ os: "linux" });
|
||||
expect(wrapperCommands()).toEqual(UNIX);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ desktop: "windows", host: "linux", target: { kind: "wsl", distro: "Ubuntu" }, expected: UNIX },
|
||||
{ desktop: "windows", host: "macos", target: { kind: "ssh", config: "box" }, expected: UNIX },
|
||||
{ desktop: "macos", host: "windows", target: { kind: "ssh", config: "win" }, expected: WINDOWS },
|
||||
] as const)("follows the $host server of a remote window opened from $desktop", async (c) => {
|
||||
usePlatform.setState({ os: c.desktop });
|
||||
const { enableRemote } = await import("@/platform/remote");
|
||||
enableRemote({ target: c.target, root: "/app", host: "h", os: c.host, commands: [] });
|
||||
expect(wrapperCommands()).toEqual(c.expected);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,6 @@
|
||||
*/
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
import { CLASSPATH, parseJavaArgs, TEST_CLASSPATH } from "@/platform/javaLaunch";
|
||||
import { hostOs } from "@/platform/remote";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { useBuildPresentation } from "@/platform/projectPresentation";
|
||||
import type { RunConfigTypeContribution, RunConfigTypeField } from "@/workbench/contributions";
|
||||
@@ -14,8 +13,7 @@ import { formatArgs, parseArgs } from "./configs";
|
||||
import { commandName } from "./commandName";
|
||||
import { updatePolicyDefaults, updatePolicyFields } from "./updatePolicies";
|
||||
|
||||
/** Whether this window's commands run on Windows: the remote server's OS in a remote window, else the desktop's. */
|
||||
export const isWindows = () => hostOs() === "windows";
|
||||
export const isWindows = () => typeof navigator !== "undefined" && /win/i.test(navigator.platform);
|
||||
|
||||
/** VM options / program arguments as typed; on Windows a backslash is a path separator. */
|
||||
export const splitJvmArgs = (text: string | undefined, windows = isWindows()) => parseArgs(text ?? "", windows);
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
* Rust come from SDK discovery and everything else resolves at launch.
|
||||
*/
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { isWindows } from "./jvmTypes";
|
||||
import type { LocatedTool, ToolEnv } from "./producers";
|
||||
|
||||
const TTL = 60_000;
|
||||
@@ -16,6 +15,7 @@ interface Entry {
|
||||
}
|
||||
|
||||
const cache = new Map<string, Entry>();
|
||||
const isWindows = typeof navigator !== "undefined" && /Win/i.test(navigator.platform || navigator.userAgent);
|
||||
let compileDir: string | null = null;
|
||||
let locateUnavailable = false;
|
||||
|
||||
@@ -115,7 +115,7 @@ export async function toolEnv(
|
||||
return {
|
||||
tool: (n) => tools.get(n),
|
||||
compileDir: compileDir ?? "/tmp/openidea-run",
|
||||
windows: isWindows(),
|
||||
windows: isWindows,
|
||||
python: py,
|
||||
...markers,
|
||||
};
|
||||
|
||||
@@ -138,17 +138,7 @@ describe("service reordering integration", () => {
|
||||
render(<ServicesTreeView />);
|
||||
select("Portal");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Move Up" }));
|
||||
act(() =>
|
||||
useRemote.setState({
|
||||
session: {
|
||||
root: "/services",
|
||||
target: { kind: "ssh", config: "host" },
|
||||
host: "host",
|
||||
os: "linux",
|
||||
commands: [],
|
||||
},
|
||||
}),
|
||||
);
|
||||
act(() => useRemote.setState({ session: { root: "/services", sshConfig: "host", host: "host", commands: [] } }));
|
||||
expect(names()).toEqual(["Spring Boot", "Gateway", "Portal", "npm", "Web", "Worker", "Docker"]);
|
||||
act(() => useRemote.setState({ session: null }));
|
||||
expect(names()).toEqual(["Spring Boot", "Portal", "Gateway", "npm", "Web", "Worker", "Docker"]);
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
import { splitCommandLine } from "@/platform/commandLine";
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
import { registerRunConfigType, type RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { hostOs } from "@/platform/remote";
|
||||
import { imageTag, targetTitle, type DockerTarget } from "./compose";
|
||||
import { connections, endpointOf, loadSettings, useServices } from "./store";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -20,7 +19,7 @@ export const DOCKER_COMPOSE = "docker-compose";
|
||||
|
||||
const GROUP = "Docker";
|
||||
const on = (v: string | undefined) => v === "true";
|
||||
const isWindows = () => hostOs() === "windows";
|
||||
const isWindows = () => typeof navigator !== "undefined" && /win/i.test(navigator.platform);
|
||||
|
||||
/** One word for the platform shell the run executes the line with (`/bin/sh -c` or `cmd /C`). */
|
||||
export function shellQuote(word: string, windows = isWindows()): string {
|
||||
|
||||
@@ -171,18 +171,16 @@ export interface SelectProps<V extends string> {
|
||||
options: readonly SelectOption<V>[];
|
||||
onChange: (value: V) => void;
|
||||
disabled?: boolean;
|
||||
onPreview?: (value: V | null) => void;
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
export function Select<V extends string>({ value, options, onChange, disabled, onPreview, ...aria }: SelectProps<V>) {
|
||||
export function Select<V extends string>({ value, options, onChange, disabled, ...aria }: SelectProps<V>) {
|
||||
return (
|
||||
<UiSelect<V>
|
||||
value={value}
|
||||
options={options}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
onPreview={onPreview}
|
||||
className={styles.select}
|
||||
aria-label={aria["aria-label"]}
|
||||
/>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import { FontPicker } from "../components/FontPicker";
|
||||
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useId, useRef, useState, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
@@ -33,8 +33,7 @@ import { HTTP_PROXY_PAGE } from "./httpProxy";
|
||||
import styles from "./Behavior.module.css";
|
||||
import { LOCALES, SUPPORTED_LOCALES, tx, useT } from "@/platform/i18n";
|
||||
import { BUILTIN_THEMES, useContributedIconThemes } from "@/platform/themes";
|
||||
import { currentThemeChoice, originDetail, previewTheme, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
|
||||
import { themePreview } from "@/workbench/quickSwitch";
|
||||
import { originDetail, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
|
||||
|
||||
const BUILTIN_THEME_LABELS = BUILTIN_THEMES.map((t) => t.label);
|
||||
|
||||
@@ -63,28 +62,12 @@ function ThemeRow() {
|
||||
const matched = useLabelMatch("Sync with OS");
|
||||
const choices = useThemeChoices();
|
||||
const shown: ConcreteTheme = theme === "system" ? "light" : theme;
|
||||
// The theme under the pointer shows as in Quick Switch; the one picked here shows until Apply or Cancel.
|
||||
const picker = useMemo(() => themePreview(), []);
|
||||
const previewed = useRef(false);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (previewed.current) previewTheme(null);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const preview = (id: ConcreteTheme | null) => {
|
||||
previewed.current = true;
|
||||
if (id !== null) return picker.preview(id);
|
||||
picker.restore();
|
||||
if (shown !== currentThemeChoice()) previewTheme(shown);
|
||||
};
|
||||
return (
|
||||
<Row label="Theme">
|
||||
<Select<ConcreteTheme>
|
||||
value={shown}
|
||||
options={themeSelectOptions(choices, shown)}
|
||||
onChange={setTheme}
|
||||
onPreview={preview}
|
||||
aria-label="Theme"
|
||||
disabled={sync}
|
||||
/>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
* parts also make the Git window's Local Changes / Stash tabs and the Commit dialog.
|
||||
*/
|
||||
import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { formatBinding, isMacHost } from "@/platform/keymap";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type PointerEvent } from "react";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import clsx from "clsx";
|
||||
@@ -225,15 +224,8 @@ export function listMenu(id: string, active: boolean, files: readonly FileStatus
|
||||
];
|
||||
}
|
||||
|
||||
/** Paths Delete… applies to: only when every selected file is unversioned (versioned ones are rolled back). */
|
||||
export function deletableUnversioned(nodes: ChangeNode[]): string[] {
|
||||
const files = filesOf(nodes);
|
||||
return files.length && files.every((f) => f.unstaged === "untracked") ? files.map((f) => f.path) : [];
|
||||
}
|
||||
|
||||
export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuItem[] {
|
||||
const files = filesOf(nodes);
|
||||
const deletable = deletableUnversioned(nodes);
|
||||
const paths = files.map((f) => f.path);
|
||||
const first = nodes.find((n) => n.type === "file");
|
||||
const untracked = files.filter((f) => f.unstaged === "untracked");
|
||||
@@ -256,15 +248,9 @@ export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuIte
|
||||
...(untracked.length
|
||||
? [
|
||||
{ kind: "action" as const, action: "vcs.addToVcs", arg: untracked.map((f) => f.path) },
|
||||
...(deletable.length
|
||||
? [
|
||||
{
|
||||
label: "Delete…",
|
||||
icon: "trash",
|
||||
shortcut: formatBinding(isMacHost() ? "Backspace" : "Delete"),
|
||||
run: () => void deleteUnversioned(deletable),
|
||||
},
|
||||
]
|
||||
// Only when every selected file is unversioned: versioned ones are rolled back, not deleted.
|
||||
...(untracked.length === files.length
|
||||
? [{ label: "Delete…", icon: "trash", run: () => void deleteUnversioned(untracked.map((f) => f.path)) }]
|
||||
: []),
|
||||
]
|
||||
: []),
|
||||
@@ -532,17 +518,11 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
e.stopPropagation();
|
||||
toggle(selectedNodes());
|
||||
} else if ((e.key === "Delete" || e.key === "Backspace") && !e.metaKey) {
|
||||
const nodes = selectedNodes();
|
||||
const group = nodes.find((x) => x.type === "group" && x.changelist);
|
||||
const deletable = group ? [] : deletableUnversioned(nodes);
|
||||
const group = selectedNodes().find((x) => x.type === "group" && x.changelist);
|
||||
if (group?.changelist) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void executeAction("vcs.changelist.delete", group.changelist);
|
||||
} else if (deletable.length) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void deleteUnversioned(deletable);
|
||||
}
|
||||
} else if (e.key === "F4") {
|
||||
const n = selectedNodes().find((x) => x.type === "file");
|
||||
|
||||
@@ -13,7 +13,7 @@ vi.mock("../dialogs", async (original) => ({
|
||||
confirmDialog: mocks.confirm,
|
||||
}));
|
||||
|
||||
const { deletableUnversioned, nodeMenu } = await import("../CommitView");
|
||||
const { nodeMenu } = await import("../CommitView");
|
||||
const { deleteUnversioned } = await import("../changeOps");
|
||||
|
||||
const file = (rel: string, unstaged: FileStatus["unstaged"]): ChangeNode => {
|
||||
@@ -36,16 +36,6 @@ describe("Delete… for unversioned files", () => {
|
||||
expect(deleteItem(nodeMenu([file("c.txt", "modified")], ["/p"]))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("shows the Delete key and gives the key handler the same paths", () => {
|
||||
expect(deleteItem(nodeMenu([file("a.txt", "untracked")], ["/p"]))).toMatchObject({ shortcut: "⌫" });
|
||||
expect(deletableUnversioned([file("a.txt", "untracked"), file("b.txt", "untracked")])).toEqual([
|
||||
"/p/a.txt",
|
||||
"/p/b.txt",
|
||||
]);
|
||||
expect(deletableUnversioned([file("a.txt", "untracked"), file("c.txt", "modified")])).toEqual([]);
|
||||
expect(deletableUnversioned([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("asks first, then deletes each file", async () => {
|
||||
mocks.confirm.mockResolvedValueOnce(false);
|
||||
await deleteUnversioned(["/p/a.txt"]);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { registerVcsActions } from "../actions";
|
||||
import { useVcs } from "../store";
|
||||
import { useCommit } from "../commitStore";
|
||||
@@ -9,11 +8,10 @@ import { initialChangelists, useChangelists } from "../changelists";
|
||||
import { chainNeighbour } from "../diffInput";
|
||||
|
||||
const opened = vi.hoisted(() => vi.fn());
|
||||
const project = vi.hoisted(() => ({ paths: [] as string[] }));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
editorService: () => ({ openInput: opened }),
|
||||
projectViewSelection: () => project.paths,
|
||||
projectViewSelection: () => [],
|
||||
}));
|
||||
vi.mock("../comparePaths", () => ({ showDirectoryWorkingDiff: async () => false }));
|
||||
|
||||
@@ -31,11 +29,9 @@ let unregister: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
opened.mockClear();
|
||||
project.paths = [];
|
||||
setContext("activeToolWindow", "");
|
||||
const files = [status("z.ts"), status("b.ts"), status("a.ts"), status("other.ts")];
|
||||
useVcs.setState({ root: "/repo", roots: ["/repo"], status: files, byPath: new Map(files.map((f) => [f.path, f])) });
|
||||
useCommit.setState({ groupByDir: false, selection: [] });
|
||||
useCommit.setState({ groupByDir: false });
|
||||
const state = initialChangelists();
|
||||
state.lists.push({ id: "other", name: "Other", comment: "" });
|
||||
state.files = { "other.ts": "other" };
|
||||
@@ -45,7 +41,6 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
unregister();
|
||||
setContext("activeToolWindow", "");
|
||||
useVcs.setState(vcs);
|
||||
useCommit.setState(commit);
|
||||
useChangelists.setState(lists);
|
||||
@@ -95,20 +90,3 @@ it("keeps repository grouping in a changelist's chain", async () => {
|
||||
"/repo/module/b.ts",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows the selected change rather than a Project view selection kept from earlier", async () => {
|
||||
// The Project view keeps its selection while the Commit window has focus: ⌘D must open
|
||||
// the file selected in the changes tree, not the one still selected there.
|
||||
project.paths = ["/repo/z.ts"];
|
||||
setContext("activeToolWindow", "commit");
|
||||
useCommit.setState({ selection: ["/repo/b.ts"] });
|
||||
await getAction("vcs.showDiff")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
|
||||
expect(opened.mock.calls[0]![0].data.path).toBe("/repo/b.ts");
|
||||
});
|
||||
|
||||
it("shows a Project view selection outside the changes tree", async () => {
|
||||
project.paths = ["/repo/z.ts"];
|
||||
setContext("activeToolWindow", "project");
|
||||
await getAction("vcs.showDiff")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
|
||||
expect(opened.mock.calls[0]![0].data.path).toBe("/repo/z.ts");
|
||||
});
|
||||
@@ -75,34 +75,16 @@ export const commitWindowFocused = () => {
|
||||
return active === "commit" || (active === "git" && useGitLog.getState().tab === "changes");
|
||||
};
|
||||
|
||||
/** The action's own paths, or the changes tree's selection while the tree has focus. */
|
||||
function changedPaths(arg: unknown): string[] {
|
||||
/** Files the current context refers to: argument, commit view selection, or the active file. */
|
||||
function contextPaths(arg: unknown): string[] {
|
||||
const explicit = argPaths(arg);
|
||||
if (explicit?.length) return explicit;
|
||||
const sel = useCommit.getState().selection;
|
||||
return commitWindowFocused() ? sel : [];
|
||||
}
|
||||
|
||||
/** Files the current context refers to: argument, commit view selection, or the active file. */
|
||||
function contextPaths(arg: unknown): string[] {
|
||||
const changed = changedPaths(arg);
|
||||
if (changed.length) return changed;
|
||||
if (commitWindowFocused() && sel.length) return sel;
|
||||
const active = maybeEditorService()?.activePath();
|
||||
return active ? [active] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths a selection-based action targets: the argument, else the changes tree's selection,
|
||||
* else the Project view's — it keeps its selection while another view has focus — else the
|
||||
* active file.
|
||||
*/
|
||||
function selectedPaths(arg: unknown): string[] {
|
||||
const changed = changedPaths(arg);
|
||||
if (changed.length) return changed;
|
||||
const project = projectViewSelection();
|
||||
return project.length ? project : contextPaths(arg);
|
||||
}
|
||||
|
||||
function showGitWindow() {
|
||||
toolWindowService().show("git", true);
|
||||
}
|
||||
@@ -339,7 +321,8 @@ export function registerVcsActions(): () => void {
|
||||
if (ctx.shelfFocus && arg === undefined) return showShelfDiff();
|
||||
const line =
|
||||
arg && typeof arg === "object" && "line" in arg ? Number((arg as { line: unknown }).line) : undefined;
|
||||
const paths = selectedPaths(arg);
|
||||
const selection = arg === undefined ? projectViewSelection() : [];
|
||||
const paths = selection.length ? selection : contextPaths(arg);
|
||||
if (!paths.length) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
|
||||
return;
|
||||
@@ -371,7 +354,8 @@ export function registerVcsActions(): () => void {
|
||||
icon: "diff",
|
||||
when: VCS,
|
||||
run: async ({ arg }) => {
|
||||
const paths = selectedPaths(arg);
|
||||
const selection = arg === undefined ? projectViewSelection() : [];
|
||||
const paths = selection.length ? selection : contextPaths(arg);
|
||||
if (!paths.length) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Open or select a file or folder to compare" });
|
||||
return;
|
||||
|
||||
@@ -111,10 +111,6 @@
|
||||
border-radius: var(--radius-small);
|
||||
}
|
||||
/* Push dialogs: the list fills the body so a resizable window shows more rows. */
|
||||
.pushDialog > [data-dialog-body] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.pushTreeWrap {
|
||||
flex: 1;
|
||||
min-height: 220px;
|
||||
@@ -131,7 +127,6 @@
|
||||
}
|
||||
/* Push dialogs: the outgoing commits' changed files below the commits, the diff beside them. */
|
||||
.pushChanges {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
|
||||
@@ -149,9 +149,6 @@ interface PushNode {
|
||||
children?: PushNode[];
|
||||
}
|
||||
|
||||
// A long outgoing list scrolls inside the dialog instead of growing it to the screen (IDEA: 800×450 centre panel).
|
||||
const PUSH_DIALOG_MAX_HEIGHT = 720;
|
||||
|
||||
function MultiPushDialog({ onClose }: { onClose: () => void }) {
|
||||
const roots = useVcs((s) => s.roots);
|
||||
const [repos, setRepos] = useState<RepoPush[] | null>(null);
|
||||
@@ -231,8 +228,6 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
|
||||
title="Push Commits"
|
||||
onClose={onClose}
|
||||
width={repos?.some((r) => r.commits.length) ? 860 : 620}
|
||||
maxHeight={PUSH_DIALOG_MAX_HEIGHT}
|
||||
className={styles.pushDialog}
|
||||
resizable="both"
|
||||
footerStart={
|
||||
<>
|
||||
@@ -446,8 +441,6 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
|
||||
title={head ? tx`Push Commits to ${upstream ?? "remote"}` : "Push"}
|
||||
onClose={onClose}
|
||||
width={commits?.length ? 860 : 620}
|
||||
maxHeight={PUSH_DIALOG_MAX_HEIGHT}
|
||||
className={styles.pushDialog}
|
||||
resizable="both"
|
||||
footerStart={
|
||||
<>
|
||||
|
||||
@@ -124,7 +124,7 @@ export function recentMenu(project: RecentProject, onOpened?: () => void): MenuI
|
||||
label: "Open in New Window",
|
||||
icon: "folder-open",
|
||||
run: () =>
|
||||
void call(commands.windowOpenRemote(remote.target, remote.path, true))
|
||||
void call(commands.windowOpenRemote(remote.sshConfig, remote.path, true))
|
||||
.then(() => onOpened?.())
|
||||
.catch(() => undefined),
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const openProject = vi.fn();
|
||||
const openRemoteProject = vi.fn();
|
||||
const UNC = String.raw`\\wsl.localhost\Ubuntu\home\me\app`;
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...real.commands,
|
||||
wslResolve: async (p: string) =>
|
||||
p === UNC ? { target: { kind: "wsl", distro: "Ubuntu" }, path: "/home/me/app" } : null,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/project", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/project")>();
|
||||
return { ...real, openProject: (p: string) => openProject(p) };
|
||||
});
|
||||
vi.mock("@/workbench/projectWindow", () => ({
|
||||
openRemoteProject: (...a: unknown[]) => openRemoteProject(...a),
|
||||
}));
|
||||
|
||||
const { openRecent } = await import("./recent");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
|
||||
beforeEach(() => {
|
||||
openProject.mockReset();
|
||||
openRemoteProject.mockReset().mockResolvedValue(true);
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
});
|
||||
|
||||
describe("openRecent", () => {
|
||||
it("opens a legacy WSL UNC recent through the distro, not as a local folder", async () => {
|
||||
expect(await openRecent({ path: UNC, name: "app" })).toBe(true);
|
||||
expect(openRemoteProject).toHaveBeenCalledWith(
|
||||
{ kind: "wsl", distro: "Ubuntu" },
|
||||
"/home/me/app",
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still opens a plain local recent locally", async () => {
|
||||
await openRecent({ path: "/p/local", name: "local" });
|
||||
expect(openProject).toHaveBeenCalledWith("/p/local");
|
||||
expect(openRemoteProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,26 +1,9 @@
|
||||
/** Recent projects: loading, filtering, opening and removal. */
|
||||
import { create } from "zustand";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import {
|
||||
commands,
|
||||
IpcError,
|
||||
isCancelled,
|
||||
isTauri,
|
||||
type RecentProject,
|
||||
type RecentProjectGroup,
|
||||
type RemoteTarget,
|
||||
} from "@/platform/ipc";
|
||||
import { commands, IpcError, isCancelled, isTauri, type RecentProject, type RecentProjectGroup } from "@/platform/ipc";
|
||||
import { openProject, useProject } from "@/platform/project";
|
||||
import {
|
||||
connectRemote,
|
||||
forgetRemote,
|
||||
parseRemoteLocation,
|
||||
recentRemotes,
|
||||
remoteLocation,
|
||||
resolveRemoteLocation,
|
||||
sameTarget,
|
||||
targetName,
|
||||
} from "@/platform/remote";
|
||||
import { connectRemote, forgetRemote, parseRemoteLocation, recentRemotes, remoteLocation } from "@/platform/remote";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { fuzzyMatch } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
@@ -81,7 +64,7 @@ export async function loadRecent() {
|
||||
/** The recent remote projects (Remote Development) among the local ones, most recent first. */
|
||||
function withRemotes(local: RecentProject[]): RecentProject[] {
|
||||
const remote: RecentProject[] = recentRemotes().map((r) => ({
|
||||
path: remoteLocation(r.target, r.path),
|
||||
path: remoteLocation(r.sshConfig, r.path),
|
||||
name: r.name,
|
||||
openedAtMs: r.openedAtMs,
|
||||
branch: null,
|
||||
@@ -94,8 +77,7 @@ function withRemotes(local: RecentProject[]): RecentProject[] {
|
||||
export function remoteDisplay(location: string): string | null {
|
||||
const r = parseRemoteLocation(location);
|
||||
if (!r) return null;
|
||||
const host =
|
||||
recentRemotes().find((x) => sameTarget(x.target, r.target) && x.path === r.path)?.host || targetName(r.target);
|
||||
const host = recentRemotes().find((x) => x.sshConfig === r.sshConfig && x.path === r.path)?.host || r.sshConfig;
|
||||
return `${host}:${r.path}`;
|
||||
}
|
||||
|
||||
@@ -106,7 +88,7 @@ export async function removeRecent(path: string) {
|
||||
}));
|
||||
const remote = parseRemoteLocation(path);
|
||||
if (remote) {
|
||||
forgetRemote(remote.target, remote.path);
|
||||
forgetRemote(remote.sshConfig, remote.path);
|
||||
return;
|
||||
}
|
||||
if (!isTauri()) return;
|
||||
@@ -125,7 +107,7 @@ export async function openRecent(project: Pick<RecentProject, "path" | "name">):
|
||||
});
|
||||
return false;
|
||||
}
|
||||
const remote = await resolveRemoteLocation(project.path);
|
||||
const remote = parseRemoteLocation(project.path);
|
||||
if (remote) return openRemote(project, remote);
|
||||
const current = useProject.getState().project;
|
||||
if (current?.root === project.path) return true;
|
||||
@@ -157,12 +139,12 @@ export async function openRecent(project: Pick<RecentProject, "path" | "name">):
|
||||
|
||||
async function openRemote(
|
||||
project: Pick<RecentProject, "path" | "name">,
|
||||
remote: { target: RemoteTarget; path: string },
|
||||
remote: { sshConfig: string; path: string },
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
return await openRemoteProject(remote.target, remote.path, async () => {
|
||||
return await openRemoteProject(remote.sshConfig, remote.path, async () => {
|
||||
useRecent.setState({ opening: project.path });
|
||||
await connectRemote(remote.target, remote.path);
|
||||
await connectRemote(remote.sshConfig, remote.path);
|
||||
});
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return false;
|
||||
|
||||
@@ -1,26 +1,15 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const openProject = vi.fn();
|
||||
const connectRemote = vi.fn();
|
||||
const UNC = String.raw`\\wsl.localhost\Ubuntu\home\me\app`;
|
||||
|
||||
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 } }),
|
||||
wslResolve: async (p: string) =>
|
||||
p === UNC ? { target: { kind: "wsl", distro: "Ubuntu" }, path: "/home/me/app" } : null,
|
||||
},
|
||||
commands: { ...real.commands, settingsGet: async () => ({ general: { reopenLastProject: true } }) },
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/remote", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/remote")>();
|
||||
return { ...real, connectRemote: (t: unknown, p: string) => connectRemote(t, p) };
|
||||
});
|
||||
vi.mock("@tauri-apps/api/window", () => ({ getCurrentWindow: () => ({ label: "main" }) }));
|
||||
vi.mock("@/platform/project", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/project")>();
|
||||
@@ -32,7 +21,6 @@ const { provideStartupLaunch, useProject } = await import("@/platform/project");
|
||||
|
||||
beforeEach(() => {
|
||||
openProject.mockReset();
|
||||
connectRemote.mockReset();
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
sessionStorage.clear();
|
||||
localStorage.setItem("openidea.session.openProject", "/p/last");
|
||||
@@ -79,12 +67,4 @@ describe("reopenLastProject", () => {
|
||||
await reopenLastProject();
|
||||
expect(openProject).toHaveBeenCalledWith("/p/last");
|
||||
});
|
||||
|
||||
it("restores a session saved as a WSL UNC folder through the distro", async () => {
|
||||
localStorage.setItem("openidea.session.openProject", UNC);
|
||||
provideStartupLaunch(Promise.resolve());
|
||||
await reopenLastProject();
|
||||
expect(connectRemote).toHaveBeenCalledWith({ kind: "wsl", distro: "Ubuntu" }, "/home/me/app");
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { create } from "zustand";
|
||||
import { commands, isCancelled, isTauri, type Settings } from "@/platform/ipc";
|
||||
import { openProject, startupLaunchHandled, useProject } from "@/platform/project";
|
||||
import { connectRemote, projectLocation, resolveRemoteLocation } from "@/platform/remote";
|
||||
import { connectRemote, parseRemoteLocation, projectLocation } from "@/platform/remote";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
const SESSION_KEY = "openidea.session.openProject";
|
||||
@@ -117,8 +117,8 @@ async function reopen(path: string) {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1) || path;
|
||||
useSession.setState({ reopening: path });
|
||||
try {
|
||||
const remote = await resolveRemoteLocation(path);
|
||||
if (remote) await connectRemote(remote.target, remote.path);
|
||||
const remote = parseRemoteLocation(path);
|
||||
if (remote) await connectRemote(remote.sshConfig, remote.path);
|
||||
else await openProject(path);
|
||||
} catch (e) {
|
||||
write(SESSION_KEY, null);
|
||||
|
||||
@@ -248,7 +248,7 @@ describe("catalogs", () => {
|
||||
it("exist for exactly the supported locales", () => {
|
||||
expect(translated.length).toBeGreaterThan(0);
|
||||
expect(Object.keys(translations).sort()).toEqual(translated);
|
||||
expect(Object.keys(texts).sort()).toEqual([...SUPPORTED_LOCALES].sort());
|
||||
expect(Object.keys(texts).sort()).toEqual(translated);
|
||||
});
|
||||
|
||||
it("translate source text into non-empty text", () => {
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"Connect through:": "Connect through:",
|
||||
"Connect through": "Connect through",
|
||||
"WSL distribution:": "WSL distribution:",
|
||||
"WSL distribution": "WSL distribution",
|
||||
"Project runs on {label}": "Project runs on {label}",
|
||||
"Forwarding ports is not supported in a WSL project yet": "Forwarding ports is not supported in a WSL project yet"
|
||||
}
|
||||
@@ -5807,18 +5807,18 @@
|
||||
"Unsigned": "Sin firmar",
|
||||
"Roll Back to {previousVersion}": "Revertir a {previousVersion}",
|
||||
"Install Plugin from Package File…": "Instalar plugin desde archivo de paquete…",
|
||||
"Import Theme from JetBrains IDE…": "Importar tema desde un IDE de JetBrains…",
|
||||
"Import Theme from IntelliJ IDE…": "Importar tema desde IntelliJ IDE…",
|
||||
"Import IntelliJ Theme from File…": "Importar tema de IntelliJ desde archivo…",
|
||||
"Import Theme from JetBrains IDE": "Importar tema desde un IDE de JetBrains",
|
||||
"Import Theme from IntelliJ IDE": "Importar tema desde IntelliJ IDE",
|
||||
"Import IntelliJ Theme": "Importar tema de IntelliJ",
|
||||
"IntelliJ theme plugin or theme file": "Plugin de tema o archivo de tema de IntelliJ",
|
||||
"Could not import the IntelliJ theme": "No se pudo importar el tema de IntelliJ",
|
||||
"Import": "Importar",
|
||||
"In use": "En uso",
|
||||
"JetBrains theme plugins": "Plugins de temas de JetBrains",
|
||||
"Looking for JetBrains themes": "Buscando temas de JetBrains",
|
||||
"Looking for JetBrains themes…": "Buscando temas de JetBrains…",
|
||||
"Theme plugins installed in the JetBrains IDEs on this computer. Importing one installs it with all its themes; choose the theme to use in Settings › Appearance. Colours without an OpenIDEA counterpart keep the default theme colours.": "Plugins de temas instalados en los IDE de JetBrains en este equipo. Al importar uno se instala con todos sus temas; elija el tema que desea usar en Configuración › Apariencia. Los colores sin equivalente en OpenIDEA conservan los colores del tema predeterminado.",
|
||||
"IntelliJ themes": "Temas de IntelliJ",
|
||||
"Looking for IntelliJ themes": "Buscando temas de IntelliJ",
|
||||
"Looking for IntelliJ themes…": "Buscando temas de IntelliJ…",
|
||||
"Theme plugins installed in the JetBrains IDEs on this computer. Importing a theme brings every theme of its plugin and applies the chosen one. Colours without an OpenIDEA counterpart keep the default theme colours.": "Plugins de temas instalados en los IDE de JetBrains en este equipo. Al importar un tema se incluyen todos los temas de su plugin y se aplica el elegido. Los colores sin equivalente en OpenIDEA conservan los colores del tema predeterminado.",
|
||||
"1 theme": "1 tema",
|
||||
"{count} themes": "{count} temas",
|
||||
"No theme plugins found in JetBrains IDEs on this computer. Choose a theme plugin downloaded from the JetBrains Marketplace (.jar or .zip) or a .theme.json file instead.": "No se encontraron plugins de temas en los IDE de JetBrains en este equipo. En su lugar, elija un plugin de tema descargado de JetBrains Marketplace (.jar o .zip) o un archivo .theme.json.",
|
||||
|
||||
@@ -4470,12 +4470,6 @@
|
||||
"Remote Development": "远程开发",
|
||||
"The project runs on the remote host; the IDE backend is installed there on first use.": "项目在远程主机上运行,首次使用时会在该主机上安装 IDE 后端。",
|
||||
"SSH configuration:": "SSH 配置:",
|
||||
"Connect through:": "连接方式:",
|
||||
"Connect through": "连接方式",
|
||||
"WSL distribution:": "WSL 发行版:",
|
||||
"WSL distribution": "WSL 发行版",
|
||||
"Project runs on {label}": "项目运行于 {label}",
|
||||
"Forwarding ports is not supported in a WSL project yet": "WSL 项目暂不支持端口转发",
|
||||
"No SSH configurations": "没有 SSH 配置",
|
||||
"Project directory:": "项目目录:",
|
||||
"Remote Development…": "远程开发…",
|
||||
@@ -5842,18 +5836,18 @@
|
||||
"Unsigned": "未签名",
|
||||
"Roll Back to {previousVersion}": "回滚到 {previousVersion}",
|
||||
"Install Plugin from Package File…": "从插件包文件安装…",
|
||||
"Import Theme from JetBrains IDE…": "从 JetBrains IDE 导入主题…",
|
||||
"Import Theme from IntelliJ IDE…": "从 IntelliJ IDE 导入主题…",
|
||||
"Import IntelliJ Theme from File…": "从文件导入 IntelliJ 主题…",
|
||||
"Import Theme from JetBrains IDE": "从 JetBrains IDE 导入主题",
|
||||
"Import Theme from IntelliJ IDE": "从 IntelliJ IDE 导入主题",
|
||||
"Import IntelliJ Theme": "导入 IntelliJ 主题",
|
||||
"IntelliJ theme plugin or theme file": "IntelliJ 主题插件或主题文件",
|
||||
"Could not import the IntelliJ theme": "无法导入 IntelliJ 主题",
|
||||
"Import": "导入",
|
||||
"In use": "使用中",
|
||||
"JetBrains theme plugins": "JetBrains 主题插件",
|
||||
"Looking for JetBrains themes": "正在查找 JetBrains 主题",
|
||||
"Looking for JetBrains themes…": "正在查找 JetBrains 主题…",
|
||||
"Theme plugins installed in the JetBrains IDEs on this computer. Importing one installs it with all its themes; choose the theme to use in Settings › Appearance. Colours without an OpenIDEA counterpart keep the default theme colours.": "此计算机上 JetBrains IDE 中安装的主题插件。导入后会安装该插件及其全部主题;要使用的主题请在“设置 › 外观”中选择。没有对应 OpenIDEA 颜色的项保留默认主题的颜色。",
|
||||
"IntelliJ themes": "IntelliJ 主题",
|
||||
"Looking for IntelliJ themes": "正在查找 IntelliJ 主题",
|
||||
"Looking for IntelliJ themes…": "正在查找 IntelliJ 主题…",
|
||||
"Theme plugins installed in the JetBrains IDEs on this computer. Importing a theme brings every theme of its plugin and applies the chosen one. Colours without an OpenIDEA counterpart keep the default theme colours.": "此计算机上 JetBrains IDE 中安装的主题插件。导入某个主题会一并导入其插件的全部主题,并应用所选主题。没有对应 OpenIDEA 颜色的项保留默认主题的颜色。",
|
||||
"1 theme": "1 个主题",
|
||||
"{count} themes": "{count} 个主题",
|
||||
"No theme plugins found in JetBrains IDEs on this computer. Choose a theme plugin downloaded from the JetBrains Marketplace (.jar or .zip) or a .theme.json file instead.": "在此计算机上的 JetBrains IDE 中未找到主题插件。请改为选择从 JetBrains Marketplace 下载的主题插件(.jar 或 .zip)或 .theme.json 文件。",
|
||||
|
||||
@@ -108,7 +108,6 @@ const UNTRANSLATED = new Set<string>([
|
||||
"loopvar,rangefunc",
|
||||
// SSH and run-target placeholders
|
||||
"SSH",
|
||||
"WSL",
|
||||
"example.com",
|
||||
"java",
|
||||
"node",
|
||||
|
||||
@@ -8,18 +8,9 @@ import { confirmProjectTrust } from "./projectTrust";
|
||||
import { Channel, type InvokeArgs, type InvokeOptions } from "@tauri-apps/api/core";
|
||||
import { invokeLocal, setInvokeRoute, type InvokeRoute } from "./tauriCore";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
isTauri,
|
||||
type ChannelFrame,
|
||||
type RemoteProgress,
|
||||
type RemoteSession,
|
||||
type RemoteTarget,
|
||||
} from "./ipc";
|
||||
import { call, commands, isTauri, type ChannelFrame, type RemoteProgress, type RemoteSession } from "./ipc";
|
||||
import { isClientSetting, overlayClientSettings } from "./clientSettings";
|
||||
import type { Settings } from "./ipc";
|
||||
import { usePlatform } from "./platformInfo";
|
||||
import { useProject } from "./project";
|
||||
|
||||
interface RemoteState {
|
||||
@@ -30,7 +21,6 @@ export const useRemote = create<RemoteState>(() => ({ session: null }));
|
||||
|
||||
let routed = new Set<string>();
|
||||
let nextChannel = 1;
|
||||
const BUILD_MODEL_COMMANDS = new Set(["build_model", "build_sync", "gradle_link_projects", "gradle_unlink_projects"]);
|
||||
|
||||
/**
|
||||
* The arguments with each `Channel` replaced by `{ $channel: id }`, and the
|
||||
@@ -58,12 +48,7 @@ async function remoteInvoke(cmd: string, args?: InvokeArgs, options?: InvokeOpti
|
||||
const onChannel = new Channel<ChannelFrame>();
|
||||
onChannel.onmessage = (frame) => channels.get(frame.id)?.onmessage(JSON.parse(frame.data));
|
||||
const result = await invokeLocal<string>("remote_invoke", { cmd, args: json, onChannel }, options);
|
||||
const value = JSON.parse(result);
|
||||
// Released servers predating independent Gradle builds return a single build.
|
||||
if (BUILD_MODEL_COMMANDS.has(cmd) && value?.gradle && !Array.isArray(value.gradle)) {
|
||||
value.gradle = [value.gradle];
|
||||
}
|
||||
return value;
|
||||
return JSON.parse(result);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,11 +119,6 @@ export function isRemoteWindow(): boolean {
|
||||
return useRemote.getState().session !== null;
|
||||
}
|
||||
|
||||
/** The OS this window's commands run on: the remote server's, else this desktop's (`usePlatform`). */
|
||||
export function hostOs(): string {
|
||||
return useRemote.getState().session?.os ?? usePlatform.getState().os;
|
||||
}
|
||||
|
||||
/** Re-attaches after a reload (the backend keeps the connection per window). */
|
||||
export async function restoreRemote(): Promise<RemoteSession | null> {
|
||||
if (!isTauri()) return null;
|
||||
@@ -153,19 +133,19 @@ export const useRemoteProgress = create<{ progress: RemoteProgress | null; locat
|
||||
location: null,
|
||||
}));
|
||||
|
||||
/** Opens `path` of `target` (an SSH host or a WSL distribution) in this window. */
|
||||
export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
/** Opens `path` on the host of SSH configuration `sshConfig` in this window. */
|
||||
export async function connectRemote(sshConfig: string, path: string) {
|
||||
useProject.setState({ opening: true });
|
||||
const onProgress = new Channel<RemoteProgress>();
|
||||
onProgress.onmessage = (progress) => useRemoteProgress.setState({ progress });
|
||||
useRemoteProgress.setState({
|
||||
progress: { stage: "connecting", fraction: null },
|
||||
location: remoteLocation(target, path),
|
||||
location: remoteLocation(sshConfig, path),
|
||||
});
|
||||
try {
|
||||
const r = await call(commands.remoteConnect(target, path, onProgress));
|
||||
enableRemote({ target: r.target, root: r.root, host: r.host, os: r.os, commands: r.commands });
|
||||
if (takeLegacyRemoteTrust(r.target, path, r.host)) {
|
||||
const r = await call(commands.remoteConnect(sshConfig, path, onProgress));
|
||||
enableRemote({ sshConfig: r.sshConfig, root: r.root, host: r.host, commands: r.commands });
|
||||
if (takeLegacyRemoteTrust(r.sshConfig, path, r.host)) {
|
||||
const status = await call(commands.projectTrustStatus(r.root));
|
||||
if (!status.decided) await call(commands.projectTrustSet(r.root, true, false));
|
||||
}
|
||||
@@ -181,7 +161,7 @@ export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
r.project.settings = await clientSettings(r.project.settings);
|
||||
useProject.setState({ project: r.project, settings: r.project.settings });
|
||||
rememberRemote({
|
||||
target: r.target,
|
||||
sshConfig: r.sshConfig,
|
||||
path: r.root,
|
||||
name: r.project.name,
|
||||
host: r.host,
|
||||
@@ -202,54 +182,32 @@ export async function disconnectRemote() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Remote project locations: `ssh://<configuration id>/<absolute path>` or
|
||||
// `wsl://<distribution>/<absolute path>`, what the session and the recent projects
|
||||
// remember for a remote window.
|
||||
// Remote project locations: `ssh://<configuration id>/<absolute path>`, what the
|
||||
// session and the recent projects remember for a remote window.
|
||||
|
||||
const SCHEMES = { ssh: "ssh://", wsl: "wsl://" } as const;
|
||||
const SCHEME = "ssh://";
|
||||
|
||||
/** The SSH configuration id or the WSL distribution name. */
|
||||
export function targetName(target: RemoteTarget): string {
|
||||
return target.kind === "ssh" ? target.config : target.distro;
|
||||
export function remoteLocation(sshConfig: string, path: string): string {
|
||||
return `${SCHEME}${encodeURIComponent(sshConfig)}${path.startsWith("/") ? "" : "/"}${path}`;
|
||||
}
|
||||
|
||||
export function sameTarget(a: RemoteTarget, b: RemoteTarget): boolean {
|
||||
return a.kind === b.kind && targetName(a) === targetName(b);
|
||||
}
|
||||
|
||||
export function remoteLocation(target: RemoteTarget, path: string): string {
|
||||
return `${SCHEMES[target.kind]}${encodeURIComponent(targetName(target))}${path.startsWith("/") ? "" : "/"}${path}`;
|
||||
}
|
||||
|
||||
export function parseRemoteLocation(location: string): { target: RemoteTarget; path: string } | null {
|
||||
const kind = (Object.keys(SCHEMES) as (keyof typeof SCHEMES)[]).find((k) => location.startsWith(SCHEMES[k]));
|
||||
if (!kind) return null;
|
||||
const rest = location.slice(SCHEMES[kind].length);
|
||||
export function parseRemoteLocation(location: string): { sshConfig: string; path: string } | null {
|
||||
if (!location.startsWith(SCHEME)) return null;
|
||||
const rest = location.slice(SCHEME.length);
|
||||
const slash = rest.indexOf("/");
|
||||
if (slash <= 0) return null;
|
||||
const name = decodeURIComponent(rest.slice(0, slash));
|
||||
const target: RemoteTarget = kind === "ssh" ? { kind, config: name } : { kind, distro: name };
|
||||
return { target, path: rest.slice(slash) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote project a saved location stands for: a `ssh://` / `wsl://` location, or a
|
||||
* `\\wsl.localhost\<distro>\…` folder remembered before WSL projects existed (it is a WSL
|
||||
* project, not a network folder). `null` for a plain local path.
|
||||
*/
|
||||
export async function resolveRemoteLocation(location: string): Promise<{ target: RemoteTarget; path: string } | null> {
|
||||
return parseRemoteLocation(location) ?? (await commands.wslResolve(location).catch(() => null));
|
||||
return { sshConfig: decodeURIComponent(rest.slice(0, slash)), path: rest.slice(slash) };
|
||||
}
|
||||
|
||||
/** The location of this window's project: remote, else its local root. */
|
||||
export function projectLocation(root: string | null | undefined): string | null {
|
||||
if (!root) return null;
|
||||
const session = useRemote.getState().session;
|
||||
return session && session.root === root ? remoteLocation(session.target, root) : root;
|
||||
return session && session.root === root ? remoteLocation(session.sshConfig, root) : root;
|
||||
}
|
||||
|
||||
export interface RecentRemote {
|
||||
target: RemoteTarget;
|
||||
sshConfig: string;
|
||||
path: string;
|
||||
name: string;
|
||||
/** `user@host:port` when it was opened. */
|
||||
@@ -272,23 +230,12 @@ export function initializeRemoteTrustMigration() {
|
||||
}
|
||||
}
|
||||
|
||||
/** An entry as stored: before WSL it carried `sshConfig` instead of `target`. */
|
||||
function normalize(entry: RecentRemote & { sshConfig?: string }): RecentRemote | null {
|
||||
if (!entry || !entry.path) return null;
|
||||
const target = entry.target ?? (entry.sshConfig ? { kind: "ssh" as const, config: entry.sshConfig } : null);
|
||||
return target ? { ...entry, target } : null;
|
||||
}
|
||||
|
||||
/** Whether `path` on SSH `target` was remembered before the trust prompt existed (WSL never was). */
|
||||
export function takeLegacyRemoteTrust(target: RemoteTarget, path: string, host: string): boolean {
|
||||
if (target.kind !== "ssh") return false;
|
||||
export function takeLegacyRemoteTrust(sshConfig: string, path: string, host: string): boolean {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(TRUST_MIGRATION_KEY) ?? "[]");
|
||||
if (!Array.isArray(value)) return false;
|
||||
const matches = (stored: RecentRemote) => {
|
||||
const entry = normalize(stored);
|
||||
return entry !== null && sameTarget(entry.target, target) && entry.path === path && entry.host === host;
|
||||
};
|
||||
const matches = (entry: RecentRemote) =>
|
||||
entry?.sshConfig === sshConfig && entry.path === path && entry.host === host;
|
||||
const found = value.some(matches);
|
||||
localStorage.setItem(TRUST_MIGRATION_KEY, JSON.stringify(value.filter((entry) => !matches(entry))));
|
||||
return found;
|
||||
@@ -300,7 +247,7 @@ export function takeLegacyRemoteTrust(target: RemoteTarget, path: string, host:
|
||||
export function recentRemotes(): RecentRemote[] {
|
||||
try {
|
||||
const list = JSON.parse(localStorage.getItem(RECENT_KEY) ?? "[]") as unknown;
|
||||
return Array.isArray(list) ? list.map(normalize).filter((r): r is RecentRemote => r !== null) : [];
|
||||
return Array.isArray(list) ? (list as RecentRemote[]).filter((r) => r && r.sshConfig && r.path) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -314,15 +261,15 @@ function saveRemotes(list: RecentRemote[]) {
|
||||
}
|
||||
}
|
||||
|
||||
const sameRemote = (a: Pick<RecentRemote, "target" | "path">, b: Pick<RecentRemote, "target" | "path">) =>
|
||||
sameTarget(a.target, b.target) && a.path === b.path;
|
||||
const sameRemote = (a: Pick<RecentRemote, "sshConfig" | "path">, b: Pick<RecentRemote, "sshConfig" | "path">) =>
|
||||
a.sshConfig === b.sshConfig && a.path === b.path;
|
||||
|
||||
export function rememberRemote(entry: RecentRemote) {
|
||||
saveRemotes([entry, ...recentRemotes().filter((r) => !sameRemote(r, entry))]);
|
||||
}
|
||||
|
||||
export function forgetRemote(target: RemoteTarget, path: string) {
|
||||
saveRemotes(recentRemotes().filter((r) => !sameRemote(r, { target, path })));
|
||||
export function forgetRemote(sshConfig: string, path: string) {
|
||||
saveRemotes(recentRemotes().filter((r) => !sameRemote(r, { sshConfig, path })));
|
||||
}
|
||||
|
||||
// Any way of leaving the remote project (Close Project, opening a local one) ends remote routing.
|
||||
|
||||
@@ -3,7 +3,6 @@ import { CLIENT_SETTINGS_KEYS } from "./clientSettings";
|
||||
import { commands, call, type Settings } from "./ipc";
|
||||
import { loadSettings, useProject } from "./project";
|
||||
import { connectRemote, disableRemote, enableRemote, isRemoteWindow, remoteRouting } from "./remote";
|
||||
import { invoke as routedInvoke } from "./tauriCore";
|
||||
|
||||
const handlers = vi.hoisted(() => new Map<string, () => void>());
|
||||
vi.mock("./ipc", async (original) => ({
|
||||
@@ -42,13 +41,7 @@ beforeEach(() => {
|
||||
cmd === "remote_invoke" ? JSON.stringify(remote) : local,
|
||||
);
|
||||
Object.assign(window, { __TAURI_INTERNALS__: { invoke, transformCallback: () => 1 } });
|
||||
enableRemote({
|
||||
target: { kind: "ssh", config: "test" },
|
||||
root: "/remote",
|
||||
host: "test",
|
||||
os: "linux",
|
||||
commands: [...served],
|
||||
});
|
||||
enableRemote({ sshConfig: "test", root: "/remote", host: "test", commands: [...served] });
|
||||
});
|
||||
afterEach(() => {
|
||||
disableRemote();
|
||||
@@ -56,33 +49,6 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("remote client settings", () => {
|
||||
it.each([
|
||||
{ gradle: { dir: "app", projects: [] }, expected: [{ dir: "app", projects: [] }] },
|
||||
{
|
||||
gradle: [
|
||||
{ dir: "one", projects: [] },
|
||||
{ dir: "two", projects: [] },
|
||||
],
|
||||
expected: [
|
||||
{ dir: "one", projects: [] },
|
||||
{ dir: "two", projects: [] },
|
||||
],
|
||||
},
|
||||
{ gradle: null, expected: null },
|
||||
])("accepts the released and current remote Gradle build models: $gradle", async ({ gradle, expected }) => {
|
||||
for (const command of ["build_model", "build_sync", "gradle_link_projects", "gradle_unlink_projects"]) {
|
||||
enableRemote({
|
||||
target: { kind: "wsl", distro: "Ubuntu" },
|
||||
root: "/remote",
|
||||
host: "Ubuntu",
|
||||
os: "linux",
|
||||
commands: [command],
|
||||
});
|
||||
invoke.mockResolvedValue(JSON.stringify({ gradle, maven: null }));
|
||||
expect(await routedInvoke(command)).toEqual({ gradle: expected, maven: null });
|
||||
}
|
||||
});
|
||||
|
||||
it("ends remote routing before a successful local open is published, even at the same path", async () => {
|
||||
invoke.mockResolvedValueOnce({ root: "/remote", settings: local });
|
||||
await call(commands.openProject("/remote"));
|
||||
@@ -125,7 +91,7 @@ describe("remote client settings", () => {
|
||||
invoke.mockImplementation(async (cmd: string) =>
|
||||
cmd === "remote_connect"
|
||||
? {
|
||||
target: { kind: "ssh", config: "test" },
|
||||
sshConfig: "test",
|
||||
root: "/remote",
|
||||
host: "test",
|
||||
commands: [...served],
|
||||
@@ -135,7 +101,7 @@ describe("remote client settings", () => {
|
||||
? "null"
|
||||
: local,
|
||||
);
|
||||
await connectRemote({ kind: "ssh", config: "test" }, "/remote");
|
||||
await connectRemote("test", "/remote");
|
||||
expect(useProject.getState().settings).toMatchObject({ keymap: "my-map", editor: { tabSize: 2, fontSize: 19 } });
|
||||
});
|
||||
it("overlays the project snapshot used by the settings window", async () => {
|
||||
|
||||
@@ -168,21 +168,6 @@ describe("Dialog chrome", () => {
|
||||
expect([dialog.style.width, dialog.style.height]).toEqual(["600px", "400px"]);
|
||||
});
|
||||
|
||||
it("caps a content-sized dialog at maxHeight until it is resized", () => {
|
||||
render(
|
||||
<Dialog open onClose={() => {}} title="Push" resizable="both" maxHeight={720}>
|
||||
<div>rows</div>
|
||||
</Dialog>,
|
||||
);
|
||||
const dialog = screen.getByRole("dialog");
|
||||
expect(dialog.style.maxHeight).toBe("min(720px, 100%)");
|
||||
fireEvent.pointerDown(screen.getByRole("separator", { name: "Resize" }), { button: 0, clientX: 0, clientY: 0 });
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: 500, clientY: 800 });
|
||||
fireEvent.pointerUp(window);
|
||||
expect(dialog.style.maxHeight).toBe("");
|
||||
expect(dialog.style.height).not.toBe("");
|
||||
});
|
||||
|
||||
it("still drags a window dialog by its title bar", () => {
|
||||
render(
|
||||
<Dialog open onClose={() => {}} title="Usages Detected" buttons={safeDelete()} platform="other">
|
||||
|
||||
@@ -117,8 +117,6 @@ export interface DialogProps {
|
||||
resizable?: "both";
|
||||
minWidth?: number;
|
||||
minHeight?: number;
|
||||
/** Height cap while content-sized; a manual resize lifts it. */
|
||||
maxHeight?: number;
|
||||
/** Size to open at, such as one remembered from `onResized`; kept inside the window. */
|
||||
initialSize?: { w: number; h: number } | null;
|
||||
/** The size a resize ended at. */
|
||||
@@ -212,7 +210,6 @@ function DialogInner({
|
||||
resizable,
|
||||
minWidth,
|
||||
minHeight,
|
||||
maxHeight,
|
||||
initialSize,
|
||||
onResized,
|
||||
position = "center",
|
||||
@@ -395,7 +392,6 @@ function DialogInner({
|
||||
style={{
|
||||
width: size ? size.w : width,
|
||||
height: size?.h,
|
||||
maxHeight: !size && maxHeight ? `min(${maxHeight}px, 100%)` : undefined,
|
||||
translate: offset.x || offset.y ? `${offset.x}px ${offset.y}px` : undefined,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Icon, type IconName } from "./icons";
|
||||
import { Popup } from "./Popup";
|
||||
@@ -33,8 +33,6 @@ export interface SelectProps<V extends string = string> {
|
||||
renderValue?: (option: SelectOption<V> | undefined) => ReactNode;
|
||||
/** Show a search box in the popup (useful for long option lists). */
|
||||
searchable?: boolean;
|
||||
/** The option under the pointer or keyboard while the list is open; `null` once it closes. */
|
||||
onPreview?: (value: V | null) => void;
|
||||
}
|
||||
|
||||
const TYPE_AHEAD_MS = 800;
|
||||
@@ -61,7 +59,6 @@ export function Select<V extends string = string>({
|
||||
className,
|
||||
renderValue,
|
||||
searchable = false,
|
||||
onPreview,
|
||||
...aria
|
||||
}: SelectProps<V>) {
|
||||
const tx = useTx();
|
||||
@@ -115,14 +112,6 @@ export function Select<V extends string = string>({
|
||||
const activeIndex =
|
||||
filtered[active] && !unavailable(filtered[active]!) ? active : filtered.findIndex((o) => !unavailable(o));
|
||||
|
||||
const previewed = open ? (filtered[activeIndex]?.value ?? null) : null;
|
||||
const lastPreview = useRef<V | null>(null);
|
||||
useEffect(() => {
|
||||
if (previewed === lastPreview.current) return;
|
||||
lastPreview.current = previewed;
|
||||
onPreview?.(previewed);
|
||||
}, [previewed, onPreview]);
|
||||
|
||||
const openPopup = () => {
|
||||
setQuery("");
|
||||
setActive(
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача