mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-25 02:44:03 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4ca3d7857 |
No files matched your search
@@ -23,7 +23,6 @@ on:
|
||||
- "Cargo.lock"
|
||||
- "src/features/run/**"
|
||||
- "src/features/debugger/**"
|
||||
- "src/features/build/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "src/workbench/**"
|
||||
@@ -106,7 +105,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
Generated
-4
@@ -4252,20 +4252,16 @@ name = "ide-core"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
|
||||
@@ -6,13 +6,6 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## Microsoft ConPTY
|
||||
|
||||
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
|
||||
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
|
||||
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
|
||||
and [package provenance](crates/ide-core/resources/conpty/README.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
@@ -73,7 +66,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
|
||||
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
|
||||
under the BSD 3-Clause License:
|
||||
|
||||
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
|
||||
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
|
||||
`resources/icons/expui/`.
|
||||
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
|
||||
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
|
||||
|
||||
@@ -26,10 +26,9 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let module = dunce::canonicalize(root.join(module))?;
|
||||
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
|
||||
let mut args = p.options.clone();
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -361,9 +361,7 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
|
||||
|
||||
@@ -517,59 +517,6 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
|
||||
Some(PathBuf::from(repo.replace("${user.home}", &home)))
|
||||
}
|
||||
|
||||
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
|
||||
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
|
||||
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
|
||||
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
|
||||
return Some(PathBuf::from(repo));
|
||||
}
|
||||
let mut args = options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return local_repository_of(Path::new(path)).or_else(default_local_repo);
|
||||
}
|
||||
}
|
||||
default_local_repo()
|
||||
}
|
||||
|
||||
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
|
||||
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
|
||||
/// in the local repository, which a repository filled from a private mirror often lacks even when
|
||||
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
|
||||
/// downloaded, else a pinned one.
|
||||
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
|
||||
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
|
||||
let (artifact, pinned) = match prefix {
|
||||
"help" => ("maven-help-plugin", "3.5.1"),
|
||||
"dependency" => ("maven-dependency-plugin", "3.8.1"),
|
||||
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
|
||||
};
|
||||
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
|
||||
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
|
||||
}
|
||||
|
||||
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
|
||||
/// from major version `min_major` up.
|
||||
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
|
||||
let dir = repo.join("org/apache/maven/plugins").join(artifact);
|
||||
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
|
||||
std::fs::read_dir(&dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter_map(|v| parse(&v).map(|n| (n, v)))
|
||||
.filter(|(n, v)| {
|
||||
n.first().is_some_and(|&major| major >= min_major)
|
||||
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
|
||||
})
|
||||
.max()
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
|
||||
Self::new_with_jdk(local_repo, profiles, None)
|
||||
@@ -2610,24 +2557,6 @@ mod tests {
|
||||
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ide_goals_resolve_from_the_repository_the_run_uses() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let settings = tmp.path().join("settings.xml");
|
||||
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
|
||||
let s = settings.to_string_lossy().into_owned();
|
||||
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
|
||||
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
|
||||
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
|
||||
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
|
||||
// No repository known: a pinned version, still by coordinates.
|
||||
assert_eq!(
|
||||
plugin_goal("dependency:build-classpath", None),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -86,37 +86,22 @@ const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
|
||||
/// plugin version is, which may be cached instead.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
/// `repo` is the local repository the build resolves from.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
goals.push("-Dverbose".into());
|
||||
goals
|
||||
vec![
|
||||
"help:effective-pom".into(),
|
||||
format!("-Doutput={}", effective.to_string_lossy()),
|
||||
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
|
||||
@@ -382,8 +367,25 @@ pub fn sync_maven(
|
||||
verbose: true,
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
let repo = maven::local_repository_for(&options.maven_options);
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read
|
||||
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
|
||||
// then the user's default repository (which `plugin()` resolves itself).
|
||||
let local_repo: Option<PathBuf> =
|
||||
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|
||||
|| {
|
||||
let mut args = options.maven_options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return maven::local_repository_of(Path::new(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
},
|
||||
);
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
@@ -405,6 +407,7 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
let repo = local_repo.clone().or_else(maven::default_local_repo);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
@@ -422,7 +425,7 @@ pub fn sync_maven(
|
||||
}
|
||||
})?;
|
||||
let effective_projects = std::fs::read_to_string(&effective)
|
||||
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
|
||||
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
|
||||
.unwrap_or_default();
|
||||
let trees = maven::parse_dependency_tree(&out.text);
|
||||
for (key, plugins, deps) in effective_projects {
|
||||
@@ -950,32 +953,11 @@ mod tests {
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, None);
|
||||
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
|
||||
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
|
||||
let jar =
|
||||
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
assert_eq!(offline[2], "dependency:tree");
|
||||
assert!(offline.contains(&"-Dverbose".to_owned()));
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
@@ -1047,7 +1029,7 @@ mod tests {
|
||||
let cache = tmp.path().join("cache");
|
||||
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
|
||||
let maven = loaded.maven.unwrap();
|
||||
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
|
||||
@@ -1072,6 +1054,6 @@ mod tests {
|
||||
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
|
||||
// `-T1` pins the daemon serial so the dependency trees stay parseable.
|
||||
assert!(args.contains("-T1"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
}
|
||||
}
|
||||
@@ -137,16 +137,19 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
evaluate.clone(),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.id".into(),
|
||||
format!("-Doutput={}", output.display()),
|
||||
]);
|
||||
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
|
||||
args.extend([
|
||||
"-DskipTests".into(),
|
||||
"package".into(),
|
||||
"help:evaluate".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
return Ok(WebBuild {
|
||||
command: top.command.clone(),
|
||||
args,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -16,12 +16,8 @@
|
||||
//! thread: AppKit and WebKit also access the general pasteboard there, and its
|
||||
//! mutable type cache cannot be protected by a mutex in this crate.
|
||||
//!
|
||||
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
|
||||
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
|
||||
//! one URI per line), read and written through the GTK clipboard on X11 and
|
||||
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
|
||||
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
|
||||
//! fails there.
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
//!
|
||||
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
|
||||
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
|
||||
@@ -83,7 +79,6 @@ const HEADER: usize = 20;
|
||||
|
||||
/// The absolute paths on the clipboard, empty when it holds no file list.
|
||||
/// Read failures remain errors so callers can retain an internal copy.
|
||||
/// Empty on Linux, where [`request_files`] reads it.
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
imp::files()
|
||||
}
|
||||
@@ -106,7 +101,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
@@ -117,82 +112,6 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
|
||||
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
|
||||
/// hosts or schemes are skipped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
|
||||
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
|
||||
}
|
||||
|
||||
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
|
||||
/// path; its percent-escapes are raw bytes, as GLib writes them.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
|
||||
let path = path.split(['?', '#']).next()?;
|
||||
if !path.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
|
||||
let bytes = path.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let escaped =
|
||||
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
|
||||
match escaped {
|
||||
Some(b) => {
|
||||
out.push(b);
|
||||
i += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
|
||||
/// percent-escaped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn file_uri(path: &std::path::Path) -> String {
|
||||
use std::fmt::Write;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let mut uri = String::from("file://");
|
||||
for &b in path.as_os_str().as_bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
|
||||
uri.push(b as char);
|
||||
} else {
|
||||
let _ = write!(uri, "%{b:02X}");
|
||||
}
|
||||
}
|
||||
uri
|
||||
}
|
||||
|
||||
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
|
||||
/// then GNOME's list, and calls `done` with the paths (empty without a list).
|
||||
/// Call on the main thread; `done` runs there later.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
|
||||
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
|
||||
fn paths_in(data: >k::SelectionData) -> Vec<PathBuf> {
|
||||
// A failed request has a negative length and no data.
|
||||
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
|
||||
}
|
||||
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
|
||||
let paths = paths_in(data);
|
||||
if !paths.is_empty() {
|
||||
return done(paths);
|
||||
}
|
||||
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
|
||||
});
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -809,25 +728,8 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const URI_LIST: &str = "text/uri-list";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
|
||||
|
||||
pub fn has_files() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
|
||||
targets.into_iter().any(|target| {
|
||||
let name = target.name();
|
||||
name == URI_LIST || name == GNOME_COPIED
|
||||
})
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
@@ -845,33 +747,6 @@ mod imp {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
|
||||
/// list (Nautilus, Thunar) and their names as text, rendered on request.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
use gtk::{TargetEntry, TargetFlags};
|
||||
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
|
||||
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
|
||||
let gnome = format!("copy\n{}", uris.join("\n"));
|
||||
let names = super::names_text(paths, "\n");
|
||||
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
|
||||
let targets = [
|
||||
entry(URI_LIST, 0),
|
||||
entry(GNOME_COPIED, 1),
|
||||
entry("UTF8_STRING", 2),
|
||||
entry("text/plain;charset=utf-8", 2),
|
||||
entry("text/plain", 2),
|
||||
];
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
|
||||
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
|
||||
1 => data.set(&data.target(), 8, gnome.as_bytes()),
|
||||
_ => {
|
||||
let _ = data.set_text(&names);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn set_files(_paths: &[PathBuf]) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -894,28 +769,6 @@ mod tests {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_manager_uri_lists_become_paths() {
|
||||
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
|
||||
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
|
||||
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
|
||||
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
|
||||
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
|
||||
// Other hosts and schemes are not local files.
|
||||
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn written_uris_read_back_as_the_same_paths() {
|
||||
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
|
||||
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
|
||||
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
|
||||
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
|
||||
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_written_list_reads_back_unchanged() {
|
||||
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
|
||||
|
||||
@@ -15,16 +15,12 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
portable-pty.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
sha2 = "0.10"
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -1,21 +0,0 @@
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Bundled Windows console host
|
||||
|
||||
Unmodified files from Microsoft's MIT-licensed
|
||||
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
|
||||
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
|
||||
puts full-screen applications' redraws in normal scrollback. A current console host
|
||||
preserves those transitions, including while resizing and updating a running TUI.
|
||||
|
||||
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
|
||||
Run and debugger builds work offline and do not depend on another installed IDE.
|
||||
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
|
||||
extracts them atomically to a versioned user cache and preloads the DLL's absolute
|
||||
path before portable-pty initializes.
|
||||
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
|
||||
failure is logged and falls back to the system backend. Windows builds before
|
||||
19041 also retain the system backend.
|
||||
|
||||
Source archive:
|
||||
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
|
||||
|
||||
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
|
||||
|
||||
For each architecture, `conpty.dll` comes from
|
||||
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
|
||||
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
|
||||
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
|
||||
|
||||
| File | SHA-256 |
|
||||
| --------------------- | ------------------------------------------------------------------ |
|
||||
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
|
||||
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
|
||||
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
|
||||
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
|
||||
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
|
||||
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
|
||||
|
||||
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
|
||||
console application and requires alternate-screen entry and exit to reach the
|
||||
reader; a system ConPTY that consumes them fails this check.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -25,7 +25,6 @@ pub mod project_dir;
|
||||
pub mod project_env;
|
||||
pub mod project_roots;
|
||||
pub mod proxy_settings;
|
||||
pub mod pty;
|
||||
pub mod real_path;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
|
||||
|
||||
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
|
||||
#[cfg(windows)]
|
||||
windows::initialize();
|
||||
portable_pty::native_pty_system()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use windows_sys::Win32::Foundation::FreeLibrary;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
|
||||
const VERSION: &str = "1.25.260930003";
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x64",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"arm64",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "x86")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x86",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
);
|
||||
|
||||
pub(super) fn initialize() -> bool {
|
||||
static BUNDLED: OnceLock<bool> = OnceLock::new();
|
||||
*BUNDLED.get_or_init(|| {
|
||||
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
|
||||
return false;
|
||||
}
|
||||
match load() {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
|
||||
false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn load() -> io::Result<()> {
|
||||
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
|
||||
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
|
||||
fs::create_dir_all(&directory)?;
|
||||
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
|
||||
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
|
||||
let library = directory.join("conpty.dll");
|
||||
install(&library, RUNTIME.1)?;
|
||||
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
|
||||
// Windows reuses this module, without adding the project directory to DLL search.
|
||||
// SAFETY: the path is terminated and the module is retained for the process lifetime.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
wide.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
|
||||
// SAFETY: `module` is loaded and each name is a terminated export name.
|
||||
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
|
||||
// SAFETY: no PTY uses this rejected module yet; release our load reference.
|
||||
unsafe { FreeLibrary(module) };
|
||||
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
|
||||
}
|
||||
}
|
||||
// Keep this reference for the process lifetime, including between PTY sessions.
|
||||
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
if fs::read(path).is_ok_and(|existing| existing == data) {
|
||||
return Ok(());
|
||||
}
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let pending =
|
||||
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let result = (|| {
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
match fs::rename(&pending, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
})();
|
||||
let _ = fs::remove_file(pending);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installs_atomically_and_repairs_incomplete_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("conpty.dll");
|
||||
fs::write(&path, b"partial").unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
let path = &path;
|
||||
scope.spawn(move || install(path, b"complete runtime").unwrap());
|
||||
}
|
||||
});
|
||||
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_the_bundled_backend() {
|
||||
assert!(initialize());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_output_child() {
|
||||
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
|
||||
return;
|
||||
}
|
||||
use windows_sys::Win32::System::Console::{
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
|
||||
};
|
||||
// SAFETY: the inherited console output handle and a local writable mode word.
|
||||
unsafe {
|
||||
let output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
let mut mode = 0;
|
||||
assert_ne!(GetConsoleMode(output, &mut mode), 0);
|
||||
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
|
||||
}
|
||||
std::io::stdout()
|
||||
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
|
||||
.unwrap();
|
||||
std::io::stdout().flush().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_preserves_alternate_screen_transitions() {
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
|
||||
let mut reader = pair.master.try_clone_reader().unwrap();
|
||||
let mut writer = pair.master.take_writer().unwrap();
|
||||
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
|
||||
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
|
||||
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
|
||||
let mut child = pair.slave.spawn_command(command).unwrap();
|
||||
drop(pair.slave);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reading = std::thread::spawn(move || {
|
||||
let mut bytes = [0; 4096];
|
||||
while let Ok(count) = reader.read(&mut bytes) {
|
||||
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut output = Vec::new();
|
||||
let mut cursor_replied = false;
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
|
||||
output.extend_from_slice(&bytes);
|
||||
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
|
||||
writer.write_all(b"\x1b[1;1R").unwrap();
|
||||
cursor_replied = true;
|
||||
}
|
||||
if output.windows(7).any(|s| s == b"VT_DONE") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
drop(writer);
|
||||
drop(pair.master);
|
||||
reading.join().unwrap();
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
|
||||
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
|
||||
#[cfg(test)]
|
||||
mod checksums {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FILES: [(&str, &[u8], &str); 6] = [
|
||||
(
|
||||
"arm64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
|
||||
),
|
||||
(
|
||||
"arm64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
|
||||
),
|
||||
(
|
||||
"x64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
|
||||
),
|
||||
(
|
||||
"x64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
|
||||
),
|
||||
(
|
||||
"x86/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
|
||||
),
|
||||
(
|
||||
"x86/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn embedded_runtime_matches_the_pinned_package() {
|
||||
for (name, bytes, expected) in FILES {
|
||||
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1218,7 +1218,6 @@ pub struct LanguagesSettings {
|
||||
pub markdown: MarkdownSettings,
|
||||
pub arduino: ArduinoSettings,
|
||||
pub zig: ZigSettings,
|
||||
pub flutter: FlutterSettings,
|
||||
}
|
||||
|
||||
impl Default for LanguagesSettings {
|
||||
@@ -1250,7 +1249,6 @@ impl Default for LanguagesSettings {
|
||||
markdown: MarkdownSettings::default(),
|
||||
arduino: ArduinoSettings::default(),
|
||||
zig: ZigSettings::default(),
|
||||
flutter: FlutterSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1517,15 +1515,6 @@ pub struct ZigSettings {
|
||||
pub zig: String,
|
||||
}
|
||||
|
||||
/// The Flutter plugin's "Flutter SDK path".
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FlutterSettings {
|
||||
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
|
||||
/// `PATH`. Empty = `PATH`.
|
||||
pub sdk: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GoSettings {
|
||||
|
||||
+14
-15
@@ -897,21 +897,6 @@ impl DebugManager {
|
||||
if config.adapter == "rdbg" {
|
||||
rdbg_command_line(&mut spec, &config, &cwd)?;
|
||||
}
|
||||
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
|
||||
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
|
||||
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
|
||||
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
|
||||
if config.adapter == "dart" {
|
||||
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
|
||||
if force_flutter || is_flutter_project(&cwd, program) {
|
||||
if spec.command == "dart" {
|
||||
spec.command = "flutter".into();
|
||||
}
|
||||
if let Some(device) = flutter_device {
|
||||
add_flutter_device(&mut arguments, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
@@ -927,6 +912,20 @@ impl DebugManager {
|
||||
spec.command = python;
|
||||
}
|
||||
}
|
||||
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
|
||||
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
|
||||
// is Flutter-only). Plain Dart projects keep the configured `dart`.
|
||||
if config.adapter == "dart" {
|
||||
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
|
||||
if force_flutter || is_flutter_project(&cwd, program) {
|
||||
if spec.command == "dart" {
|
||||
spec.command = "flutter".into();
|
||||
}
|
||||
if let Some(device) = flutter_device {
|
||||
add_flutter_device(&mut arguments, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
let id = DebugSessionId::next();
|
||||
let debug_server = take_debug_server(&mut arguments)?;
|
||||
if let Some(server) = &debug_server {
|
||||
|
||||
@@ -1061,8 +1061,7 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
|
||||
/// starts a launcher that gives the program its terminal, and the program reads input only from
|
||||
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
|
||||
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
|
||||
use ide_core::pty::native_pty_system;
|
||||
use portable_pty::{CommandBuilder, PtySize};
|
||||
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
|
||||
let argv: Vec<String> = args
|
||||
.get("args")
|
||||
.and_then(Value::as_array)
|
||||
|
||||
@@ -658,7 +658,8 @@ impl DbManager {
|
||||
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
|
||||
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
|
||||
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
|
||||
return self.ssh.set_secret(&c, secret, save);
|
||||
self.ssh.set_secret(&c, secret, save);
|
||||
return Ok(());
|
||||
}
|
||||
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
|
||||
}
|
||||
@@ -759,9 +760,7 @@ impl DbManager {
|
||||
} else {
|
||||
if let Some(s) = ssh_secret {
|
||||
let save = self.ssh.config(config)?.save_secret;
|
||||
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
|
||||
tracing::warn!("could not save the SSH credential: {}", e.message);
|
||||
}
|
||||
self.ssh.set_secret(config, Some(s), save);
|
||||
}
|
||||
self.ssh.session(config).await?
|
||||
})
|
||||
|
||||
@@ -1,34 +1,23 @@
|
||||
//! One `dart devtools` server per project window. In `--machine` mode it reports its port as a
|
||||
//! `server.started` line on stdout.
|
||||
//! One `dart devtools` server per project window, started when first asked for. In `--machine`
|
||||
//! mode it reports its port as a `server.started` line on stdout. A server that fails or exits
|
||||
//! is not restarted on its own: the next request starts a new one.
|
||||
|
||||
use crate::flutter_executable;
|
||||
use crate::server::{Line, Spec, ToolServer};
|
||||
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
|
||||
use ide_core::process::{kill_tree, terminate_tree};
|
||||
use ide_core::tool_path::{find_command, search_path_in};
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use serde_json::Value;
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use std::process::Child;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// The address embedded pages are allowed to come from, so never `localhost`.
|
||||
pub(crate) const HOST: &str = "127.0.0.1";
|
||||
const HOST: &str = "127.0.0.1";
|
||||
const ARGS: [&str; 7] = ["devtools", "--machine", "--allow-embedding", "--host", HOST, "--port", "0"];
|
||||
|
||||
pub(crate) static DEVTOOLS: Spec = Spec {
|
||||
name: "Flutter DevTools",
|
||||
args: &ARGS,
|
||||
timeout: Duration::from_secs(60),
|
||||
executable: dart_executable,
|
||||
not_found: "Dart SDK not found: install Flutter or add it to PATH",
|
||||
line,
|
||||
failed: |message| if message.is_empty() { "dart devtools exited".into() } else { message },
|
||||
};
|
||||
|
||||
impl ToolServer {
|
||||
/// `dart` is the configured one, else the one of the `flutter` on the search path.
|
||||
pub fn devtools(root: PathBuf, dart: crate::Configured) -> Self {
|
||||
Self::new(root, &DEVTOOLS, dart)
|
||||
}
|
||||
}
|
||||
|
||||
fn started_port(line: &str) -> Option<u16> {
|
||||
let message: Value = serde_json::from_str(line.trim()).ok()?;
|
||||
if message.get("event")?.as_str()? != "server.started" {
|
||||
@@ -37,23 +26,186 @@ fn started_port(line: &str) -> Option<u16> {
|
||||
u16::try_from(message.get("params")?.get("port")?.as_u64()?).ok()
|
||||
}
|
||||
|
||||
fn line(line: &str) -> Line {
|
||||
match started_port(line) {
|
||||
Some(port) => Line::Url(format!("http://{HOST}:{port}")),
|
||||
None => Line::Output(line.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `dart` of the SDK `flutter` belongs to, so that DevTools matches the debugged app.
|
||||
fn dart_executable(root: &Path) -> Option<PathBuf> {
|
||||
flutter_executable(root)
|
||||
let path = search_path_in(root);
|
||||
find_command("flutter", &path, root)
|
||||
.and_then(|flutter| {
|
||||
// On the search path `flutter` is often a link into the SDK.
|
||||
let flutter = if cfg!(unix) { std::fs::canonicalize(&flutter).unwrap_or(flutter) } else { flutter };
|
||||
let dart = flutter.with_file_name(if cfg!(windows) { "dart.bat" } else { "dart" });
|
||||
dart.is_file().then_some(dart)
|
||||
})
|
||||
.or_else(|| find_command("dart", &search_path_in(root), root))
|
||||
.or_else(|| find_command("dart", &path, root))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum Status {
|
||||
#[default]
|
||||
Stopped,
|
||||
Starting,
|
||||
Ready(String),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// Bumped by every start and stop: a reader of an older process no longer has a say.
|
||||
generation: u64,
|
||||
child: Option<Child>,
|
||||
status: Status,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn shut_down(&mut self) {
|
||||
self.generation += 1;
|
||||
if let Some(mut child) = self.child.take() {
|
||||
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
root: PathBuf,
|
||||
/// Replaces the lookup on the search path (tests).
|
||||
executable: Option<PathBuf>,
|
||||
timeout: Duration,
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// Applies `status` unless this process was replaced or stopped; false if it was.
|
||||
fn set(&self, generation: u64, status: Status) -> bool {
|
||||
let mut state = self.state.lock();
|
||||
if state.generation != generation {
|
||||
return false;
|
||||
}
|
||||
state.status = status;
|
||||
self.changed.notify_all();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DevToolsServer(Arc<Shared>);
|
||||
|
||||
impl DevToolsServer {
|
||||
pub fn new(root: PathBuf) -> Self {
|
||||
Self::with_executable(root, None, START_TIMEOUT)
|
||||
}
|
||||
|
||||
fn with_executable(root: PathBuf, executable: Option<PathBuf>, timeout: Duration) -> Self {
|
||||
Self(Arc::new(Shared { root, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
|
||||
}
|
||||
|
||||
/// The server's address, starting it if none runs. Blocks until it is known.
|
||||
pub fn url(&self) -> Result<String, String> {
|
||||
let shared = &self.0;
|
||||
let deadline = Instant::now() + shared.timeout;
|
||||
let mut state = shared.state.lock();
|
||||
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
|
||||
state.generation += 1;
|
||||
state.status = Status::Starting;
|
||||
let (shared, generation) = (shared.clone(), state.generation);
|
||||
std::thread::spawn(move || run(&shared, generation));
|
||||
}
|
||||
loop {
|
||||
match &state.status {
|
||||
Status::Ready(url) => return Ok(url.clone()),
|
||||
Status::Failed(message) => return Err(message.clone()),
|
||||
Status::Stopped => return Err("Flutter DevTools was stopped".into()),
|
||||
Status::Starting => {}
|
||||
}
|
||||
if shared.changed.wait_until(&mut state, deadline).timed_out() {
|
||||
state.shut_down();
|
||||
let message = "Flutter DevTools did not start in time".to_owned();
|
||||
state.status = Status::Failed(message.clone());
|
||||
shared.changed.notify_all();
|
||||
return Err(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the server (project closed, or no longer trusted).
|
||||
pub fn stop(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
state.shut_down();
|
||||
state.status = Status::Stopped;
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Ends the server before returning, for a process about to exit.
|
||||
pub fn kill(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
state.generation += 1;
|
||||
state.status = Status::Stopped;
|
||||
if let Some(mut child) = state.child.take() {
|
||||
kill_tree(&mut child);
|
||||
}
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// One server's whole life, on its own thread.
|
||||
fn run(shared: &Arc<Shared>, generation: u64) {
|
||||
let fail = |message: String| {
|
||||
shared.set(generation, Status::Failed(message));
|
||||
};
|
||||
let Some(executable) = shared.executable.clone().or_else(|| dart_executable(&shared.root)) else {
|
||||
return fail("Dart SDK not found: install Flutter or add it to PATH".into());
|
||||
};
|
||||
let mut child = match spawn_watched(&executable, &ARGS, &shared.root) {
|
||||
Ok(child) => child,
|
||||
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
|
||||
};
|
||||
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
|
||||
terminate_tree(&mut child, Duration::ZERO);
|
||||
return fail("no output pipe".into());
|
||||
};
|
||||
{
|
||||
let mut state = shared.state.lock();
|
||||
if state.generation != generation {
|
||||
drop(state);
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return;
|
||||
}
|
||||
state.child = Some(child);
|
||||
}
|
||||
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
|
||||
let errors = {
|
||||
let tail = tail.clone();
|
||||
std::thread::spawn(move || {
|
||||
read_lines(stderr, |line| {
|
||||
keep_output(&tail, line);
|
||||
true
|
||||
});
|
||||
})
|
||||
};
|
||||
read_lines(stdout, |line| match started_port(line) {
|
||||
Some(port) => shared.set(generation, Status::Ready(format!("http://{HOST}:{port}"))),
|
||||
None => {
|
||||
keep_output(&tail, line);
|
||||
true
|
||||
}
|
||||
});
|
||||
let _ = errors.join();
|
||||
|
||||
let mut state = shared.state.lock();
|
||||
if state.generation != generation {
|
||||
return;
|
||||
}
|
||||
let child = state.child.take();
|
||||
state.status = if matches!(state.status, Status::Ready(_)) {
|
||||
Status::Stopped
|
||||
} else {
|
||||
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
|
||||
Status::Failed(if message.is_empty() { "dart devtools exited".into() } else { message })
|
||||
};
|
||||
shared.changed.notify_all();
|
||||
drop(state);
|
||||
if let Some(mut child) = child {
|
||||
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -73,15 +225,14 @@ mod tests {
|
||||
mod process {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Instant;
|
||||
|
||||
const STARTED: &str = r#"echo '{"event":"server.started","params":{"port":4242}}'"#;
|
||||
|
||||
fn server(dir: &Path, script: &str, timeout: Duration) -> ToolServer {
|
||||
fn server(dir: &Path, script: &str, timeout: Duration) -> DevToolsServer {
|
||||
let path = dir.join("dart");
|
||||
std::fs::write(&path, format!("#!/bin/sh\necho run >> runs\n{script}")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
ToolServer::with_executable(dir.to_owned(), &DEVTOOLS, Box::new(move || Some(path.clone())), timeout)
|
||||
DevToolsServer::with_executable(dir.to_owned(), Some(path), timeout)
|
||||
}
|
||||
|
||||
fn runs(dir: &Path) -> usize {
|
||||
@@ -101,8 +252,8 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = format!("echo \"$*\" > args\necho $$ > pid\n{STARTED}\nexec sleep 30");
|
||||
let devtools = server(dir.path(), &script, Duration::from_secs(10));
|
||||
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
|
||||
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
|
||||
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
|
||||
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
|
||||
assert_eq!(runs(dir.path()), 1);
|
||||
let args = std::fs::read_to_string(dir.path().join("args")).unwrap();
|
||||
assert_eq!(args.trim(), ARGS.join(" "));
|
||||
@@ -120,10 +271,10 @@ mod tests {
|
||||
fn a_failure_is_reported_and_only_a_new_request_retries() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let devtools = server(dir.path(), "echo boom >&2\nexit 3", Duration::from_secs(10));
|
||||
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
|
||||
assert_eq!(devtools.url().unwrap_err(), "boom");
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert_eq!(runs(dir.path()), 1);
|
||||
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
|
||||
assert_eq!(devtools.url().unwrap_err(), "boom");
|
||||
assert_eq!(runs(dir.path()), 2);
|
||||
}
|
||||
|
||||
@@ -131,10 +282,10 @@ mod tests {
|
||||
fn a_server_that_exits_is_not_restarted_until_asked() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let devtools = server(dir.path(), STARTED, Duration::from_secs(10));
|
||||
devtools.url(&[]).unwrap();
|
||||
wait_for("the exit to be noticed", || devtools.is_stopped());
|
||||
devtools.url().unwrap();
|
||||
wait_for("the exit to be noticed", || matches!(devtools.0.state.lock().status, Status::Stopped));
|
||||
assert_eq!(runs(dir.path()), 1);
|
||||
devtools.url(&[]).unwrap();
|
||||
devtools.url().unwrap();
|
||||
assert_eq!(runs(dir.path()), 2);
|
||||
}
|
||||
|
||||
@@ -142,7 +293,7 @@ mod tests {
|
||||
fn a_server_that_never_reports_times_out() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let devtools = server(dir.path(), "exec sleep 30", Duration::from_millis(200));
|
||||
assert_eq!(devtools.url(&[]).unwrap_err(), "Flutter DevTools did not start in time");
|
||||
assert_eq!(devtools.url().unwrap_err(), "Flutter DevTools did not start in time");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,8 @@
|
||||
//! daemon that fails stays failed until the user restarts it.
|
||||
|
||||
mod devtools;
|
||||
mod server;
|
||||
mod widget_preview;
|
||||
|
||||
pub use server::ToolServer;
|
||||
pub use devtools::DevToolsServer;
|
||||
|
||||
use ide_android::AndroidDevice;
|
||||
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
|
||||
@@ -191,7 +189,8 @@ impl State {
|
||||
struct Shared {
|
||||
root: PathBuf,
|
||||
sink: SharedSink,
|
||||
executable: Configured,
|
||||
/// Replaces the lookup on the search path (tests).
|
||||
executable: Option<PathBuf>,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
@@ -201,21 +200,16 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// The configured `flutter` / `dart` (the Flutter SDK setting), asked at each start; `None`
|
||||
/// looks it up on the search path.
|
||||
pub type Configured = Box<dyn Fn() -> Option<PathBuf> + Send + Sync>;
|
||||
|
||||
/// One project window's `flutter daemon`, started on first use.
|
||||
pub struct FlutterDaemon(Arc<Shared>);
|
||||
|
||||
impl FlutterDaemon {
|
||||
pub fn new(root: PathBuf, sink: SharedSink, executable: Configured) -> Self {
|
||||
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
|
||||
pub fn new(root: PathBuf, sink: SharedSink) -> Self {
|
||||
Self::with_executable(root, sink, None)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
|
||||
Self::new(root, sink, Box::new(move || executable.clone()))
|
||||
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
|
||||
}
|
||||
|
||||
/// The current list; starts the daemon unless it already ran. Never blocks on the process.
|
||||
@@ -277,15 +271,6 @@ impl FlutterDaemon {
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a running daemon again, with the SDK the settings now choose.
|
||||
pub fn sdk_changed(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
if state.status != FlutterDaemonStatus::Stopped {
|
||||
state.shut_down();
|
||||
start(&self.0, &mut state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the daemon (project closed, or no longer trusted).
|
||||
pub fn stop(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
@@ -400,14 +385,10 @@ fn read_lines(pipe: impl Read, mut on_line: impl FnMut(&str) -> bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `flutter` that commands run in `root` use.
|
||||
fn flutter_executable(root: &Path) -> Option<PathBuf> {
|
||||
find_command("flutter", &search_path_in(root), root)
|
||||
}
|
||||
|
||||
/// One daemon's whole life, on its own thread.
|
||||
fn run(shared: &Arc<Shared>, generation: u64) {
|
||||
let executable = (shared.executable)().or_else(|| flutter_executable(&shared.root));
|
||||
let executable =
|
||||
shared.executable.clone().or_else(|| find_command("flutter", &search_path_in(&shared.root), &shared.root));
|
||||
let Some(executable) = executable else {
|
||||
return finish(shared, generation, FlutterDaemonStatus::NotInstalled);
|
||||
};
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
//! A Flutter tool serving pages for the IDE to embed, one per project window, started when first
|
||||
//! asked for. It reports its address on stdout. A server that fails or exits is not restarted on
|
||||
//! its own: the next request starts a new one.
|
||||
|
||||
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
|
||||
use ide_core::process::{kill_tree, terminate_tree};
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Child;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// What one line of the tool's output says.
|
||||
pub(crate) enum Line {
|
||||
/// The page's address: the server is ready.
|
||||
Url(String),
|
||||
/// Text worth showing if the server fails.
|
||||
Output(String),
|
||||
/// Nothing worth keeping.
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// How to run one kind of server.
|
||||
pub(crate) struct Spec {
|
||||
/// For messages, e.g. "Flutter DevTools".
|
||||
pub name: &'static str,
|
||||
pub args: &'static [&'static str],
|
||||
pub timeout: Duration,
|
||||
pub executable: fn(&Path) -> Option<PathBuf>,
|
||||
pub not_found: &'static str,
|
||||
pub line: fn(&str) -> Line,
|
||||
/// The failure to report, from the output kept until the tool exited.
|
||||
pub failed: fn(String) -> String,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum Status {
|
||||
#[default]
|
||||
Stopped,
|
||||
Starting,
|
||||
Ready(String),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// Bumped by every start and stop: a reader of an older process no longer has a say.
|
||||
generation: u64,
|
||||
child: Option<Child>,
|
||||
status: Status,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn shut_down(&mut self) {
|
||||
self.generation += 1;
|
||||
if let Some(mut child) = self.child.take() {
|
||||
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
root: PathBuf,
|
||||
spec: &'static Spec,
|
||||
/// The configured executable; the spec's lookup on the search path without one.
|
||||
executable: crate::Configured,
|
||||
timeout: Duration,
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// Applies `status` unless this process was replaced or stopped; false if it was.
|
||||
fn set(&self, generation: u64, status: Status) -> bool {
|
||||
let mut state = self.state.lock();
|
||||
if state.generation != generation {
|
||||
return false;
|
||||
}
|
||||
state.status = status;
|
||||
self.changed.notify_all();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ToolServer(Arc<Shared>);
|
||||
|
||||
impl ToolServer {
|
||||
pub(crate) fn new(root: PathBuf, spec: &'static Spec, executable: crate::Configured) -> Self {
|
||||
Self::with_executable(root, spec, executable, spec.timeout)
|
||||
}
|
||||
|
||||
pub(crate) fn with_executable(
|
||||
root: PathBuf,
|
||||
spec: &'static Spec,
|
||||
executable: crate::Configured,
|
||||
timeout: Duration,
|
||||
) -> Self {
|
||||
Self(Arc::new(Shared { root, spec, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
|
||||
}
|
||||
|
||||
/// The server's address, starting it with `extra` arguments if none runs. Blocks until it is known.
|
||||
pub fn url(&self, extra: &[String]) -> Result<String, String> {
|
||||
let shared = &self.0;
|
||||
let deadline = Instant::now() + shared.timeout;
|
||||
let mut state = shared.state.lock();
|
||||
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
|
||||
state.generation += 1;
|
||||
state.status = Status::Starting;
|
||||
let (shared, generation, extra) = (shared.clone(), state.generation, extra.to_vec());
|
||||
std::thread::spawn(move || run(&shared, generation, &extra));
|
||||
}
|
||||
loop {
|
||||
match &state.status {
|
||||
Status::Ready(url) => return Ok(url.clone()),
|
||||
Status::Failed(message) => return Err(message.clone()),
|
||||
Status::Stopped => return Err(format!("{} was stopped", shared.spec.name)),
|
||||
Status::Starting => {}
|
||||
}
|
||||
if shared.changed.wait_until(&mut state, deadline).timed_out() {
|
||||
state.shut_down();
|
||||
let message = format!("{} did not start in time", shared.spec.name);
|
||||
state.status = Status::Failed(message.clone());
|
||||
shared.changed.notify_all();
|
||||
return Err(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the server (project closed, or no longer trusted).
|
||||
pub fn stop(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
state.shut_down();
|
||||
state.status = Status::Stopped;
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Ends the server before returning, for a process about to exit.
|
||||
pub fn kill(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
state.generation += 1;
|
||||
state.status = Status::Stopped;
|
||||
if let Some(mut child) = state.child.take() {
|
||||
kill_tree(&mut child);
|
||||
}
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn is_stopped(&self) -> bool {
|
||||
matches!(self.0.state.lock().status, Status::Stopped)
|
||||
}
|
||||
}
|
||||
|
||||
/// One server's whole life, on its own thread.
|
||||
fn run(shared: &Arc<Shared>, generation: u64, extra: &[String]) {
|
||||
let spec = shared.spec;
|
||||
let fail = |message: String| {
|
||||
shared.set(generation, Status::Failed(message));
|
||||
};
|
||||
let Some(executable) = (shared.executable)().or_else(|| (spec.executable)(&shared.root)) else {
|
||||
return fail(spec.not_found.into());
|
||||
};
|
||||
let args: Vec<&str> = spec.args.iter().copied().chain(extra.iter().map(String::as_str)).collect();
|
||||
let mut child = match spawn_watched(&executable, &args, &shared.root) {
|
||||
Ok(child) => child,
|
||||
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
|
||||
};
|
||||
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
|
||||
terminate_tree(&mut child, Duration::ZERO);
|
||||
return fail("no output pipe".into());
|
||||
};
|
||||
{
|
||||
let mut state = shared.state.lock();
|
||||
if state.generation != generation {
|
||||
drop(state);
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return;
|
||||
}
|
||||
state.child = Some(child);
|
||||
}
|
||||
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
|
||||
let errors = {
|
||||
let tail = tail.clone();
|
||||
std::thread::spawn(move || {
|
||||
read_lines(stderr, |line| {
|
||||
keep_output(&tail, line);
|
||||
true
|
||||
});
|
||||
})
|
||||
};
|
||||
read_lines(stdout, |line| match (spec.line)(line) {
|
||||
Line::Url(url) => shared.set(generation, Status::Ready(url)),
|
||||
Line::Output(text) => {
|
||||
keep_output(&tail, &text);
|
||||
true
|
||||
}
|
||||
Line::Skip => true,
|
||||
});
|
||||
let _ = errors.join();
|
||||
|
||||
let mut state = shared.state.lock();
|
||||
if state.generation != generation {
|
||||
return;
|
||||
}
|
||||
let child = state.child.take();
|
||||
state.status = if matches!(state.status, Status::Ready(_)) {
|
||||
Status::Stopped
|
||||
} else {
|
||||
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
|
||||
Status::Failed((spec.failed)(message))
|
||||
};
|
||||
shared.changed.notify_all();
|
||||
drop(state);
|
||||
if let Some(mut child) = child {
|
||||
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
//! One `flutter widget-preview` server per project window: the `@Preview` widgets of the project,
|
||||
//! served as a web page that reloads as they change. Like the Flutter plugins of Android Studio
|
||||
//! and VS Code it runs on the `web-server` device, in `--machine` mode, where it reports events
|
||||
//! as bracketed JSON lines and the page's address with `widget_preview.started`. Without
|
||||
//! `--dtd-url` it starts its own analysis server and Dart Tooling Daemon to find the previews.
|
||||
|
||||
use crate::devtools::HOST;
|
||||
use crate::flutter_executable;
|
||||
use crate::server::{Line, Spec, ToolServer};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The release whose `widget-preview start` has the options used here.
|
||||
const MIN_FLUTTER: &str = "3.38";
|
||||
|
||||
static WIDGET_PREVIEW: Spec = Spec {
|
||||
name: "Flutter Widget Preview",
|
||||
args: &["widget-preview", "start", "--machine", "--web-server"],
|
||||
// The first start runs `pub get` and compiles the preview environment.
|
||||
timeout: Duration::from_secs(300),
|
||||
executable: flutter_executable,
|
||||
not_found: "Flutter SDK not found: install Flutter or add it to PATH",
|
||||
line,
|
||||
failed,
|
||||
};
|
||||
|
||||
impl ToolServer {
|
||||
/// `flutter` is the configured one, else the one on the search path.
|
||||
pub fn widget_preview(root: PathBuf, flutter: crate::Configured) -> Self {
|
||||
Self::new(root, &WIDGET_PREVIEW, flutter)
|
||||
}
|
||||
}
|
||||
|
||||
fn line(line: &str) -> Line {
|
||||
let Ok(Value::Array(messages)) = serde_json::from_str(line.trim()) else {
|
||||
return Line::Output(line.to_owned());
|
||||
};
|
||||
let Some(message) = messages.first() else { return Line::Skip };
|
||||
let params = &message["params"];
|
||||
match message["event"].as_str() {
|
||||
// The server listens on every interface; embedded pages may only come from `HOST`.
|
||||
Some("widget_preview.started") => params["url"]
|
||||
.as_str()
|
||||
.map_or(Line::Skip, |url| Line::Url(url.replacen("//localhost:", &format!("//{HOST}:"), 1))),
|
||||
Some("widget_preview.logMessage") if matches!(params["level"].as_str(), Some("error" | "warning")) => {
|
||||
params["message"].as_str().map_or(Line::Skip, |text| Line::Output(text.to_owned()))
|
||||
}
|
||||
_ => Line::Skip,
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(message: String) -> String {
|
||||
// What an older `flutter` says of a command or an option it doesn't know.
|
||||
if message.contains("Could not find a") && message.contains(" named \"") {
|
||||
format!(
|
||||
"Flutter Widget Preview needs Flutter {MIN_FLUTTER} or later. Upgrade Flutter, then refresh the window."
|
||||
)
|
||||
} else if message.is_empty() {
|
||||
"flutter widget-preview exited".into()
|
||||
} else {
|
||||
message
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn url(line: &str) -> Option<String> {
|
||||
match super::line(line) {
|
||||
Line::Url(url) => Some(url),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn output(line: &str) -> Option<String> {
|
||||
match super::line(line) {
|
||||
Line::Output(text) => Some(text),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn started_gives_the_address_on_the_embeddable_host() {
|
||||
let line = r#"[{"event":"widget_preview.started","params":{"url":"http://localhost:56207"}}]"#;
|
||||
assert_eq!(url(line).as_deref(), Some("http://127.0.0.1:56207"));
|
||||
let launch =
|
||||
r#"[{"event":"widget_preview.app.webLaunchUrl","params":{"url":"http://localhost:1","launched":false}}]"#;
|
||||
assert_eq!(url(launch), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_errors_warnings_and_plain_text_are_kept() {
|
||||
let log = |level: &str| {
|
||||
format!(r#"[{{"event":"widget_preview.logMessage","params":{{"level":"{level}","message":"m"}}}}]"#)
|
||||
};
|
||||
assert_eq!(output(&log("error")).as_deref(), Some("m"));
|
||||
assert_eq!(output(&log("warning")).as_deref(), Some("m"));
|
||||
assert_eq!(output(&log("status")), None);
|
||||
assert_eq!(output(r#"[{"event":"widget_preview.initializing","params":{"pid":1}}]"#), None);
|
||||
assert_eq!(
|
||||
output("Could not find a command named \"widget-preview\".").as_deref(),
|
||||
Some("Could not find a command named \"widget-preview\".")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_flutter_is_named_as_the_cause() {
|
||||
for message in
|
||||
[r#"Could not find a command named "widget-preview"."#, r#"Could not find an option named "--web-server"."#]
|
||||
{
|
||||
assert!(failed(message.into()).starts_with("Flutter Widget Preview needs Flutter 3.38"));
|
||||
}
|
||||
assert_eq!(failed("pub get failed".into()), "pub get failed");
|
||||
assert_eq!(failed(String::new()), "flutter widget-preview exited");
|
||||
}
|
||||
}
|
||||
@@ -27,21 +27,17 @@ pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
|
||||
/// `logs` in the local data directory elsewhere (Tauri's `app_log_dir`), so a custom location
|
||||
/// from Settings › System Settings › Caches moves the logs too.
|
||||
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
|
||||
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
if let Some(var) = std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
return resolve_env(LOG_ENV, Some(var), None, identifier);
|
||||
let os = if cfg!(target_os = "macos") {
|
||||
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
|
||||
} else {
|
||||
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
|
||||
};
|
||||
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
|
||||
None => os.ok_or_else(|| "cannot find the log directory".into()),
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
return dirs::home_dir()
|
||||
.map(|home| home.join("Library/Logs").join(identifier))
|
||||
.ok_or_else(|| "cannot find the log directory".into());
|
||||
}
|
||||
startup_local_data_dir(identifier)
|
||||
.or_else(|_| local_data_dir(identifier))
|
||||
.map(|dir| dir.join("logs"))
|
||||
.map_err(|_| "cannot find the log directory".into())
|
||||
}
|
||||
|
||||
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
|
||||
@@ -221,74 +217,6 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// WebView2's profile (localStorage, IndexedDB, cookies) inside the directory the windows
|
||||
/// are given, which on Windows is the local data directory.
|
||||
pub const WEBVIEW_PROFILE: &str = "EBWebView";
|
||||
|
||||
/// Browser caches in a WebView2 profile: rebuilt on demand, so not copied across volumes.
|
||||
const WEBVIEW_CACHES: [&str; 6] = ["Cache", "Code Cache", "GPUCache", "DawnCache", "GrShaderCache", "ShaderCache"];
|
||||
|
||||
/// Brings WebView2's profile into `local` before the first window opens: from a scheduled
|
||||
/// move's source (Settings › System Settings › Caches), else from the default directory, where
|
||||
/// windows kept it before they followed a custom location. Runs synchronously, as a window
|
||||
/// started meanwhile would create an empty profile; a profile already in `local` is never
|
||||
/// merged into or replaced, and a failed move leaves the old one in place.
|
||||
pub fn adopt_webview_profile(identifier: &str, local: &Path) {
|
||||
let scheduled = migration_path(identifier)
|
||||
.and_then(|path| fs::read(path).ok())
|
||||
.and_then(|bytes| serde_json::from_slice::<CustomMigration>(&bytes).ok())
|
||||
.filter(|job| job.to == local)
|
||||
.map(|job| job.from);
|
||||
adopt_webview_profile_from(scheduled.into_iter().chain(local_data_dir(identifier).ok()), local);
|
||||
}
|
||||
|
||||
fn adopt_webview_profile_from(sources: impl IntoIterator<Item = PathBuf>, local: &Path) {
|
||||
let target = local.join(WEBVIEW_PROFILE);
|
||||
if target.try_exists().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let Some(source) = sources
|
||||
.into_iter()
|
||||
.filter(|dir| dir != local)
|
||||
.map(|dir| dir.join(WEBVIEW_PROFILE))
|
||||
.find(|profile| fs::symlink_metadata(profile).is_ok_and(|m| m.is_dir()))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let result = fs::create_dir_all(local).and_then(|()| match rename_missing(&source, &target) {
|
||||
Err(error) if rename_failure(&error) == RenameFailure::Copy => {
|
||||
let staging = local.join(format!(".migration-{}", uuid::Uuid::new_v4()));
|
||||
let copied = copy_profile(&source, &staging).and_then(|()| rename_missing(&staging, &target));
|
||||
if staging.exists() {
|
||||
let _ = remove_entry(&staging);
|
||||
}
|
||||
copied.and_then(|()| remove_entry(&source))
|
||||
}
|
||||
other => other,
|
||||
});
|
||||
match result {
|
||||
Ok(()) => tracing::info!(?source, ?target, "moved the WebView profile to the local data directory"),
|
||||
Err(error) => tracing::warn!(?source, ?target, %error, "cannot move the WebView profile; starting a new one"),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`copy_tree`] without the profile's browser caches.
|
||||
fn copy_profile(source: &Path, target: &Path) -> io::Result<()> {
|
||||
let metadata = fs::symlink_metadata(source)?;
|
||||
if !metadata.is_dir() {
|
||||
return copy_tree(source, target);
|
||||
}
|
||||
fs::create_dir(target)?;
|
||||
for entry in fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
if WEBVIEW_CACHES.iter().any(|name| entry.file_name() == *name) {
|
||||
continue;
|
||||
}
|
||||
copy_profile(&entry.path(), &target.join(entry.file_name()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entries of a local-data tree that move to a newly chosen directory.
|
||||
/// Non-relocatable tool installs (virtual environments with absolute interpreter
|
||||
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
|
||||
@@ -624,46 +552,6 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_webview_profile_moves_into_a_custom_local_directory_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (default, custom) = (tmp.path().join("default"), tmp.path().join("custom"));
|
||||
let storage = default.join(WEBVIEW_PROFILE).join("Default/Local Storage");
|
||||
fs::create_dir_all(&storage).unwrap();
|
||||
fs::write(storage.join("leveldb"), "history").unwrap();
|
||||
adopt_webview_profile_from([default.clone()], &custom);
|
||||
let moved = custom.join(WEBVIEW_PROFILE).join("Default/Local Storage/leveldb");
|
||||
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
|
||||
assert!(!default.join(WEBVIEW_PROFILE).exists());
|
||||
// A profile already in place is never replaced by an older one.
|
||||
fs::create_dir_all(default.join(WEBVIEW_PROFILE)).unwrap();
|
||||
adopt_webview_profile_from([default.clone()], &custom);
|
||||
assert!(default.join(WEBVIEW_PROFILE).exists());
|
||||
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_directory_keeps_its_own_profile() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let profile = tmp.path().join(WEBVIEW_PROFILE);
|
||||
fs::create_dir_all(&profile).unwrap();
|
||||
adopt_webview_profile_from([tmp.path().to_path_buf()], tmp.path());
|
||||
assert!(profile.is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_profile_leaves_the_browser_caches_behind() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let source = tmp.path().join("source");
|
||||
fs::create_dir_all(source.join("Default/Cache/Cache_Data")).unwrap();
|
||||
fs::create_dir_all(source.join("Default/IndexedDB")).unwrap();
|
||||
fs::write(source.join("Default/Cache/Cache_Data/f_1"), "x").unwrap();
|
||||
fs::write(source.join("Default/IndexedDB/db"), "kept").unwrap();
|
||||
copy_profile(&source, &tmp.path().join("copy")).unwrap();
|
||||
assert_eq!(fs::read_to_string(tmp.path().join("copy/Default/IndexedDB/db")).unwrap(), "kept");
|
||||
assert!(!tmp.path().join("copy/Default/Cache").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
|
||||
let os = Some(PathBuf::from("/os"));
|
||||
|
||||
@@ -190,8 +190,6 @@ impl Host {
|
||||
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
|
||||
let global_settings = SettingsStore::load(&config_dir, None);
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
|
||||
let migration = ssh.clone();
|
||||
runtime.spawn_blocking(move || migration.start_password_migration());
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
@@ -401,7 +399,6 @@ impl Host {
|
||||
project.agents.shutdown();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
project.widget_preview.stop();
|
||||
project.notebooks.stop_admission();
|
||||
// What the closing window started goes with it — the builds and searches it
|
||||
// asked for, its runs, its shells and its debug sessions — and its language
|
||||
@@ -531,7 +528,6 @@ impl Host {
|
||||
for project in self.projects() {
|
||||
project.flutter.kill();
|
||||
project.devtools.kill();
|
||||
project.widget_preview.kill();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -574,7 +570,6 @@ impl Host {
|
||||
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
|
||||
project.flutter.kill();
|
||||
project.devtools.kill();
|
||||
project.widget_preview.kill();
|
||||
}
|
||||
for project in &projects {
|
||||
project.plugin_diagnostics.close();
|
||||
|
||||
@@ -33,10 +33,8 @@ fn get_workspace_roots() -> Tool {
|
||||
"get_workspace_roots",
|
||||
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
|
||||
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
|
||||
Call this before the first project-related operation in a session, and when asked about the workspace, project or
|
||||
working directories. `projectRoot` is the project this connection serves, the default base for paths; `roots` is
|
||||
every project in the workspace, the scope to search and read, not a list of projects to change. It doesn't change the
|
||||
working directory or permissions. Other tools reach an attached project by its root as `projectPath`.",
|
||||
Call this when asked about the workspace, project or working directories, and before planning a change that may span
|
||||
projects. Other tools reach an attached project by its root as `projectPath`.",
|
||||
|call| async move {
|
||||
let root = call.root().to_path_buf();
|
||||
let mut roots = vec![root.clone()];
|
||||
|
||||
@@ -40,27 +40,11 @@ pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> I
|
||||
#[command(trust = trusted)]
|
||||
pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || project.devtools.url(&[]))
|
||||
tokio::task::spawn_blocking(move || project.devtools.url())
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
/// The address of the project's Widget Preview page, its server started on first use with the
|
||||
/// project's DevTools for its inspector. A server that failed or exited is only started again by
|
||||
/// the next request.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn flutter_widget_preview_url(host: &Host, window: &str) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
// Without it the tool starts a DevTools of its own.
|
||||
let devtools = project.devtools.url(&[]).map(|url| format!("--devtools-server-address={url}"));
|
||||
project.widget_preview.url(&Vec::from_iter(devtools.ok()))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
|
||||
flutter_devtools_url, flutter_widget_preview_url);
|
||||
flutter_devtools_url);
|
||||
@@ -413,31 +413,6 @@ pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos)
|
||||
}
|
||||
}
|
||||
|
||||
/// The Flutter Property Editor's arguments of the call at `pos`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_editable_arguments(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Option<EditableArguments>> {
|
||||
host.project(window)?.lsp.editable_arguments(doc, pos).await
|
||||
}
|
||||
|
||||
/// Sets an argument of the call at `pos`; the edit reaches the document as the server's
|
||||
/// `workspace/applyEdit`, undoable like any other.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_edit_argument(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
name: String,
|
||||
value: Option<ArgumentValue>,
|
||||
) -> IdeResult<()> {
|
||||
host.project(window)?.lsp.edit_argument(doc, pos, name, value).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
|
||||
let target = position_document(host, window, doc, pos).await?;
|
||||
@@ -3225,8 +3200,6 @@ ide_command::domain!(
|
||||
lsp_completion,
|
||||
lsp_document_colors,
|
||||
lsp_document_highlights,
|
||||
lsp_edit_argument,
|
||||
lsp_editable_arguments,
|
||||
lsp_document_links,
|
||||
lsp_exception_class_at,
|
||||
lsp_execute_code_action,
|
||||
|
||||
@@ -407,13 +407,6 @@ pub fn set_settings(
|
||||
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
|
||||
host.apply_git_executable();
|
||||
}
|
||||
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
|
||||
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
|
||||
for project in affected() {
|
||||
project.flutter.sdk_changed();
|
||||
project.devtools.stop();
|
||||
}
|
||||
}
|
||||
if is_proxy {
|
||||
host.apply_proxy();
|
||||
}
|
||||
|
||||
@@ -391,10 +391,8 @@ async fn start_inner(
|
||||
if config.command.is_empty() {
|
||||
return Err(IdeError::invalid("run configuration has no command"));
|
||||
}
|
||||
// A JVM on a run target gets no plugin agents; a local one gets them once its JDK is resolved.
|
||||
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
|
||||
add_java_agents(&mut config, &on_output, None);
|
||||
}
|
||||
let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
|
||||
add_java_agents(&mut config, &on_output, !on_target);
|
||||
// Settings › Run Targets: over SSH, or in a container.
|
||||
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
|
||||
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
|
||||
@@ -485,8 +483,6 @@ async fn start_inner(
|
||||
);
|
||||
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
|
||||
}
|
||||
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
add_java_agents(&mut config, &on_output, Some(&run_dir));
|
||||
if config.command == ide_sdk::godot::COMMAND {
|
||||
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
|
||||
}
|
||||
@@ -559,24 +555,14 @@ async fn start_inner(
|
||||
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
|
||||
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
|
||||
/// run target gets none; the console says so, and why an approved agent was left out.
|
||||
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
|
||||
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, local: bool) {
|
||||
if !ide_run::java_agent::applies(&config.kind) {
|
||||
return;
|
||||
}
|
||||
// The JVM the launch starts: a bare `java` (what generated configurations name) is looked
|
||||
// up the way the process start finds it, so the `jdk` filter of `vmOptions` sees that JDK.
|
||||
let java = run_dir.and_then(|dir| {
|
||||
let search = ide_run::wrap::search_path_in(config, dir);
|
||||
let home = config
|
||||
.env
|
||||
.get("JAVA_HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
|
||||
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
|
||||
});
|
||||
let agents = ide_run::java_agent::current_for(java.as_deref());
|
||||
let java = std::path::Path::new(&config.command);
|
||||
let agents = ide_run::java_agent::current_for(Some(java));
|
||||
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
|
||||
if run_dir.is_none() {
|
||||
if !local {
|
||||
if !agents.options.is_empty() {
|
||||
say(
|
||||
"Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.",
|
||||
|
||||
@@ -470,27 +470,6 @@ pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
|
||||
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
|
||||
}
|
||||
|
||||
/// `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
|
||||
/// search path when `path` is empty; `None` when there is no Flutter SDK.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn sdk_flutter_at(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: String,
|
||||
) -> IdeResult<Option<ide_sdk::flutter::FlutterVersion>> {
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
blocking_value(move || {
|
||||
let root = root.unwrap_or_default();
|
||||
let sdk = match ide_sdk::apply::setting_path(&root, &path) {
|
||||
Some(sdk) => Some(sdk),
|
||||
None => ide_core::tool_path::find_command("flutter", &ide_core::tool_path::search_path_in(&root), &root)
|
||||
.and_then(|f| ide_sdk::flutter::sdk_of(&f)),
|
||||
};
|
||||
sdk.and_then(|sdk| ide_sdk::flutter::version(&sdk))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -649,7 +628,6 @@ mod tests {
|
||||
ide_command::domain!(
|
||||
sdk:
|
||||
sdk_detect,
|
||||
sdk_flutter_at,
|
||||
sdk_jdk_at,
|
||||
sdk_locate_tools,
|
||||
sdk_php_composer_install,
|
||||
|
||||
@@ -4,10 +4,8 @@
|
||||
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::remote_settings::SshConfiguration;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult};
|
||||
use ide_ssh::secrets::LegacyPasswordAction;
|
||||
|
||||
/// Test Connection: connects with `config` as edited (not necessarily saved).
|
||||
#[command(trust = always)]
|
||||
@@ -17,23 +15,8 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
|
||||
|
||||
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
|
||||
#[command(trust = always)]
|
||||
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
|
||||
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
|
||||
host.window_sink(window).emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: "Could not save credential".into(),
|
||||
body: Some(e.message),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some` means legacy credentials remain in plaintext on this host.
|
||||
#[command(trust = always)]
|
||||
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
let ssh = host.ssh.clone();
|
||||
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
|
||||
host.ssh.set_secret(&id, secret, save);
|
||||
}
|
||||
|
||||
/// Whether a password is saved under `key` (an FTP deployment server's).
|
||||
@@ -69,7 +52,6 @@ ide_command::domain!(
|
||||
ssh:
|
||||
ssh_connected,
|
||||
ssh_disconnect,
|
||||
ssh_legacy_passwords,
|
||||
ssh_needs_secret,
|
||||
ssh_password_saved,
|
||||
ssh_set_secret,
|
||||
|
||||
@@ -68,9 +68,7 @@ pub struct Project {
|
||||
/// Flutter's devices; its daemon starts when the UI first asks for them.
|
||||
pub(crate) flutter: ide_flutter::FlutterDaemon,
|
||||
/// Flutter DevTools; its server starts when the UI first asks for it.
|
||||
pub(crate) devtools: ide_flutter::ToolServer,
|
||||
/// Flutter Widget Preview; its server starts when its tool window first opens.
|
||||
pub(crate) widget_preview: ide_flutter::ToolServer,
|
||||
pub(crate) devtools: ide_flutter::DevToolsServer,
|
||||
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
|
||||
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
|
||||
pub(crate) watcher: Arc<Watcher>,
|
||||
@@ -646,16 +644,8 @@ impl Host {
|
||||
let project = Arc::new(Project {
|
||||
plugin_diagnostics,
|
||||
trusted,
|
||||
flutter: ide_flutter::FlutterDaemon::new(
|
||||
root.clone(),
|
||||
sink.clone(),
|
||||
flutter_tool(&root, &settings, "flutter"),
|
||||
),
|
||||
devtools: ide_flutter::ToolServer::devtools(root.clone(), flutter_tool(&root, &settings, "dart")),
|
||||
widget_preview: ide_flutter::ToolServer::widget_preview(
|
||||
root.clone(),
|
||||
flutter_tool(&root, &settings, "flutter"),
|
||||
),
|
||||
flutter: ide_flutter::FlutterDaemon::new(root.clone(), sink.clone()),
|
||||
devtools: ide_flutter::DevToolsServer::new(root.clone()),
|
||||
root,
|
||||
sink,
|
||||
languages,
|
||||
@@ -905,16 +895,8 @@ impl Host {
|
||||
let project = Arc::new(Project {
|
||||
plugin_diagnostics,
|
||||
trusted: Arc::new(AtomicBool::new(false)),
|
||||
flutter: ide_flutter::FlutterDaemon::new(
|
||||
dir.clone(),
|
||||
sink.clone(),
|
||||
flutter_tool(&dir, &settings, "flutter"),
|
||||
),
|
||||
devtools: ide_flutter::ToolServer::devtools(dir.clone(), flutter_tool(&dir, &settings, "dart")),
|
||||
widget_preview: ide_flutter::ToolServer::widget_preview(
|
||||
dir.clone(),
|
||||
flutter_tool(&dir, &settings, "flutter"),
|
||||
),
|
||||
flutter: ide_flutter::FlutterDaemon::new(dir.clone(), sink.clone()),
|
||||
devtools: ide_flutter::DevToolsServer::new(dir.clone()),
|
||||
sink,
|
||||
languages,
|
||||
settings,
|
||||
@@ -1042,12 +1024,6 @@ fn light_watcher(
|
||||
)
|
||||
}
|
||||
|
||||
/// `flutter` / `dart` as Settings › Flutter chooses them, read each time the daemon or DevTools starts.
|
||||
fn flutter_tool(root: &Path, settings: &Arc<SettingsStore>, command: &'static str) -> ide_flutter::Configured {
|
||||
let (root, settings) = (root.to_path_buf(), settings.clone());
|
||||
Box::new(move || ide_sdk::apply::tool_command(&root, &settings.effective(), command))
|
||||
}
|
||||
|
||||
/// Looks for repositories nested below the project (and the one containing it);
|
||||
/// emits `VcsChanged` when the set of roots changed.
|
||||
fn scan_repositories(
|
||||
|
||||
@@ -287,7 +287,6 @@ impl crate::Host {
|
||||
project.agents.shutdown();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
project.widget_preview.stop();
|
||||
self.processes.kill_project(&project.root);
|
||||
project.notebooks.restrict().await;
|
||||
let windows: Vec<_> = self
|
||||
|
||||
@@ -2,26 +2,6 @@ mod common;
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
|
||||
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
|
||||
|
||||
use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = common::host_config(tmp.path());
|
||||
std::fs::create_dir_all(&config.data_dir).unwrap();
|
||||
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
|
||||
let host = Host::new(config);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("startup migration");
|
||||
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -136,8 +136,7 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
|
||||
save_secret: true,
|
||||
..Default::default()
|
||||
}]);
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
|
||||
ssh.set_secret("local-test", Some("secret".into()), true);
|
||||
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
|
||||
ssh.trust_host("local-test").await.unwrap();
|
||||
ssh.session("local-test").await.unwrap()
|
||||
|
||||
@@ -10,30 +10,6 @@ use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = common::host_config(tmp.path());
|
||||
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let host = Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let tx = tx.clone();
|
||||
Arc::new(move |e| tx.send(e).unwrap())
|
||||
}),
|
||||
..config
|
||||
});
|
||||
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
|
||||
let warning = rx.try_iter().find_map(|e| match e {
|
||||
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
|
||||
_ => None,
|
||||
});
|
||||
let warning = warning.expect("the window should be told saving failed");
|
||||
assert!(warning.contains("session only"));
|
||||
assert!(!warning.contains("test-value"));
|
||||
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
|
||||
}
|
||||
|
||||
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
|
||||
let mut all = String::new();
|
||||
while !all.contains(needle) {
|
||||
@@ -62,8 +38,7 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
|
||||
save_secret: true,
|
||||
..Default::default()
|
||||
}]);
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
ssh.set_secret("box", Some("secret".into()), true).unwrap();
|
||||
ssh.set_secret("box", Some("secret".into()), true);
|
||||
assert!(ssh.session("box").await.is_err(), "unknown host key first");
|
||||
ssh.trust_host("box").await.unwrap();
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
|
||||
auth: SshAuth::Password,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
|
||||
ssh.set_secret("selected-host", Some("secret".into()), false);
|
||||
assert!(ssh.session("selected-host").await.is_err());
|
||||
ssh.trust_host("selected-host").await.unwrap();
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ done
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains(":build-classpath"), "{calls}");
|
||||
assert!(calls.contains("dependency:build-classpath"), "{calls}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -305,18 +305,6 @@ impl PathFilter {
|
||||
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
|
||||
}
|
||||
|
||||
/// The folders directly in `dir` that the index would walk.
|
||||
pub(crate) fn child_dirs(&self, dir: &Path) -> Vec<PathBuf> {
|
||||
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
|
||||
builder
|
||||
.max_depth(Some(1))
|
||||
.build()
|
||||
.flatten()
|
||||
.filter(|e| e.depth() == 1 && e.file_type().is_some_and(|t| t.is_dir()))
|
||||
.map(|e| e.into_path())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec<PathBuf> {
|
||||
let matches = parking_lot::Mutex::new(Vec::new());
|
||||
for root in self.roots() {
|
||||
|
||||
@@ -26,12 +26,6 @@ pub use filter::walk_skips;
|
||||
pub use worker::MAX_SYMBOL_FILE;
|
||||
use worker::{Job, MAX_RECENT, Shared};
|
||||
|
||||
/// Stack of the indexing threads. Parsing and outlining a deeply nested file (generated
|
||||
/// code, a big JSON or minified script) recurse as deep as the file nests; the 2 MiB a Rust
|
||||
/// thread gets by default overflowed on Windows and took the whole IDE down (#5739). Only
|
||||
/// what a thread touches is committed, so the reservation costs address space, not memory.
|
||||
const INDEX_STACK: usize = 32 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileMatch {
|
||||
@@ -156,7 +150,6 @@ impl ProjectIndex {
|
||||
let shared = shared.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-index".into())
|
||||
.stack_size(INDEX_STACK)
|
||||
.spawn(move || shared.run(scan))
|
||||
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
|
||||
};
|
||||
|
||||
@@ -1246,66 +1246,3 @@ fn queries_during_streaming_scan_do_not_deadlock() {
|
||||
|
||||
done_rx.recv_timeout(Duration::from_secs(60)).expect("concurrent index queries deadlocked with streaming scan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconciling_a_few_changed_files_does_not_show_indexing() {
|
||||
let fx = sample();
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |e: IdeEvent| events.lock().push(e))
|
||||
};
|
||||
let idx = fx.open_with(sink);
|
||||
let announced = |events: &Mutex<Vec<IdeEvent>>| {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::IndexState { indexing: true, .. } | IdeEvent::Task { done: false, .. }))
|
||||
.count()
|
||||
};
|
||||
let settle = || {
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
// The touched folders are reconciled once the snapshot delay has passed.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
};
|
||||
|
||||
// A program appending to its log in the project, as a debugged Spring app does.
|
||||
events.lock().clear();
|
||||
let log = fx.write("logs/app.log", "start\n");
|
||||
for i in 0..3 {
|
||||
std::fs::write(&log, format!("line {i}\n").repeat(i + 1)).unwrap();
|
||||
idx.update(std::slice::from_ref(&log), &[]);
|
||||
settle();
|
||||
}
|
||||
assert_eq!(announced(&events), 0, "a log being written must not show Indexing");
|
||||
assert!(files(&idx, "app.log").contains(&"logs/app.log".to_owned()), "the log is still indexed");
|
||||
}
|
||||
|
||||
/// #5749: a file at the project root changing must not re-walk the whole project when the
|
||||
/// touched folders are reconciled, yet folders that appear or vanish there are still picked up.
|
||||
#[test]
|
||||
fn reconciling_a_root_change_lists_only_that_folder() {
|
||||
let fx = sample();
|
||||
let idx = fx.open();
|
||||
|
||||
// Written behind the index's back, deep in a folder it already knows.
|
||||
fx.write("src/order/Unreported.java", "class Unreported {}\n");
|
||||
// A new folder, a vanished one and an unreported file next to the changed root file.
|
||||
fx.write("fresh/deep/Fresh.java", "class Fresh {}\n");
|
||||
std::fs::remove_dir_all(fx.root.join("docs")).unwrap();
|
||||
fx.write("Unlisted.txt", "x\n");
|
||||
let log = fx.write("app.log", "line\n");
|
||||
idx.update(std::slice::from_ref(&log), &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
// The touched folders are reconciled once the snapshot delay has passed.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
|
||||
assert!(files(&idx, "app.log").contains(&"app.log".to_owned()), "the changed file is indexed");
|
||||
assert!(files(&idx, "Unlisted").contains(&"Unlisted.txt".to_owned()), "the root folder is listed");
|
||||
assert!(files(&idx, "Fresh").contains(&"fresh/deep/Fresh.java".to_owned()), "a new folder is walked");
|
||||
assert!(files(&idx, "maintenance").is_empty(), "a vanished folder's files are dropped");
|
||||
assert!(files(&idx, "main.rs").contains(&"src/main.rs".to_owned()), "other folders keep their files");
|
||||
assert!(files(&idx, "Unreported").is_empty(), "known subfolders are not re-walked");
|
||||
}
|
||||
+32
-128
@@ -22,7 +22,6 @@ use std::time::{Duration, Instant, SystemTime};
|
||||
static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.thread_name(|i| format!("openidea-index-{i}"))
|
||||
.stack_size(crate::INDEX_STACK)
|
||||
.build()
|
||||
.expect("cannot build index thread pool")
|
||||
});
|
||||
@@ -37,15 +36,6 @@ const PROGRESS_EVERY: Duration = Duration::from_millis(250);
|
||||
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
|
||||
#[cfg(test)]
|
||||
const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
|
||||
/// The shortest gap between two snapshot refreshes. Any index write drops the snapshot (see
|
||||
/// `Store::apply`), so a later refresh only makes the next startup faster; a project whose files
|
||||
/// keep changing (a log written inside it) would otherwise rewrite it every couple of seconds.
|
||||
#[cfg(not(test))]
|
||||
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
|
||||
#[cfg(test)]
|
||||
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
|
||||
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
|
||||
const QUIET_SCAN_FILES: usize = 200;
|
||||
pub(crate) const MAX_RECENT: usize = 50;
|
||||
|
||||
pub(crate) enum Job {
|
||||
@@ -85,8 +75,6 @@ pub(crate) struct Shared {
|
||||
idle: Condvar,
|
||||
/// Coalesced post-update snapshot refresh.
|
||||
snapshot_due: Mutex<Option<Instant>>,
|
||||
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
|
||||
snapshot_saved: Mutex<Option<Instant>>,
|
||||
/// Directories whose watcher events still need reconciliation before a
|
||||
/// refreshed snapshot can be trusted.
|
||||
pending_dirs: Mutex<HashSet<PathBuf>>,
|
||||
@@ -115,7 +103,6 @@ impl Shared {
|
||||
wake: Condvar::new(),
|
||||
idle: Condvar::new(),
|
||||
snapshot_due: Mutex::default(),
|
||||
snapshot_saved: Mutex::default(),
|
||||
pending_dirs: Mutex::default(),
|
||||
}
|
||||
}
|
||||
@@ -457,8 +444,7 @@ impl Shared {
|
||||
}
|
||||
|
||||
/// A cancelled scan (project closed) still ends its progress task and the indexing state.
|
||||
fn end_scan(&self, task: Option<TaskId>) {
|
||||
let Some(task) = task else { return };
|
||||
fn end_scan(&self, task: TaskId) {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
@@ -485,13 +471,13 @@ impl Shared {
|
||||
}
|
||||
|
||||
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
|
||||
self.scan(None, &[], found, guard);
|
||||
self.scan(None, found, guard);
|
||||
// Parsing every file churns through far more memory than the index keeps.
|
||||
ide_core::memory::release_free_pages();
|
||||
}
|
||||
|
||||
/// Shows "Indexing" (the status flag and a background task) for a scan.
|
||||
fn start_scan(&self) -> TaskId {
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
|
||||
let started = Instant::now();
|
||||
self.indexing.store(true, Ordering::SeqCst);
|
||||
self.emit_state();
|
||||
let task = TaskId::next();
|
||||
@@ -503,25 +489,6 @@ impl Shared {
|
||||
done: false,
|
||||
cancellable: false,
|
||||
});
|
||||
task
|
||||
}
|
||||
|
||||
/// A full scan shows "Indexing" from the start. A subtree scan (folders the watcher reported,
|
||||
/// reconciled after each burst of changes) shows it only once it has
|
||||
/// [`QUIET_SCAN_FILES`] or more files to parse: a program writing its log inside the project
|
||||
/// would otherwise keep "Indexing" in the status bar for as long as it runs.
|
||||
///
|
||||
/// Indexed files the walk didn't see are dropped when they are below one of `dirs` (all of
|
||||
/// them for a full scan) or directly in one of `shallow`.
|
||||
fn scan(
|
||||
&self,
|
||||
dirs: Option<&[PathBuf]>,
|
||||
shallow: &[PathBuf],
|
||||
prewalked: Option<Vec<Found>>,
|
||||
guard: SystemTime,
|
||||
) -> Option<ScanCounts> {
|
||||
let started = Instant::now();
|
||||
let mut task = dirs.is_none().then(|| self.start_scan());
|
||||
|
||||
let filter = self.filter();
|
||||
let walk_started = Instant::now();
|
||||
@@ -540,10 +507,7 @@ impl Shared {
|
||||
found.iter().filter_map(|f| prev_hash_if_stale(&d, f).map(|h| (f, h))).collect();
|
||||
let stale: Vec<PathBuf> = d
|
||||
.paths()
|
||||
.filter(|p| {
|
||||
dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir)))
|
||||
|| p.parent().is_some_and(|parent| shallow.iter().any(|dir| dir == parent))
|
||||
})
|
||||
.filter(|p| dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir))))
|
||||
.filter(|p| !seen.contains(p.as_path()))
|
||||
.cloned()
|
||||
.collect();
|
||||
@@ -560,9 +524,6 @@ impl Shared {
|
||||
self.persist(&[], &stale, false);
|
||||
|
||||
let total = todo.len();
|
||||
if task.is_none() && total >= QUIET_SCAN_FILES {
|
||||
task = Some(self.start_scan());
|
||||
}
|
||||
let update_started = Instant::now();
|
||||
let mut laps = ChunkLaps::default();
|
||||
{
|
||||
@@ -603,9 +564,7 @@ impl Shared {
|
||||
}
|
||||
done += batch.len();
|
||||
laps.add(self.publish(batch.drain(..)));
|
||||
if let Some(task) = task
|
||||
&& last_progress.elapsed() >= PROGRESS_EVERY
|
||||
{
|
||||
if last_progress.elapsed() >= PROGRESS_EVERY {
|
||||
last_progress = Instant::now();
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
@@ -647,19 +606,15 @@ impl Shared {
|
||||
}
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
*self.snapshot_due.lock() = None;
|
||||
*self.snapshot_saved.lock() = Some(Instant::now());
|
||||
if let Some(task) = task {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
title: "Indexing".into(),
|
||||
message: None,
|
||||
fraction: Some(1.0),
|
||||
done: true,
|
||||
cancellable: false,
|
||||
});
|
||||
}
|
||||
// The counts may have changed either way.
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
title: "Indexing".into(),
|
||||
message: None,
|
||||
fraction: Some(1.0),
|
||||
done: true,
|
||||
cancellable: false,
|
||||
});
|
||||
self.emit_state();
|
||||
if self.is_cancelled() {
|
||||
return None;
|
||||
@@ -802,67 +757,17 @@ impl Shared {
|
||||
}
|
||||
let mut due = self.snapshot_due.lock();
|
||||
if due.is_none() {
|
||||
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
|
||||
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
|
||||
*due = Some(Instant::now() + SNAPSHOT_DELAY);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
|
||||
/// A folder the index already has files below is listed one level deep: its own files, plus
|
||||
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
|
||||
/// knows nothing below is walked whole. Walking known folders whole would re-read the entire
|
||||
/// project after every change to a file at its root.
|
||||
fn reconcile(&self, dirs: &[PathBuf]) {
|
||||
let filter = self.filter();
|
||||
// The subfolders each reported folder has indexed files in; absent when it has none.
|
||||
let mut known: HashMap<&Path, HashSet<PathBuf>> = HashMap::new();
|
||||
{
|
||||
let d = self.data.read();
|
||||
for path in d.paths() {
|
||||
for dir in dirs {
|
||||
let Ok(rest) = path.strip_prefix(dir) else { continue };
|
||||
let subdirs = known.entry(dir.as_path()).or_default();
|
||||
let mut parts = rest.components();
|
||||
if let (Some(first), Some(_)) = (parts.next(), parts.next()) {
|
||||
subdirs.insert(dir.join(first));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
let mut trees = Vec::new();
|
||||
let mut shallow = Vec::new();
|
||||
for dir in dirs {
|
||||
let Some(indexed) = known.get(dir.as_path()) else {
|
||||
found.extend(filter.walk(dir, &self.cancelled));
|
||||
trees.push(dir.clone());
|
||||
continue;
|
||||
};
|
||||
found.extend(filter.list_dir(dir));
|
||||
shallow.push(dir.clone());
|
||||
for sub in filter.child_dirs(dir) {
|
||||
if !indexed.contains(&sub) {
|
||||
found.extend(filter.walk(&sub, &self.cancelled));
|
||||
trees.push(sub);
|
||||
}
|
||||
}
|
||||
// Gone from disk; a subfolder only hidden from the listing (an extra content root
|
||||
// or a newly excluded folder) is handled by its own root or the rule-change rescan.
|
||||
trees.extend(indexed.iter().filter(|sub| std::fs::symlink_metadata(sub).is_err()).cloned());
|
||||
}
|
||||
// Reported folders may nest; parse each file once.
|
||||
let mut unique = HashSet::new();
|
||||
found.retain(|f| unique.insert(f.path.clone()));
|
||||
self.scan(Some(&trees), &shallow, Some(found), SystemTime::now());
|
||||
}
|
||||
|
||||
fn save_snapshot_now(&self) {
|
||||
let dirs: Vec<PathBuf> = self.pending_dirs.lock().drain().collect();
|
||||
if !dirs.is_empty() {
|
||||
// Reconcile the directories touched since the last scan before
|
||||
// recording their mtimes; otherwise a missed watcher event could be
|
||||
// blessed into the manifest.
|
||||
self.reconcile(&dirs);
|
||||
self.scan(Some(&dirs), None, SystemTime::now());
|
||||
return;
|
||||
}
|
||||
if let Some(store) = &self.store {
|
||||
@@ -874,7 +779,6 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
*self.snapshot_due.lock() = None;
|
||||
*self.snapshot_saved.lock() = Some(Instant::now());
|
||||
}
|
||||
|
||||
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
|
||||
@@ -980,7 +884,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
if !rescan {
|
||||
self.scan(Some(&roots), &[], None, SystemTime::now());
|
||||
self.scan(Some(&roots), None, SystemTime::now());
|
||||
changed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
|
||||
removed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
|
||||
}
|
||||
@@ -1270,7 +1174,7 @@ mod metric_tests {
|
||||
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
|
||||
}
|
||||
std::fs::write(root.join("keep.txt"), "x").unwrap();
|
||||
shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 41);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
@@ -1294,7 +1198,7 @@ mod metric_tests {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "x").unwrap();
|
||||
}
|
||||
shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 7);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
@@ -1329,11 +1233,11 @@ mod metric_tests {
|
||||
for i in 0..count {
|
||||
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
|
||||
}
|
||||
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
|
||||
assert_eq!(shared.data.read().file_count as usize, count);
|
||||
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
|
||||
assert_eq!(hot.outcomes.total(), 0);
|
||||
}
|
||||
@@ -1345,7 +1249,7 @@ mod metric_tests {
|
||||
let shared = shared(&root);
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}").unwrap();
|
||||
shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let (found, hash) = {
|
||||
let data = shared.data.read();
|
||||
let e = data.get(&path).unwrap();
|
||||
@@ -1365,10 +1269,10 @@ mod metric_tests {
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}\n").unwrap();
|
||||
let shared = shared(&root);
|
||||
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
|
||||
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
|
||||
assert_eq!(hot.outcomes, ExtractionCounts::default());
|
||||
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
|
||||
@@ -1379,7 +1283,7 @@ mod metric_tests {
|
||||
rec.mtime = rec.mtime.wrapping_add(1);
|
||||
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
|
||||
shared.data.write().insert(entry, symbols);
|
||||
let touched = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
|
||||
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
|
||||
assert_eq!(shared.data.read().symbol_count, 1);
|
||||
@@ -1435,13 +1339,13 @@ mod metric_tests {
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
let found = index.walk_roots(None);
|
||||
index.load_persisted(&found);
|
||||
let counts = index.scan(None, &[], Some(found), SystemTime::now()).unwrap();
|
||||
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
|
||||
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
|
||||
assert_eq!(counts.outcomes, ExtractionCounts::default());
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
@@ -1458,7 +1362,7 @@ mod metric_tests {
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
@@ -1507,7 +1411,7 @@ mod metric_tests {
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
index.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
index.scan(None, None, SystemTime::now()).unwrap();
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
@@ -1558,7 +1462,7 @@ mod metric_tests {
|
||||
});
|
||||
index
|
||||
});
|
||||
assert!(index.scan(None, &[], None, SystemTime::now()).is_none());
|
||||
assert!(index.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(index.is_cancelled());
|
||||
assert!(!index.indexing.load(Ordering::Relaxed));
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
@@ -1569,7 +1473,7 @@ mod metric_tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let shared = shared(dir.path());
|
||||
shared.cancel();
|
||||
assert!(shared.scan(None, &[], None, SystemTime::now()).is_none());
|
||||
assert!(shared.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(!shared.indexing.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ mod tests {
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(json, "{\"threadDump\":{}}");
|
||||
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
|
||||
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
|
||||
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
@@ -87,7 +87,6 @@ use std::time::Duration;
|
||||
use text::{DocText, Encoding};
|
||||
use types::*;
|
||||
|
||||
const DART_SERVER: &str = "dart";
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -2449,34 +2448,6 @@ impl LspManager {
|
||||
.then(|| outline.items.clone())
|
||||
}
|
||||
|
||||
/// The arguments of the call at `pos` the Flutter Property Editor shows; `None` outside a
|
||||
/// call, or when no Dart server serves the document.
|
||||
pub async fn editable_arguments(&self, doc: DocId, pos: Pos) -> IdeResult<Option<EditableArguments>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
|
||||
let Some(t) = targets.iter().find(|t| t.server.name == DART_SERVER) else { return Ok(None) };
|
||||
self.call(t, "dart/textDocument/editableArguments", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await
|
||||
}
|
||||
|
||||
/// Sets the argument `name` of the call at `pos` to `value` (`None` passes null). The server
|
||||
/// sends the edit back as `workspace/applyEdit`, which the apply-edit hook applies.
|
||||
pub async fn edit_argument(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
name: String,
|
||||
value: Option<ArgumentValue>,
|
||||
) -> IdeResult<()> {
|
||||
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
|
||||
let t = targets
|
||||
.iter()
|
||||
.find(|t| t.server.name == DART_SERVER)
|
||||
.ok_or_else(|| IdeError::unavailable("no Dart language server serves this document"))?;
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["edit"] = json!({ "name": name, "newValue": value });
|
||||
let _: Value = self.call(t, "dart/textDocument/editArgument", params, None, DEFAULT_TIMEOUT).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records a published outline; whether what the open documents of `path` show changed.
|
||||
fn set_flutter_outline(
|
||||
&self,
|
||||
|
||||
@@ -654,57 +654,3 @@ pub struct ClassifiedReference {
|
||||
#[specta(optional)]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// The arguments the Flutter Property Editor edits: those of the widget (or other) call at a
|
||||
/// position, as the Dart server's `dart/textDocument/editableArguments` reports them.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EditableArguments {
|
||||
/// The widget's (or callee's) name.
|
||||
pub name: Option<String>,
|
||||
pub documentation: Option<String>,
|
||||
pub arguments: Vec<EditableArgument>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EditableArgument {
|
||||
pub name: String,
|
||||
pub documentation: Option<String>,
|
||||
/// How to edit it: `string`, `int`, `double`, `bool` or `enum`.
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
/// The literal value in the code (only while `has_argument`); an expression has `display_value`.
|
||||
pub value: Option<ArgumentValue>,
|
||||
#[serde(default)]
|
||||
pub has_argument: bool,
|
||||
pub default_value: Option<ArgumentValue>,
|
||||
pub display_value: Option<String>,
|
||||
// Absent from older Dart SDKs (`isDeprecated` came later): read as false rather than
|
||||
// failing the whole list.
|
||||
#[serde(default)]
|
||||
pub is_required: bool,
|
||||
#[serde(default)]
|
||||
pub is_nullable: bool,
|
||||
#[serde(default)]
|
||||
pub is_deprecated: bool,
|
||||
#[serde(default = "editable_by_default")]
|
||||
pub is_editable: bool,
|
||||
pub not_editable_reason: Option<String>,
|
||||
/// An enum's values, as `EnumName.value`.
|
||||
pub options: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
fn editable_by_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// A literal argument value. Ints stay ints: the server rejects `1.0` for an `int` parameter.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(untagged)]
|
||||
pub enum ArgumentValue {
|
||||
Bool(bool),
|
||||
Int(i64),
|
||||
Double(f64),
|
||||
Text(String),
|
||||
}
|
||||
@@ -1549,85 +1549,6 @@ async fn flutter_outline_follows_the_document_and_the_server_instance() {
|
||||
assert!(h.mgr.flutter_outline(reopened).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn property_editor_lists_the_dart_servers_arguments_and_applies_its_edit() {
|
||||
let h = harness(&[("dart", incremental_caps())]);
|
||||
let (doc, path) = h.open("a.mk", "Text('x')\n");
|
||||
h.wait_status("dart", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("dart");
|
||||
let arg = |name: &str, extra: Value| {
|
||||
let mut a = json!({ "name": name, "hasArgument": false, "isRequired": false, "isNullable": true,
|
||||
"isDeprecated": false, "isEditable": true });
|
||||
a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
a
|
||||
};
|
||||
let at = json!({"start":{"line":0,"character":0},"end":{"line":0,"character":9}});
|
||||
s.respond(
|
||||
"dart/textDocument/editableArguments",
|
||||
json!({ "textDocument": { "uri": uri_of(&path), "version": 1 }, "name": "Text", "range": at, "arguments": [
|
||||
arg("data", json!({ "type": "string", "value": "x", "hasArgument": true, "isRequired": true, "isNullable": false })),
|
||||
arg("textAlign", json!({ "type": "enum", "options": ["TextAlign.left", "TextAlign.center"] })),
|
||||
arg("maxLines", json!({ "type": "int", "value": 2, "hasArgument": true })),
|
||||
// An older SDK leaves out flags it doesn't know yet.
|
||||
json!({ "name": "softWrap", "type": "bool", "hasArgument": false }),
|
||||
]}),
|
||||
);
|
||||
let args = h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().unwrap();
|
||||
assert_eq!(args.name.as_deref(), Some("Text"));
|
||||
assert_eq!(
|
||||
(args.arguments[0].kind.as_str(), args.arguments[0].value.clone()),
|
||||
("string", Some(ArgumentValue::Text("x".into())))
|
||||
);
|
||||
assert_eq!(args.arguments[1].options.as_ref().unwrap()[1], "TextAlign.center");
|
||||
assert_eq!(args.arguments[1].value, None);
|
||||
assert!(args.arguments[3].is_editable && !args.arguments[3].is_deprecated && !args.arguments[3].is_required);
|
||||
assert_eq!(args.arguments[2].value, Some(ArgumentValue::Int(2)));
|
||||
let asked = s.requested("dart/textDocument/editableArguments");
|
||||
assert_eq!(asked[0]["position"], json!({"line":0,"character":2}));
|
||||
|
||||
// The server answers editArgument with null and sends the edit as workspace/applyEdit.
|
||||
let applied: Arc<Mutex<Vec<WorkspaceEdit>>> = Arc::default();
|
||||
let received = applied.clone();
|
||||
h.mgr.set_apply_edit_hook(Box::new(move |e| {
|
||||
received.lock().push(e);
|
||||
true
|
||||
}));
|
||||
let uri = uri_of(&path);
|
||||
*s.responder.lock() = Some(Arc::new(move |s, method, _| {
|
||||
(method == "dart/textDocument/editArgument").then(|| {
|
||||
let edit = json!({ "changes": { uri.clone(): [{ "range":
|
||||
{"start":{"line":0,"character":5},"end":{"line":0,"character":8}}, "newText": "'y'" }] } });
|
||||
let reply: Value = tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(s.peer().request(
|
||||
"workspace/applyEdit",
|
||||
json!({ "edit": edit }),
|
||||
None,
|
||||
))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(reply, json!({"applied": true}));
|
||||
Value::Null
|
||||
})
|
||||
}));
|
||||
h.mgr.edit_argument(doc, Pos::new(0, 2), "data".into(), Some(ArgumentValue::Text("y".into()))).await.unwrap();
|
||||
let sent = s.requested("dart/textDocument/editArgument");
|
||||
assert_eq!(sent[0]["edit"], json!({ "name": "data", "newValue": "y" }));
|
||||
assert_eq!(sent[0]["position"], json!({"line":0,"character":2}));
|
||||
let edits = applied.lock().clone();
|
||||
assert!(
|
||||
matches!(&edits[..], [e] if matches!(&e.files[0], FileEdit::Edit { edits, .. } if edits[0].new_text == "'y'"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn property_editor_has_nothing_without_a_dart_server() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, _) = h.open("a.mk", "Text('x')\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
assert!(h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().is_none());
|
||||
assert!(h.launcher.state("mock").requested("dart/textDocument/editableArguments").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -168,13 +168,8 @@ impl Session<'_> {
|
||||
"instructions": format!(
|
||||
"Built-in OpenIDEA tools for {about}: they see the files as the IDE has them and, \
|
||||
for a project open in a window, its editors. The project's workspace can include other \
|
||||
projects attached to it, which a session's working directory doesn't show. Before the \
|
||||
first project-related operation in a session, call `get_workspace_roots`: its \
|
||||
`projectRoot` is the project this connection serves and the default base for paths, and \
|
||||
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
|
||||
not a list of projects to change; it doesn't change your working directory or \
|
||||
permissions. Pass another root as `projectPath` to reach that project. Call it again \
|
||||
when the user switches projects or attaches one."
|
||||
projects attached to it: call `get_workspace_roots` to list them before answering about \
|
||||
workspace directories or planning a change across projects."
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -282,8 +282,6 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
|
||||
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
|
||||
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
|
||||
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
|
||||
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
|
||||
|
||||
@@ -123,27 +123,6 @@ fn is_jetbrains_jdk(java: &Path) -> bool {
|
||||
release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains"))
|
||||
}
|
||||
|
||||
/// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is
|
||||
/// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is
|
||||
/// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is
|
||||
/// `java_home`'s. `None` when neither is found.
|
||||
pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> {
|
||||
let path = Path::new(command);
|
||||
if path.components().count() > 1 {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
let windows = cfg!(windows);
|
||||
let found =
|
||||
ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref());
|
||||
if let Some(java) = &found
|
||||
&& release_field(java, "JAVA_VERSION").is_some()
|
||||
{
|
||||
return found;
|
||||
}
|
||||
let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" }));
|
||||
java.filter(|java| java.is_file()).or(found)
|
||||
}
|
||||
|
||||
/// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`).
|
||||
fn release_field(java: &Path, key: &str) -> Option<String> {
|
||||
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
|
||||
@@ -247,42 +226,6 @@ fn split_text(text: &str) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A JDK home with `bin/java` and a `release` file naming `implementor`.
|
||||
#[cfg(unix)]
|
||||
fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf {
|
||||
let home = root.join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
home
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_bare_java_is_the_one_the_launch_finds() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o.");
|
||||
let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium");
|
||||
// A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says.
|
||||
let search = std::env::join_paths([jbr.join("bin")]).unwrap();
|
||||
let java = launched_java("java", &search, Some(&openjdk)).unwrap();
|
||||
assert!(jdk_allows(Some(&java), Some("jetbrains")));
|
||||
// A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's.
|
||||
let stub = dir.path().join("usr/bin");
|
||||
std::fs::create_dir_all(&stub).unwrap();
|
||||
std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let search = std::env::join_paths([stub]).unwrap();
|
||||
let java = launched_java("java", &search, Some(&jbr)).unwrap();
|
||||
assert!(jdk_allows(Some(&java), Some("jetbrains")));
|
||||
assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains")));
|
||||
// A path is itself.
|
||||
assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java")));
|
||||
}
|
||||
|
||||
fn strings(a: &[&str]) -> Vec<String> {
|
||||
a.iter().map(|s| (*s).to_owned()).collect()
|
||||
}
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
|
||||
use crate::utf8::OutputDecoder;
|
||||
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
|
||||
use ide_core::pty::native_pty_system;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize};
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -127,7 +127,6 @@ pub(crate) fn info(def: &Def) -> GeneratorInfo {
|
||||
description: def.description.clone(),
|
||||
git: def.git,
|
||||
fields: def.fields.iter().map(field).collect(),
|
||||
directory: def.directory.clone(),
|
||||
dynamic: def.service.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,16 +57,6 @@ fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
|
||||
out
|
||||
}
|
||||
|
||||
/// The project folder's name: the generator's `directory` template (the solution name of a
|
||||
/// .NET project with a solution), or the project name.
|
||||
fn project_folder(def: &Def, name: &str, values: &Values) -> String {
|
||||
def.directory
|
||||
.as_deref()
|
||||
.map(|t| render(t, values).trim().to_owned())
|
||||
.filter(|folder| !folder.is_empty())
|
||||
.unwrap_or_else(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The fields a project service adds to the form (its metadata); empty for other generators.
|
||||
pub fn options(id: &str, values: &Values, cancel: &CancellationToken) -> IdeResult<Vec<Field>> {
|
||||
let def = def(id).ok_or_else(|| unknown(id))?;
|
||||
@@ -408,19 +398,15 @@ pub(crate) fn create_with(
|
||||
if let Some(e) = name_error(name) {
|
||||
return Err(IdeError::invalid(e));
|
||||
}
|
||||
let values = with_defaults(def, name, &req.values);
|
||||
let folder = project_folder(def, name, &values);
|
||||
if let Some(e) = name_error(&folder) {
|
||||
return Err(IdeError::invalid(e));
|
||||
}
|
||||
let location = req.location.to_path_buf();
|
||||
if !location.is_dir() {
|
||||
std::fs::create_dir_all(&location)?;
|
||||
}
|
||||
let target = location.join(&folder);
|
||||
let target = location.join(name);
|
||||
if target_taken(&target) {
|
||||
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
|
||||
}
|
||||
let values = with_defaults(def, name, &req.values);
|
||||
|
||||
let search = search_path();
|
||||
let mut missing = def
|
||||
@@ -434,10 +420,10 @@ pub(crate) fn create_with(
|
||||
return Err(IdeError::unavailable(format!("`{}`{need} is required to create this project", r.program)));
|
||||
}
|
||||
|
||||
let staging = Staging(location.join(format!(".{folder}.openidea-new-{}", std::process::id())));
|
||||
let staging = Staging(location.join(format!(".{name}.openidea-new-{}", std::process::id())));
|
||||
let _ = std::fs::remove_dir_all(&staging.0);
|
||||
std::fs::create_dir_all(&staging.0)?;
|
||||
let project = staging.0.join(&folder);
|
||||
let project = staging.0.join(name);
|
||||
|
||||
download_service(def, &values, &staging.0, &project, cancel, emit)?;
|
||||
let creates_dir = def.steps.iter().any(|s| s.cwd == Cwd::Parent && s.applies(&values));
|
||||
|
||||
@@ -169,17 +169,6 @@ fn dotnet_pins_the_sdk_and_creates_a_solution() {
|
||||
let (pin, lines) = render(&[("solution", "false")]);
|
||||
assert_eq!(pin, None);
|
||||
assert_eq!(lines, ["dotnet new console --name Shop --output . --language C#", "dotnet new gitignore"]);
|
||||
|
||||
// #5732: the top folder is the solution's (Store/Store.slnx, Store/Shop/Shop.csproj), as in
|
||||
// Rider and Visual Studio; without a solution `solution-name` isn't sent and it is the project's.
|
||||
let folder = |pairs: &[(&str, &str)]| {
|
||||
let given = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
project_folder(def, "Shop", &with_defaults(def, "Shop", &given))
|
||||
};
|
||||
assert_eq!(folder(&[("solution-name", "Store")]), "Store");
|
||||
assert_eq!(folder(&[]), "Shop");
|
||||
assert_eq!(folder(&[("solution", "false")]), "Shop");
|
||||
assert_eq!(folder(&[("solution-name", " ")]), "Shop");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -209,11 +198,6 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
|
||||
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
|
||||
assert_eq!(pin["sdk"]["version"], "10.0.400");
|
||||
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
|
||||
// A solution named apart from the project names the folder.
|
||||
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
|
||||
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(project, tmp.path().join("Store"));
|
||||
assert!(project.join("global.json").is_file());
|
||||
}
|
||||
|
||||
/// `dotnet` of a runtime-only install: `--version` fails ("No .NET SDKs were found").
|
||||
|
||||
@@ -30,11 +30,6 @@ pub(crate) struct Def {
|
||||
pub requires: Vec<RequireDef>,
|
||||
#[serde(default)]
|
||||
pub fields: Vec<FieldDef>,
|
||||
/// The project folder's name, when it isn't the project name: a template over the fields
|
||||
/// (.NET's solution name). Steps that create the folder themselves (`cwd = "parent"`) can't
|
||||
/// use it.
|
||||
#[serde(default)]
|
||||
pub directory: Option<String>,
|
||||
#[serde(default)]
|
||||
pub service: Option<ServiceDef>,
|
||||
/// Generation runs: the service's zip, `steps`, `files`, then `after`.
|
||||
@@ -285,9 +280,6 @@ pub struct GeneratorInfo {
|
||||
/// Offer "Create Git repository".
|
||||
pub git: bool,
|
||||
pub fields: Vec<Field>,
|
||||
/// The project folder's name when it isn't the project name: a template over the fields
|
||||
/// shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
|
||||
pub directory: Option<String>,
|
||||
/// More fields come from `scaffold_options` (a project service's metadata).
|
||||
pub dynamic: bool,
|
||||
}
|
||||
|
||||
@@ -1184,31 +1184,13 @@ pub fn tool_command(root: &Path, s: &Settings, command: &str) -> Option<PathBuf>
|
||||
if command == godot::COMMAND {
|
||||
return godot::find(custom);
|
||||
}
|
||||
custom.or_else(|| flutter_sdk_tool(root, s, command))
|
||||
}
|
||||
|
||||
/// `flutter` / `dart` of the Flutter SDK in Settings › Languages & Frameworks › Flutter, else
|
||||
/// `None` (the search path). Dart is the SDK's own (`bin/cache/dart-sdk`), else its `bin/dart`
|
||||
/// wrapper, which downloads it on first use.
|
||||
pub fn flutter_sdk_tool(root: &Path, s: &Settings, command: &str) -> Option<PathBuf> {
|
||||
let bin = setting_path(root, &s.languages.flutter.sdk)?.join("bin");
|
||||
let script = |name: &str| bin.join(if cfg!(windows) { format!("{name}.bat") } else { name.to_owned() });
|
||||
match command {
|
||||
"flutter" => Some(script("flutter")),
|
||||
"dart" => Some(
|
||||
Some(bin.join("cache/dart-sdk/bin").join(exe("dart")))
|
||||
.filter(|d| d.is_file())
|
||||
.unwrap_or_else(|| script("dart")),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
custom
|
||||
}
|
||||
|
||||
/// Points a run configuration launching a bare tool name at the executable from
|
||||
/// [`tool_command`] (Godot apps live outside the search path; `flutter` / `dart` follow the
|
||||
/// Flutter SDK setting).
|
||||
/// [`tool_command`] (Godot apps live outside the search path).
|
||||
pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
|
||||
if matches!(config.command.as_str(), godot::COMMAND | "flutter" | "dart")
|
||||
if config.command == godot::COMMAND
|
||||
&& let Some(path) = tool_command(root, s, &config.command)
|
||||
{
|
||||
config.command = path.to_string_lossy().into_owned();
|
||||
@@ -2225,12 +2207,9 @@ pub fn without_derived_in(config: &RunConfig, root: &Path, fallback: Option<&Pat
|
||||
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
|
||||
{
|
||||
// Generated configurations name the bare program (`java`), also on Windows where the
|
||||
// derived path ends in `java.exe` (`flutter.bat`).
|
||||
let bare = name
|
||||
.len()
|
||||
.checked_sub(4)
|
||||
.filter(|&at| name[at..].eq_ignore_ascii_case(".exe") || name[at..].eq_ignore_ascii_case(".bat"))
|
||||
.map(|at| &name[..at]);
|
||||
// derived path ends in `java.exe`.
|
||||
let bare =
|
||||
name.len().checked_sub(4).filter(|&at| name[at..].eq_ignore_ascii_case(".exe")).map(|at| &name[..at]);
|
||||
for candidate in bare.into_iter().chain([name.as_str()]) {
|
||||
let mut probe = out.clone();
|
||||
probe.command = candidate.to_owned();
|
||||
|
||||
@@ -32,7 +32,6 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
SdkKind::Ruby => crate::ruby::detect(root),
|
||||
SdkKind::Zig => zig(),
|
||||
SdkKind::Dotnet => dotnet(),
|
||||
SdkKind::Flutter => crate::flutter::detect(),
|
||||
};
|
||||
if let Some(root) = root {
|
||||
pinned_first(&mut out, kind, root);
|
||||
@@ -49,12 +48,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
|
||||
SdkKind::Maven => Some(Tool::Maven),
|
||||
SdkKind::Ruby => Some(Tool::Ruby),
|
||||
SdkKind::Zig => Some(Tool::Zig),
|
||||
SdkKind::Php
|
||||
| SdkKind::PackageManager
|
||||
| SdkKind::Rust
|
||||
| SdkKind::TypeScript
|
||||
| SdkKind::Dotnet
|
||||
| SdkKind::Flutter => None,
|
||||
SdkKind::Php | SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript | SdkKind::Dotnet => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
//! Flutter SDKs: Settings › Languages & Frameworks › Flutter (the Flutter plugin's "Flutter SDK path").
|
||||
|
||||
use crate::exec::query_in;
|
||||
use crate::{Sdk, home_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `flutter --version` may first unpack the Dart SDK or print the analytics notice.
|
||||
const VERSION_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// What `flutter --version --machine` reports of an SDK.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct FlutterVersion {
|
||||
/// SDK root (not part of Flutter's answer).
|
||||
pub root: String,
|
||||
pub framework_version: String,
|
||||
pub channel: Option<String>,
|
||||
pub dart_sdk_version: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn flutter_script(sdk: &Path) -> PathBuf {
|
||||
sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" })
|
||||
}
|
||||
|
||||
/// The SDK root of a `flutter` executable; on the search path it is often a link into the SDK.
|
||||
pub fn sdk_of(flutter: &Path) -> Option<PathBuf> {
|
||||
let real = dunce::canonicalize(flutter).ok()?;
|
||||
let root = real.parent()?.parent()?;
|
||||
flutter_script(root).is_file().then(|| root.to_path_buf())
|
||||
}
|
||||
|
||||
/// `flutter --version --machine` of the SDK at `sdk`. `None` when `sdk` holds no `bin/flutter`;
|
||||
/// an empty `framework_version` when it did not answer.
|
||||
pub fn version(sdk: &Path) -> Option<FlutterVersion> {
|
||||
let flutter = flutter_script(sdk);
|
||||
if !flutter.is_file() {
|
||||
return None;
|
||||
}
|
||||
let out = query_in(&flutter, &["--version", "--machine"], Some(sdk), &[], VERSION_TIMEOUT).unwrap_or_default();
|
||||
let mut version = parse_version(&out).unwrap_or_default();
|
||||
version.root = sdk.to_string_lossy().into_owned();
|
||||
Some(version)
|
||||
}
|
||||
|
||||
/// The JSON object of `flutter --version --machine`, after anything it printed first.
|
||||
fn parse_version(out: &str) -> Option<FlutterVersion> {
|
||||
let json = &out[out.find('{')?..=out.rfind('}')?];
|
||||
serde_json::from_str(json).ok()
|
||||
}
|
||||
|
||||
/// The framework version an SDK records, without running it.
|
||||
fn recorded_version(sdk: &Path) -> Option<String> {
|
||||
let json = std::fs::read_to_string(sdk.join("bin/cache/flutter.version.json")).ok();
|
||||
json.and_then(|j| parse_version(&j))
|
||||
.map(|v| v.framework_version)
|
||||
.or_else(|| std::fs::read_to_string(sdk.join("version")).ok().map(|v| v.trim().to_owned()))
|
||||
.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Flutter SDKs: the one on the search path, fvm's and the usual install folders.
|
||||
pub(crate) fn detect() -> Vec<Sdk> {
|
||||
let mut roots: Vec<(PathBuf, &str)> = Vec::new();
|
||||
if let Some(sdk) = crate::exec::which("flutter").and_then(|f| sdk_of(&f)) {
|
||||
roots.push((sdk, "path"));
|
||||
}
|
||||
if let Some(home) = home_dir() {
|
||||
for dir in ["flutter", "development/flutter", "sdk/flutter"] {
|
||||
roots.push((home.join(dir), "system"));
|
||||
}
|
||||
if let Ok(versions) = std::fs::read_dir(home.join("fvm/versions")) {
|
||||
roots.extend(versions.flatten().map(|e| (e.path(), "fvm")));
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
roots
|
||||
.into_iter()
|
||||
.filter(|(sdk, _)| flutter_script(sdk).is_file())
|
||||
.filter(|(sdk, _)| seen.insert(dunce::canonicalize(sdk).unwrap_or_else(|_| sdk.clone())))
|
||||
.map(|(sdk, source)| {
|
||||
let version = recorded_version(&sdk);
|
||||
Sdk {
|
||||
path: sdk.clone().into(),
|
||||
name: format!("Flutter {}", version.as_deref().unwrap_or_default()).trim().to_owned(),
|
||||
version,
|
||||
source: source.to_owned(),
|
||||
home: Some(sdk.into()),
|
||||
extra: None,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_the_version_after_what_flutter_printed_first() {
|
||||
let out = "Downloading Dart SDK…\n{\n \"frameworkVersion\": \"3.38.1\",\n \"channel\": \"stable\",\n \"dartSdkVersion\": \"3.10.0\"\n}\n";
|
||||
let v = parse_version(out).unwrap();
|
||||
assert_eq!(
|
||||
(v.framework_version.as_str(), v.channel.as_deref(), v.dart_sdk_version.as_deref()),
|
||||
("3.38.1", Some("stable"), Some("3.10.0"))
|
||||
);
|
||||
assert_eq!(parse_version("flutter: command not found"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_without_bin_flutter_is_no_sdk() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(version(dir.path()), None);
|
||||
std::fs::create_dir_all(dir.path().join("bin/cache")).unwrap();
|
||||
std::fs::write(flutter_script(dir.path()), "").unwrap();
|
||||
std::fs::write(dir.path().join("bin/cache/flutter.version.json"), r#"{"frameworkVersion":"3.35.0"}"#).unwrap();
|
||||
assert_eq!(recorded_version(dir.path()).as_deref(), Some("3.35.0"));
|
||||
assert_eq!(sdk_of(&flutter_script(dir.path())), Some(dunce::canonicalize(dir.path()).unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ mod astro;
|
||||
pub mod container_python;
|
||||
mod discover;
|
||||
mod exec;
|
||||
pub mod flutter;
|
||||
pub mod go;
|
||||
pub mod godot;
|
||||
pub mod java;
|
||||
@@ -58,8 +57,6 @@ pub enum SdkKind {
|
||||
Zig,
|
||||
/// .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins.
|
||||
Dotnet,
|
||||
/// Flutter SDK roots.
|
||||
Flutter,
|
||||
}
|
||||
|
||||
/// One installed interpreter / toolchain.
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_core::settings::Settings;
|
||||
use ide_language::LanguageServerConfig;
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
fn fake_venv(root: &Path, name: &str) -> std::path::PathBuf {
|
||||
@@ -2058,55 +2058,6 @@ fn the_godot_setting_applies_to_server_debugger_and_run_configurations() {
|
||||
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "zls"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flutter_sdk_setting_picks_flutter_and_dart_for_server_and_run_configurations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let sdk = tmp.path().join("flutter");
|
||||
let run = |command: &str| RunConfig {
|
||||
id: "dart:pub get".into(),
|
||||
name: "pub get".into(),
|
||||
kind: "dart-command".into(),
|
||||
command: command.into(),
|
||||
args: vec!["pub".into(), "get".into()],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
// No setting: the names stay for the search path.
|
||||
let mut s = Settings::default();
|
||||
let mut plain = run("flutter");
|
||||
apply_to_run_configs(std::slice::from_mut(&mut plain), tmp.path(), &s);
|
||||
assert_eq!(plain.command, "flutter");
|
||||
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), None);
|
||||
|
||||
// A project-relative SDK: `bin/flutter`, and `bin/dart` until the Dart SDK is unpacked.
|
||||
s.languages.flutter.sdk = "flutter".into();
|
||||
let flutter = sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" });
|
||||
let wrapper = sdk.join("bin").join(if cfg!(windows) { "dart.bat" } else { "dart" });
|
||||
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(wrapper));
|
||||
let dart = sdk.join("bin/cache/dart-sdk/bin").join(exe("dart"));
|
||||
std::fs::create_dir_all(dart.parent().unwrap()).unwrap();
|
||||
std::fs::write(&dart, "").unwrap();
|
||||
let mut cfg = server("dart");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(Path::new(&cfg.command), dart);
|
||||
|
||||
let mut configs = [run("flutter"), run("dart"), run("/usr/bin/flutter")];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(Path::new(&configs[0].command), flutter);
|
||||
assert_eq!(Path::new(&configs[1].command), dart);
|
||||
assert_eq!(configs[2].command, "/usr/bin/flutter");
|
||||
// Saved configurations keep the bare name.
|
||||
assert_eq!(crate::apply::without_derived(&configs[0], tmp.path(), &s).command, "flutter");
|
||||
// An explicit tool path still wins.
|
||||
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: "/opt/dart/bin/dart".into() });
|
||||
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(PathBuf::from("/opt/dart/bin/dart")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_library_paths_are_parsed_and_deduplicated() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! App-wide SSH connections, one per SSH configuration, shared by every
|
||||
//! feature that works on that host (deployment, run targets, data sources).
|
||||
|
||||
use crate::secrets::{LegacyPasswordAction, SecretFile};
|
||||
use crate::secrets::SecretFile;
|
||||
use crate::session::{ConnectError, Session, UnknownHostKey};
|
||||
use crate::target::{SshFiles, SshTarget};
|
||||
use ide_core::remote_settings::{SshAuth, SshConfiguration};
|
||||
@@ -14,7 +14,6 @@ use std::sync::Arc;
|
||||
pub struct SshManager {
|
||||
files: SshFiles,
|
||||
saved: SecretFile,
|
||||
startup_migration: std::sync::Once,
|
||||
/// Secrets entered this session (not saved, or not yet), by configuration id.
|
||||
entered: Mutex<HashMap<String, String>>,
|
||||
configs: RwLock<Vec<SshConfiguration>>,
|
||||
@@ -35,8 +34,7 @@ impl SshManager {
|
||||
pub fn with_files(secrets: PathBuf, files: SshFiles) -> Self {
|
||||
Self {
|
||||
files,
|
||||
saved: SecretFile::ssh_passwords(secrets),
|
||||
startup_migration: std::sync::Once::new(),
|
||||
saved: SecretFile::new(secrets),
|
||||
entered: Mutex::default(),
|
||||
configs: RwLock::default(),
|
||||
sessions: Mutex::default(),
|
||||
@@ -49,19 +47,6 @@ impl SshManager {
|
||||
&self.files
|
||||
}
|
||||
|
||||
pub fn start_password_migration(&self) {
|
||||
self.startup_migration.call_once(|| match self.saved.resolve_legacy(LegacyPasswordAction::Retry) {
|
||||
Ok(None) => {}
|
||||
Ok(Some(why)) => tracing::warn!("ssh-passwords.json still contains legacy plaintext credentials: {why}"),
|
||||
Err(e) => tracing::warn!("could not check ssh-passwords.json: {}", e.message),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn resolve_legacy_passwords(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
self.start_password_migration();
|
||||
self.saved.resolve_legacy(action)
|
||||
}
|
||||
|
||||
/// Replaces the configurations (Settings › SSH Configurations); sessions of
|
||||
/// changed or removed ones are closed, secrets of removed ones forgotten.
|
||||
pub fn set_configs(&self, configs: Vec<SshConfiguration>) {
|
||||
@@ -101,7 +86,7 @@ impl SshManager {
|
||||
|
||||
/// Remembers the password / passphrase of configuration `id` for the session,
|
||||
/// and in the saved passwords with `save` (`None` forgets it).
|
||||
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) {
|
||||
match &secret {
|
||||
Some(s) => {
|
||||
self.entered.lock().insert(id.to_owned(), s.clone());
|
||||
@@ -111,13 +96,12 @@ impl SshManager {
|
||||
}
|
||||
}
|
||||
match (secret, save) {
|
||||
(Some(s), true) => self.saved.set(id, &s).map_err(|e| {
|
||||
IdeError::unavailable(format!("The credential was kept for this session only. {}", e.message))
|
||||
}),
|
||||
_ => {
|
||||
self.saved.delete(id);
|
||||
Ok(())
|
||||
(Some(s), true) => {
|
||||
if let Err(e) = self.saved.set(id, &s) {
|
||||
tracing::warn!("could not save the SSH password: {}", e.message);
|
||||
}
|
||||
}
|
||||
_ => self.saved.delete(id),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+17
-164
@@ -25,14 +25,6 @@ static LOCK: Mutex<()> = Mutex::new(());
|
||||
/// Reads the secrets of an older version's file, by key (`None`: not that format).
|
||||
pub type Legacy = fn(serde_json::Value) -> Option<BTreeMap<String, String>>;
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LegacyPasswordAction {
|
||||
Check,
|
||||
Retry,
|
||||
RemovePlaintext,
|
||||
}
|
||||
|
||||
/// Where the secrets are kept: the default credential store, or a stand-in in tests.
|
||||
pub trait Vault: Send + Sync {
|
||||
fn available(&self) -> bool;
|
||||
@@ -85,7 +77,6 @@ pub struct SecretFile {
|
||||
path: PathBuf,
|
||||
legacy: Legacy,
|
||||
vault: Arc<dyn Vault>,
|
||||
keep_legacy_until_moved: bool,
|
||||
}
|
||||
|
||||
/// The file's contents. `id` keeps the credentials of different data directories
|
||||
@@ -96,11 +87,6 @@ struct Index {
|
||||
keys: BTreeSet<String>,
|
||||
}
|
||||
|
||||
enum Stored {
|
||||
Index(Index),
|
||||
Legacy(BTreeMap<String, String>),
|
||||
}
|
||||
|
||||
enum Contents {
|
||||
Index(Index),
|
||||
/// An older version's file that could not be moved, and why.
|
||||
@@ -136,17 +122,12 @@ impl SecretFile {
|
||||
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
|
||||
}
|
||||
|
||||
/// For the startup migration with a user-visible choice to retry or discard.
|
||||
pub(crate) fn ssh_passwords(path: PathBuf) -> Self {
|
||||
Self { keep_legacy_until_moved: true, ..Self::new(path) }
|
||||
}
|
||||
|
||||
pub fn with_legacy(path: PathBuf, legacy: Legacy) -> Self {
|
||||
Self::with_vault(path, legacy, Arc::new(DefaultStore))
|
||||
}
|
||||
|
||||
pub fn with_vault(path: PathBuf, legacy: Legacy, vault: Arc<dyn Vault>) -> Self {
|
||||
Self { path, legacy, vault, keep_legacy_until_moved: false }
|
||||
Self { path, legacy, vault }
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<String> {
|
||||
@@ -241,73 +222,21 @@ impl SecretFile {
|
||||
})
|
||||
}
|
||||
|
||||
fn read(&self) -> std::io::Result<Stored> {
|
||||
use std::io::{Error, ErrorKind};
|
||||
let bytes = match std::fs::read(&self.path) {
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {
|
||||
return Ok(Stored::Index(Index { id: new_id(), keys: BTreeSet::new() }));
|
||||
}
|
||||
other => other?,
|
||||
};
|
||||
let value = serde_json::from_slice::<serde_json::Value>(&bytes)
|
||||
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid JSON"))?;
|
||||
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
|
||||
return Ok(Stored::Index(index));
|
||||
}
|
||||
(self.legacy)(value).map(Stored::Legacy).ok_or_else(|| Error::new(ErrorKind::InvalidData, "unknown format"))
|
||||
}
|
||||
|
||||
fn load(&self) -> Contents {
|
||||
match self.read() {
|
||||
Ok(Stored::Index(index)) => Contents::Index(index),
|
||||
Ok(Stored::Legacy(old)) => self.migrate(old),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => self.set_aside(&e.to_string()),
|
||||
Err(e) => Contents::Plaintext(BTreeMap::new(), format!("{}: {e}", self.path.display())),
|
||||
let value = match std::fs::read(&self.path) {
|
||||
Err(_) => return Contents::Index(Index { id: new_id(), keys: BTreeSet::new() }),
|
||||
Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return self.set_aside(&e.to_string()),
|
||||
},
|
||||
};
|
||||
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
|
||||
return Contents::Index(index);
|
||||
}
|
||||
match (self.legacy)(value) {
|
||||
Some(old) => self.migrate(old),
|
||||
None => self.set_aside("unknown format"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some` means plaintext remains. Never overwrite an index that another window
|
||||
/// already migrated; an unreadable file is set aside, as on any other access.
|
||||
pub(crate) fn resolve_legacy(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
off_runtime(|| {
|
||||
let _g = LOCK.lock();
|
||||
let old = match self.read() {
|
||||
Ok(Stored::Legacy(old)) => old,
|
||||
Ok(Stored::Index(_)) => return Ok(None),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
|
||||
return match self.set_aside(&e.to_string()) {
|
||||
Contents::Index(_) => Ok(None),
|
||||
Contents::Plaintext(_, why) => Err(unavailable(&why)),
|
||||
};
|
||||
}
|
||||
Err(e) => return Err(unavailable(&format!("{}: {e}", self.path.display()))),
|
||||
};
|
||||
if matches!(action, LegacyPasswordAction::Check) && !old.is_empty() {
|
||||
return Ok(Some("Migration is incomplete.".into()));
|
||||
}
|
||||
if matches!(action, LegacyPasswordAction::RemovePlaintext) || old.is_empty() {
|
||||
// A partial move may already have secured some keys. Preserve their
|
||||
// namespace without needing the vault to be unlocked to remove plaintext.
|
||||
let pending = self.pending_path();
|
||||
let index = match std::fs::read_to_string(&pending) {
|
||||
Ok(id) if !id.trim().is_empty() => Index { id: id.trim().into(), keys: old.into_keys().collect() },
|
||||
Ok(_) => return Err(unavailable("empty migration id")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Index { id: new_id(), keys: BTreeSet::new() },
|
||||
Err(e) => return Err(unavailable(&format!("{}: {e}", pending.display()))),
|
||||
};
|
||||
self.write(&index)?;
|
||||
if let Err(e) = std::fs::remove_file(&pending)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!("saved passwords: could not remove {}: {e}", pending.display());
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match self.migrate(old) {
|
||||
Contents::Index(_) => None,
|
||||
Contents::Plaintext(_, why) => Some(why),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// An unreadable file is renamed rather than overwritten (it may index
|
||||
@@ -333,8 +262,8 @@ impl SecretFile {
|
||||
}
|
||||
|
||||
/// Moves an older version's secrets to the credential store, key by key; a secret
|
||||
/// the store refuses for good (too long, say) is forgotten unless the caller
|
||||
/// offers explicit recovery. The old file is replaced only when everything else was moved.
|
||||
/// the store refuses for good (too long, say) is forgotten, and the user is asked
|
||||
/// for it again. The old file is replaced only when everything else was moved.
|
||||
/// Until then the id waits in `<file>.migrating`, so a retry after a failure or a
|
||||
/// crash overwrites the same credentials instead of copying them again.
|
||||
fn migrate(&self, old: BTreeMap<String, String>) -> Contents {
|
||||
@@ -358,7 +287,7 @@ impl SecretFile {
|
||||
Ok(()) => {
|
||||
index.keys.insert(key.clone());
|
||||
}
|
||||
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) if !self.keep_legacy_until_moved => {
|
||||
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) => {
|
||||
tracing::warn!("saved passwords: {key} does not fit the credential store and is forgotten: {e}");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -496,82 +425,6 @@ mod tests {
|
||||
|
||||
const OLD: &str = r#"{"https://a.example": "me\nold-a", "https://b.example": "me\nold-b"}"#;
|
||||
|
||||
#[test]
|
||||
fn a_pending_plaintext_migration_can_be_retried_or_explicitly_discarded() {
|
||||
use LegacyPasswordAction::{Check, RemovePlaintext, Retry};
|
||||
for discard in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault::default());
|
||||
let file = with_fake(&path, &vault);
|
||||
assert!(file.resolve_legacy(Check).unwrap().is_none());
|
||||
assert!(!path.exists());
|
||||
std::fs::write(&path, OLD).unwrap();
|
||||
vault.fail("https://b.example", platform);
|
||||
assert!(file.resolve_legacy(Retry).unwrap().is_some());
|
||||
assert!(file.resolve_legacy(Check).unwrap().is_some());
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), OLD);
|
||||
if discard {
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
}
|
||||
vault.heal();
|
||||
assert!(file.resolve_legacy(Retry).unwrap().is_none());
|
||||
// A stale action from another window cannot erase a migrated index.
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
assert_eq!(files_containing(tmp.path(), "old-"), Vec::<PathBuf>::new());
|
||||
assert_eq!(file.get("https://a.example").as_deref(), Some("me\nold-a"));
|
||||
assert_eq!(file.get("https://b.example").as_deref(), (!discard).then_some("me\nold-b"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_plaintext_needs_no_vault_and_sets_an_unknown_format_aside() {
|
||||
use LegacyPasswordAction::{RemovePlaintext, Retry};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault { absent: true, ..Default::default() });
|
||||
let file = with_fake(&path, &vault);
|
||||
std::fs::write(&path, OLD).unwrap();
|
||||
assert!(file.resolve_legacy(Retry).unwrap().is_some());
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
assert!(files_containing(tmp.path(), "old-").is_empty());
|
||||
assert!(file.keys().is_empty());
|
||||
std::fs::write(&path, "unknown-format").unwrap();
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
let aside = files_containing(tmp.path(), "unknown-format");
|
||||
assert_eq!(aside.len(), 1);
|
||||
assert_ne!(aside[0], path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_keeps_the_only_copy_until_the_user_can_choose_what_to_do() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault::default());
|
||||
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
|
||||
vault.fail("box", || StoreError::TooLong("password".into(), 2560));
|
||||
std::fs::write(&path, r#"{"box":"legacy-value"}"#).unwrap();
|
||||
assert!(file.resolve_legacy(LegacyPasswordAction::Retry).unwrap().is_some());
|
||||
assert_eq!(file.get("box").as_deref(), Some("legacy-value"));
|
||||
assert_eq!(files_containing(tmp.path(), "legacy-value"), std::slice::from_ref(&path));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_ssh_file_is_set_aside_instead_of_blocking_new_saves() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault::default());
|
||||
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
|
||||
std::fs::write(&path, "{ malformed").unwrap();
|
||||
assert!(file.resolve_legacy(LegacyPasswordAction::Check).unwrap().is_none());
|
||||
let aside = files_containing(tmp.path(), "{ malformed");
|
||||
assert_eq!(aside.len(), 1);
|
||||
assert_ne!(aside[0], path);
|
||||
file.set("box", "new-value").unwrap();
|
||||
assert_eq!(file.get("box").as_deref(), Some("new-value"));
|
||||
assert!(files_containing(tmp.path(), "new-value").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_secrets_never_reach_disk() {
|
||||
use_memory_store();
|
||||
|
||||
@@ -4,11 +4,10 @@
|
||||
mod integration;
|
||||
mod scrollback;
|
||||
|
||||
use ide_core::pty::native_pty_system;
|
||||
use ide_core::utf8::Utf8Decoder;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize};
|
||||
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
@@ -164,7 +164,7 @@ Each form has **Host** and **Port** fields and shows the command to start the re
|
||||
- **Java HotSwap**: **Run › Debugging Actions › Reload Changed Classes** compiles your changes and reloads the changed classes into the running Java debug session. Active frames keep running the old code until they return. When JDT LS finishes a build after a save, the IDE offers the reload.
|
||||
- **JavaScript in the browser**: a **JavaScript Debug** configuration opens a URL in Chrome or Edge and debugs the page's scripts in their sources through source maps. See [JavaScript and TypeScript](/en/languages/javascript#debugging).
|
||||
- **Maven and Gradle**: debugging a Maven or Gradle configuration starts the JVM with a JDWP agent and attaches java-debug to it.
|
||||
- **Dart / Flutter**: **Settings › Languages & Frameworks › Flutter › Flutter SDK path** chooses the Flutter SDK whose `flutter` and Dart the language server, the debugger, run configurations, pub commands, the device list and **Build › Flutter** use; empty uses the ones on `PATH`. **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
|
||||
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
|
||||
- **PHP**: if the PHP interpreter does not load Xdebug, breakpoints are skipped; the IDE warns about this when the session starts.
|
||||
- **Python**: **Settings › Build, Execution, Deployment › Python Debugger** has **Attach to subprocess automatically while debugging** and **Gevent compatible**.
|
||||
|
||||
|
||||
@@ -46,11 +46,6 @@ through the app-wide SSH configurations.
|
||||
Saved passwords and passphrases go to the macOS Keychain, Windows Credential Manager or the Secret Service on Linux,
|
||||
never to a settings file. The **+**, **−** and copy buttons above the list add, remove and duplicate configurations.
|
||||
|
||||
Older versions stored saved credentials in plaintext in `ssh-passwords.json`. On startup, OpenIDEA moves them into
|
||||
the OS credential store. If the file still contains passwords, unlock the store and choose **Retry migration**, or
|
||||
choose **Remove plaintext copy** and re-enter any credentials that were not migrated. New credentials that cannot
|
||||
be saved are kept only for the session. Migration does not change old backups: rotate any exposed password.
|
||||
|
||||
### `~/.ssh/config` support
|
||||
|
||||
OpenIDEA has its own SSH client and reads `~/.ssh/config` itself. It understands `Host`, `Match`, `Include`,
|
||||
|
||||
@@ -166,7 +166,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
|
||||
- **Java HotSwap**:**运行 › 调试操作 › 重新加载已更改的类** 编译改动,并把变化的类重新加载到正在运行的 Java 调试会话中。已经在执行的帧要等返回后才会用上新代码。保存后 JDT LS 自动完成构建时,IDE 也会提示是否重新加载。
|
||||
- **浏览器中的 JavaScript**:**JavaScript 调试** 配置在 Chrome 或 Edge 中打开一个 URL,通过 source map 在源码中调试页面脚本。见 [JavaScript 与 TypeScript](/zh/languages/javascript)。
|
||||
- **Maven 和 Gradle**:调试 Maven 或 Gradle 配置时,IDE 会让 JVM 带上 JDWP agent 启动,再用 java-debug 附加上去。
|
||||
- **Dart / Flutter**:**设置 › 语言和框架 › Flutter › Flutter SDK 路径** 选择 Flutter SDK,语言服务器、调试器、运行配置、pub 命令、设备列表和 **构建 › Flutter** 都使用它的 `flutter` 和 Dart;留空则使用 `PATH` 中的。Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
|
||||
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
|
||||
- **PHP**:如果 PHP 解释器没有加载 Xdebug,断点会被跳过;会话启动时 IDE 会提示。
|
||||
- **Python**:**设置 › 构建、执行、部署 › Python 调试器** 中有 **调试时自动附加到子进程** 和 **兼容 Gevent**。
|
||||
|
||||
|
||||
@@ -38,10 +38,6 @@ OpenIDEA 通过 SSH 连接;在 Windows 上也可以直接连入 WSL 发行版
|
||||
保存的密码和密码短语存放在 macOS 钥匙串、Windows 凭据管理器或 Linux 的 Secret Service 中,不会写进设置文件。列表上方的
|
||||
**+**、**−** 和复制按钮用于添加、移除和复制配置。
|
||||
|
||||
旧版本会在 `ssh-passwords.json` 中明文保存凭据。OpenIDEA 会在启动时将它们迁移到系统凭据库。
|
||||
如果文件中仍有密码,可以解锁凭据库后选择**重试迁移**,也可以选择**移除明文副本**,并在下次使用时重新输入未迁移的凭据。
|
||||
无法保存的新凭据仅在当前会话中有效。迁移不会更改旧备份;如果备份中的密码已泄露,请更换密码。
|
||||
|
||||
### `~/.ssh/config` 支持
|
||||
|
||||
OpenIDEA 自带 SSH 客户端,自行读取 `~/.ssh/config`,支持 `Host`、`Match`、`Include`、`HostName`、`User`、`Port`、
|
||||
|
||||
@@ -313,8 +313,8 @@ for (const surface of ["new", "task"] as const) {
|
||||
const settings = page.getByRole("button", { name: /^Model settings:/ });
|
||||
await settings.click();
|
||||
await expect(page.getByRole("button", { name: "Back to models" })).toHaveCount(0);
|
||||
await page.getByRole("option", { name: "Thorough" }).click();
|
||||
await page.getByRole("option", { name: "1M" }).click();
|
||||
await page.getByRole("radio", { name: "Thorough" }).click();
|
||||
await page.getByRole("radio", { name: "1M" }).click();
|
||||
await expect(settings).toHaveText("Thorough · 1M");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(box(page)).toHaveText("Review the project structure");
|
||||
@@ -418,7 +418,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
|
||||
await expect(search).toHaveValue("keymap");
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await effortLabel(page).click();
|
||||
const popup = page.getByRole("listbox", { name: "Effort Level", exact: true });
|
||||
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
|
||||
await expect(popup).toBeVisible();
|
||||
await page.keyboard.press("Alt+t");
|
||||
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
|
||||
@@ -642,10 +642,10 @@ test("New Task discovers uncached model effort before the first prompt", async (
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
|
||||
await expectEffort(page, "Quick");
|
||||
await effortLabel(page).click();
|
||||
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
|
||||
await expect(efforts.getByRole("option", { name: "Quick", exact: true })).toBeVisible();
|
||||
await expect(efforts.getByRole("option", { name: "Thorough", exact: true })).toBeVisible();
|
||||
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
|
||||
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
|
||||
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
|
||||
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
|
||||
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(box(page)).toHaveText("Keep this first task unsent");
|
||||
await expectNoSubmission(page);
|
||||
@@ -675,9 +675,9 @@ test("an existing chat can choose effort for a refreshed model before sending",
|
||||
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
|
||||
await expectEffort(page, "Quick");
|
||||
await effortLabel(page).click();
|
||||
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
|
||||
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
|
||||
await efforts.getByRole("option", { name: "Thorough", exact: true }).click();
|
||||
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
|
||||
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
|
||||
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
await expectEffort(page, "Thorough");
|
||||
await expect(send).toBeEnabled();
|
||||
|
||||
@@ -413,7 +413,8 @@ test("keeps chat history readable and selections free of timestamps and status l
|
||||
expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/);
|
||||
await page.keyboard.press("ControlOrMeta+c");
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
|
||||
// The latest turn stays open: its reasoning shows as its own collapsed row.
|
||||
// The finished turn's reasoning is folded with its work.
|
||||
await stream.locator("[class*='_turnFold_'] > summary").click();
|
||||
await stream.locator("[class*='_thought_'] > summary").click();
|
||||
await expect(stream.locator("[class*='_thoughtPreview_']")).toHaveText("Requesting task context");
|
||||
await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context");
|
||||
@@ -794,7 +795,8 @@ test("Find in Conversation skips user-select:none summaries and closed <details>
|
||||
}, TASK);
|
||||
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
// A command is its own row, outside the reasoning's run.
|
||||
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
|
||||
await runSummary.click();
|
||||
await expect(stream.getByText("stop_bash")).toBeVisible();
|
||||
|
||||
await stream.focus();
|
||||
@@ -892,14 +894,13 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
// Reasoning and read-only calls group into one run; commands and edits would be rows of their own.
|
||||
[
|
||||
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
|
||||
{
|
||||
type: "tool",
|
||||
id: "t1",
|
||||
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
|
||||
kind: "fetch",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: "All checks pending",
|
||||
@@ -910,7 +911,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
|
||||
type: "tool",
|
||||
id: "t2",
|
||||
title: "read_bash",
|
||||
kind: "read",
|
||||
kind: "other",
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: "E2E pass",
|
||||
@@ -920,7 +921,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
|
||||
type: "tool",
|
||||
id: "t3",
|
||||
title: "read_bash",
|
||||
kind: "read",
|
||||
kind: "other",
|
||||
status: "running",
|
||||
locations: [],
|
||||
output: "",
|
||||
|
||||
+9
-14
@@ -40,17 +40,13 @@ const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[]
|
||||
},
|
||||
]).flat();
|
||||
|
||||
/** Opens the 80-turn chat; `foldTurns` folds each earlier turn's work into one row. */
|
||||
async function openHistory(page: Page, foldTurns = false) {
|
||||
async function openHistory(page: Page) {
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task, entries, foldTurns }) => {
|
||||
async ({ task, entries }) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const store = await import(path);
|
||||
const { useProject } = await import(projectPath);
|
||||
useProject.setState({ settings: { agents: { foldTurns } } });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
@@ -62,12 +58,10 @@ async function openHistory(page: Page, foldTurns = false) {
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries, foldTurns },
|
||||
{ task, entries },
|
||||
);
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
// A turn shows its request, the read and the reasoning runs, the command, the edit and the reply;
|
||||
// folded, its work is one row. The latest turn stays open.
|
||||
await expect(stream.locator(":scope > *")).toHaveCount(foldTurns ? 79 * 3 + 6 : 80 * 6);
|
||||
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
return stream;
|
||||
}
|
||||
@@ -91,7 +85,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
|
||||
);
|
||||
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
|
||||
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
|
||||
await expect(stream.locator(":scope > *")).toHaveCount(80 * 6 + 1);
|
||||
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
|
||||
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
|
||||
const timer = await page.evaluate(async (id) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
@@ -192,7 +186,7 @@ for (const selected of [false, true]) {
|
||||
}
|
||||
|
||||
test("opens a folded turn with the keyboard and jumps back to the latest reply", async ({ page }) => {
|
||||
const stream = await openHistory(page, true);
|
||||
const stream = await openHistory(page);
|
||||
await stream.evaluate((el) => {
|
||||
el.scrollTop = 0;
|
||||
});
|
||||
@@ -203,8 +197,9 @@ test("opens a folded turn with the keyboard and jumps back to the latest reply",
|
||||
await summary.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(fold).toHaveAttribute("open", "");
|
||||
// A folded turn lists its work without nesting runs.
|
||||
await expect(fold.locator("[class*='_processRun_']")).toHaveCount(0);
|
||||
const run = fold.locator("[class*='_processRun_']").first();
|
||||
await expect(run).toBeVisible();
|
||||
await run.locator(":scope > summary").click();
|
||||
await expect(fold.getByText("read src/module-0.ts", { exact: true })).toBeVisible();
|
||||
await summary.focus();
|
||||
await page.keyboard.press("Space");
|
||||
|
||||
@@ -63,14 +63,7 @@ test("the chosen device is used for Run, and replaced while it is disconnected",
|
||||
await page.keyboard.press("Control+r");
|
||||
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
|
||||
const [started] = await ipcCalls(page, "run_start");
|
||||
expect((started!.config as { args: string[] }).args).toEqual([
|
||||
"run",
|
||||
"-t",
|
||||
"lib/main.dart",
|
||||
"-d",
|
||||
"chrome",
|
||||
"--machine",
|
||||
]);
|
||||
expect((started!.config as { args: string[] }).args).toEqual(["run", "-t", "lib/main.dart", "-d", "chrome"]);
|
||||
|
||||
const emit = (devices: unknown[]) =>
|
||||
page.evaluate(
|
||||
|
||||
@@ -476,46 +476,3 @@ test("difference navigation focuses and centres the merge result caret with sync
|
||||
await page.keyboard.press("Shift+F7");
|
||||
await check(101);
|
||||
});
|
||||
|
||||
test("scrolling one pane sideways scrolls the other two to the same offset", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 900, height: 600 });
|
||||
const long = (tag: string) => `const ${tag} = "${"x".repeat(400)}";`;
|
||||
await mountMerge(page, [
|
||||
lines(long("base"), "a", "b"),
|
||||
lines(long("ours"), "a", "b"),
|
||||
lines(long("theirs"), "a", "b"),
|
||||
]);
|
||||
const lefts = () =>
|
||||
page
|
||||
.locator("#merge-host .cm-scroller")
|
||||
.evaluateAll((els) => els.map((el) => Math.round((el as HTMLElement).scrollLeft)));
|
||||
for (const pane of ["Your version", "Result", "Their version"]) {
|
||||
const offset = pane === "Result" ? 240 : pane === "Your version" ? 120 : 60;
|
||||
await page
|
||||
.getByRole("region", { name: pane })
|
||||
.locator(".cm-scroller")
|
||||
.evaluate((el, x) => (el.scrollLeft = x), offset);
|
||||
await expect.poll(lefts).toEqual([offset, offset, offset]);
|
||||
}
|
||||
});
|
||||
|
||||
test("says when every change is processed and saves the result from the notice", async ({ page }) => {
|
||||
await mountMerge(page);
|
||||
await captureWrites(page);
|
||||
const notice = page.locator("#merge-host").getByText("All changes have been processed.");
|
||||
await expect(notice).toBeHidden();
|
||||
await page.getByRole("button", { name: "Resolve Simple Conflicts" }).click();
|
||||
await expect(status(page)).toHaveText("1 change left, 1 conflict");
|
||||
await expect(notice).toBeHidden();
|
||||
// The conflict left takes both sides.
|
||||
await page.getByRole("region", { name: "Your version" }).locator(".cm-merge-accept").first().click();
|
||||
await expect(notice).toBeHidden();
|
||||
await page.getByRole("region", { name: "Their version" }).locator(".cm-merge-accept").first().click();
|
||||
await expect(status(page)).toHaveText("All changes processed");
|
||||
await expect(notice).toBeVisible();
|
||||
await page.screenshot({ path: process.env.MERGE_SHOT, animations: "disabled" }).catch(() => undefined);
|
||||
await page.getByRole("button", { name: "Save changes and finish merging" }).click();
|
||||
// Nothing is left to confirm: the result is written and staged.
|
||||
await expect.poll(async () => (await writes(page)).some((call) => call.command === "vcsStage")).toBe(true);
|
||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||
});
|
||||
@@ -9,7 +9,6 @@ const java: GeneratorInfo = {
|
||||
order: 1,
|
||||
description: "A plain Java application built with Maven or Gradle.",
|
||||
git: true,
|
||||
directory: null,
|
||||
dynamic: false,
|
||||
fields: [
|
||||
{
|
||||
|
||||
@@ -23,7 +23,7 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await page.getByRole("option", { name: "Current File", exact: true }).click();
|
||||
const project = page.getByRole("region", { name: "Project", exact: true });
|
||||
const buttons = [
|
||||
...["Select Opened File", "Expand Selected", "Collapse All", "Options", "Hide"].map((name) =>
|
||||
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
|
||||
project.getByRole("button", { name, exact: true }),
|
||||
),
|
||||
...[
|
||||
@@ -66,8 +66,7 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await expect(button).toHaveCSS("outline-width", "2px");
|
||||
}
|
||||
|
||||
const expand = project.getByRole("button", { name: "Expand Selected", exact: true });
|
||||
await project.getByRole("treeitem", { name: "src", exact: true }).click();
|
||||
const expand = project.getByRole("button", { name: "Expand All", exact: true });
|
||||
await expand.hover();
|
||||
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
|
||||
await page.mouse.down();
|
||||
@@ -75,12 +74,6 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await page.mouse.up();
|
||||
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
|
||||
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
|
||||
const projectRoot = project.getByRole("treeitem", { name: /^acme-api/ });
|
||||
await expect(projectRoot).toHaveAttribute("aria-expanded", "false");
|
||||
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveCount(0);
|
||||
await projectRoot.click();
|
||||
await project.getByRole("tree", { name: "Project" }).press("ArrowRight");
|
||||
await expect(projectRoot).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
await project.getByRole("button", { name: "Options", exact: true }).click();
|
||||
|
||||
@@ -7,11 +7,10 @@ interface Node {
|
||||
label: string;
|
||||
children?: Node[];
|
||||
}
|
||||
const rowCount = new URLSearchParams(location.search).has("large") ? 6000 : 160;
|
||||
const longLabel = `z_${"long_file_name_".repeat(16)}.ts`;
|
||||
const initial: Node[] = [
|
||||
{ key: "src", label: "src", children: [{ key: "child", label: "child.ts" }] },
|
||||
...Array.from({ length: rowCount }, (_, i) => ({ key: `file-${i}`, label: `file_${i}.ts` })),
|
||||
...Array.from({ length: 160 }, (_, i) => ({ key: `file-${i}`, label: `file_${i}.ts` })),
|
||||
{ key: "wide", label: longLabel },
|
||||
];
|
||||
const shorten = (nodes: Node[]): Node[] =>
|
||||
|
||||
+1
-94
@@ -131,17 +131,14 @@ test("offscreen same-key updates remain estimates until the row is mounted again
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
|
||||
test("hidden trees retain the virtual viewport and reconcile pending width changes when shown", async ({ page }) => {
|
||||
test("hidden trees keep their widths and reconcile pending removals when shown", async ({ page }) => {
|
||||
await open(page);
|
||||
const tree = page.getByRole("tree", { name: "Width fixture", includeHidden: true });
|
||||
const before = await measureLong(page, tree);
|
||||
const row = await tree.getByRole("treeitem", { name: /^z_long/ }).elementHandle();
|
||||
const top = await tree.evaluate((node) => node.scrollTop);
|
||||
const spacer = tree.locator("[data-content-width]");
|
||||
const stored = await spacer.evaluate((node) => (node as HTMLElement).style.width);
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await expect(tree).toBeHidden();
|
||||
await tree.evaluate((node) => node.dispatchEvent(new Event("scroll")));
|
||||
// Give ResizeObserver deliveries a chance to run while there is no layout.
|
||||
await page.evaluate(
|
||||
() =>
|
||||
@@ -149,103 +146,13 @@ test("hidden trees retain the virtual viewport and reconcile pending width chang
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
}),
|
||||
);
|
||||
expect(await row.evaluate((node) => node.isConnected)).toBe(true);
|
||||
expect(await spacer.evaluate((node) => (node as HTMLElement).style.width)).toBe(stored);
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await expect(tree).toBeVisible();
|
||||
await expect.poll(() => metrics(tree)).toEqual(before);
|
||||
expect(await tree.evaluate((node) => node.scrollTop)).toBe(top);
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await page.getByRole("button", { name: "Delete widest" }).click();
|
||||
await page.getByRole("button", { name: "Change indent" }).click();
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
|
||||
test("a scroll just before hiding takes effect when the tree is shown again", async ({ page }) => {
|
||||
const tree = await open(page);
|
||||
await wheel(page, tree, 0, 10000);
|
||||
await expect(tree.getByRole("treeitem", { name: /^z_long/ })).toBeVisible();
|
||||
const visibility = page.getByRole("button", { name: "Toggle visibility" });
|
||||
await visibility.evaluate((button) => {
|
||||
document.querySelector<HTMLElement>('[role="tree"]')!.scrollTop = 0;
|
||||
(button as HTMLButtonElement).click();
|
||||
});
|
||||
await expect(tree).toBeHidden();
|
||||
await visibility.click();
|
||||
expect(await tree.evaluate((node) => node.scrollTop)).toBe(0);
|
||||
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test("large wheel and thumb jumps keep the viewport covered", async ({ page }) => {
|
||||
await page.goto("/e2e/treeWidth.html?large");
|
||||
const tree = page.getByRole("tree", { name: "Width fixture" });
|
||||
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
|
||||
const box = (await tree.boundingBox())!;
|
||||
const eventState = await tree.evaluateHandle((element) => {
|
||||
const coverage = () => {
|
||||
const { top, left } = element.getBoundingClientRect();
|
||||
const bottom = top + element.clientHeight;
|
||||
let covered = true;
|
||||
for (let y = top + 1; y < bottom; y += 8) {
|
||||
const row = element.ownerDocument.elementFromPoint(left + 12, y)?.closest("[data-row]");
|
||||
if (!row || !element.contains(row)) covered = false;
|
||||
}
|
||||
return { offset: element.scrollTop, covered, mounted: element.querySelectorAll("[data-row]").length };
|
||||
};
|
||||
const state = { wheel: coverage(), drag: coverage() };
|
||||
// At the end of the input event, before the browser can paint the new offset.
|
||||
window.addEventListener("wheel", () => (state.wheel = coverage()));
|
||||
window.addEventListener("pointermove", (event) => {
|
||||
if (event.buttons === 1) state.drag = coverage();
|
||||
});
|
||||
return state;
|
||||
});
|
||||
const maximum = await tree.evaluate((element) => element.scrollHeight - element.clientHeight);
|
||||
expect(maximum).toBeGreaterThan(140_000);
|
||||
|
||||
await page.mouse.move(box.x + 40, box.y + 100);
|
||||
for (const [delta, offset] of [
|
||||
[40_000, 40_000],
|
||||
[80_000, 120_000],
|
||||
[-90_000, 30_000],
|
||||
[-50_000, 0],
|
||||
] as const) {
|
||||
await page.mouse.wheel(0, delta);
|
||||
await expect.poll(async () => eventState.evaluate((state) => state.wheel.offset)).toBe(offset);
|
||||
expect(await eventState.evaluate((state) => state.wheel.covered)).toBe(true);
|
||||
}
|
||||
|
||||
const thumbX = box.x + box.width - 5;
|
||||
const thumbY = box.y + 12;
|
||||
const travel = await page.evaluate(
|
||||
({ x, y }) => {
|
||||
const thumb = document.elementFromPoint(x, y) as HTMLElement;
|
||||
return thumb.parentElement!.clientHeight - thumb.offsetHeight;
|
||||
},
|
||||
{ x: thumbX, y: thumbY },
|
||||
);
|
||||
expect(travel).toBeGreaterThan(0);
|
||||
await page.mouse.move(thumbX, thumbY);
|
||||
await page.mouse.down();
|
||||
try {
|
||||
for (const fraction of [0.65, 0.2, 0.95, 0.4, 1]) {
|
||||
const distance = Math.round(travel * fraction);
|
||||
await page.mouse.move(thumbX, thumbY + distance);
|
||||
const state = await eventState.evaluate((state) => state.drag);
|
||||
expect(state.covered).toBe(true);
|
||||
expect(state.mounted).toBeLessThanOrEqual(40);
|
||||
expect(Math.abs(state.offset - (distance / travel) * maximum)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
} finally {
|
||||
await page.mouse.up();
|
||||
}
|
||||
await expect(tree.getByRole("treeitem", { name: /^z_long/ })).toBeVisible();
|
||||
|
||||
// The pointer can remain over the tree's scrollbar for the next wheel gesture.
|
||||
await page.mouse.move(thumbX, box.y + box.height - 12);
|
||||
await page.mouse.wheel(0, -maximum);
|
||||
await expect.poll(async () => eventState.evaluate((state) => state.wheel.offset)).toBe(0);
|
||||
expect(await eventState.evaluate((state) => state.wheel.covered)).toBe(true);
|
||||
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -3,9 +3,6 @@ name = ".NET"
|
||||
group = ".NET"
|
||||
icon = "project-dotnet"
|
||||
description = "A .NET project from dotnet new."
|
||||
# With a solution, the top folder is named after it (MySolution/MyProject/MyProject.csproj).
|
||||
# `solution-name` is sent only while "Create solution" is checked; otherwise it renders the name.
|
||||
directory = "{{solution-name}}"
|
||||
|
||||
# `dotnet --version` fails without an SDK (a runtime-only install). Blazor Web App and the
|
||||
# other templates' current options need SDK 8.
|
||||
@@ -53,7 +50,6 @@ type = "checkbox"
|
||||
default = "true"
|
||||
hint = "As in Visual Studio: the solution file at the top, the project in its own folder."
|
||||
|
||||
|
||||
[[fields]]
|
||||
id = "solution-name"
|
||||
label = "Solution name:"
|
||||
|
||||
@@ -52,7 +52,6 @@
|
||||
"@codemirror/lang-html": "^6.4.12",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-less": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-sass": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
|
||||
Generated
-3
@@ -31,9 +31,6 @@ importers:
|
||||
'@codemirror/lang-javascript':
|
||||
specifier: ^6.2.5
|
||||
version: 6.2.5
|
||||
'@codemirror/lang-less':
|
||||
specifier: ^6.0.2
|
||||
version: 6.0.2
|
||||
'@codemirror/lang-markdown':
|
||||
specifier: ^6.5.2
|
||||
version: 6.5.2
|
||||
|
||||
@@ -15,9 +15,6 @@ fn main() {
|
||||
println!("cargo:rerun-if-changed={}", manifest.display());
|
||||
println!("cargo:rustc-link-arg=/MANIFEST:EMBED");
|
||||
println!("cargo:rustc-link-arg=/MANIFESTINPUT:{}", manifest.display());
|
||||
// Windows gives the main thread a 1 MB stack by default (macOS and Linux: 8 MB), which
|
||||
// unoptimized debug frames overflow (STATUS_STACK_OVERFLOW). Match the 8 MB elsewhere.
|
||||
println!("cargo:rustc-link-arg=/STACK:8388608");
|
||||
}
|
||||
tauri_build::try_build(tauri_build::Attributes::new().windows_attributes(windows)).expect("tauri build");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The OS clipboard's file list, so the project view and the file manager exchange files.
|
||||
//! The OS clipboard's file list, so the project view and Explorer exchange files.
|
||||
|
||||
use ide_command::desktop_command;
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
@@ -83,21 +83,7 @@ pub async fn clipboard_text(app: AppHandle) -> IdeResult<Option<String>> {
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_file_list(app: AppHandle) -> IdeResult<Vec<String>> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
app.run_on_main_thread(move || {
|
||||
ide_clipboard::request_files(move |paths| {
|
||||
let _ = tx.send(paths);
|
||||
})
|
||||
})
|
||||
.map_err(|error| IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}")))?;
|
||||
Ok(rx.await.unwrap_or_default().iter().map(|p| slash(p)).collect())
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
|
||||
}
|
||||
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
|
||||
}
|
||||
|
||||
/// Whether the clipboard holds files: cheap, for the Paste item's enabled state.
|
||||
|
||||
@@ -275,12 +275,6 @@ pub fn run() {
|
||||
})
|
||||
.on_window_event(|window, event| match event {
|
||||
tauri::WindowEvent::CloseRequested { .. } => {
|
||||
// A dead web engine never answers the page's close handler: close the window here.
|
||||
#[cfg(windows)]
|
||||
if windows_webview_recovery::browser_failed(window.app_handle()) {
|
||||
let _ = window.destroy();
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
linux_window_state::save_before_close(window.app_handle());
|
||||
if let Some(w) = window.try_state::<WindowsState>() {
|
||||
|
||||
@@ -13,10 +13,6 @@
|
||||
//! inside the window, so with several monitors its candidate window opens on the wrong
|
||||
//! one. Through the compositor (Mutter hands text-input to Fcitx's IBus frontend) it
|
||||
//! follows the caret, so GNOME Wayland sessions drop `GTK_IM_MODULE=fcitx`.
|
||||
//!
|
||||
//! WSLg's Wayland compositor has no usable GPU path for WebKitGTK (Mesa reports an
|
||||
//! incompatible driver and the window stays blank); its X server works, so WSL uses X11
|
||||
//! unless `GDK_BACKEND` is set.
|
||||
|
||||
const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
const DISABLE_EXPLICIT_SYNC: &str = "__NV_DISABLE_EXPLICIT_SYNC";
|
||||
@@ -25,10 +21,6 @@ const IM_MODULE: &str = "GTK_IM_MODULE";
|
||||
/// Run before other threads start (`set_var`).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn configure() {
|
||||
if use_x11_on_wsl(|k| std::env::var(k).ok()) {
|
||||
tracing::info!("WSLg: GDK_BACKEND=x11");
|
||||
unsafe { std::env::set_var("GDK_BACKEND", "x11") };
|
||||
}
|
||||
let nvidia = ["/proc/driver/nvidia/version", "/sys/module/nvidia"].iter().any(|p| std::path::Path::new(p).exists());
|
||||
if disable_explicit_sync(|k| std::env::var(k).ok(), nvidia) {
|
||||
tracing::info!("Wayland with the NVIDIA driver: {DISABLE_EXPLICIT_SYNC}=1");
|
||||
@@ -51,12 +43,6 @@ fn drop_fcitx_module(var: impl Fn(&str) -> Option<String>) -> bool {
|
||||
gnome && var(IM_MODULE).is_some_and(|m| matches!(m.trim(), "fcitx" | "fcitx5")) && gdk_wayland(&var)
|
||||
}
|
||||
|
||||
/// Under WSL with WSLg's X server available, unless the user chose a GDK backend.
|
||||
fn use_x11_on_wsl(var: impl Fn(&str) -> Option<String>) -> bool {
|
||||
let set = |k: &str| var(k).is_some_and(|v| !v.is_empty());
|
||||
(set("WSL_DISTRO_NAME") || set("WSL_INTEROP")) && set("DISPLAY") && !set("GDK_BACKEND")
|
||||
}
|
||||
|
||||
/// GTK 3's IBus input method module (`ibus-gtk3`), wherever the distribution keeps it.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn gtk_ibus_module_installed() -> bool {
|
||||
@@ -177,16 +163,6 @@ mod tests {
|
||||
assert!(!drop_fcitx_module(env(&[gnome[0], gnome[1], (IM_MODULE, "ibus")])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_uses_x11_unless_a_backend_is_chosen() {
|
||||
let wslg = [("WSL_DISTRO_NAME", "Ubuntu-24.04"), ("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
|
||||
assert!(use_x11_on_wsl(env(&wslg)));
|
||||
assert!(use_x11_on_wsl(env(&[("WSL_INTEROP", "/run/WSL/1_interop"), ("DISPLAY", ":0")])));
|
||||
assert!(!use_x11_on_wsl(env(&[wslg[0], wslg[1], wslg[2], ("GDK_BACKEND", "wayland")])));
|
||||
assert!(!use_x11_on_wsl(env(&[wslg[0], wslg[1]])), "no X server");
|
||||
assert!(!use_x11_on_wsl(env(&[wslg[1], wslg[2]])), "not WSL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_users_input_method_module() {
|
||||
let vars = [("WAYLAND_DISPLAY", "wayland-0"), ("XMODIFIERS", "@im=ibus"), (IM_MODULE, "wayland")];
|
||||
|
||||
@@ -76,10 +76,6 @@ impl AppState {
|
||||
// Caches: the previous tree moves first, so a pending invalidation still
|
||||
// wipes what was just moved.
|
||||
let identifier = app.config().identifier.clone();
|
||||
// Windows: the WebView2 profile follows the local data directory too, and must be in
|
||||
// place before the first window opens (the scheduled move below runs before them too).
|
||||
#[cfg(windows)]
|
||||
ide_host::data_dirs::adopt_webview_profile(&identifier, &local_data_dir);
|
||||
ide_host::data_dirs::apply_custom_migration(&identifier, &local_data_dir);
|
||||
// File › Invalidate Caches… requested at the last run.
|
||||
let removed = ide_workspace::caches::apply_pending(&data_dir, &local_data_dir);
|
||||
|
||||
@@ -850,18 +850,8 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let show_after_build = crate::linux_window_state::prepare(app, &mut config);
|
||||
// Windows opens a project window at the configured size (window-state restores only the
|
||||
// maximized flag there), which Restore Down returns to.
|
||||
#[cfg(windows)]
|
||||
if let Ok(Some(monitor)) = app.primary_monitor() {
|
||||
let area = monitor.work_area().size.to_logical::<f64>(monitor.scale_factor());
|
||||
let min = (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0));
|
||||
let (size, min) = fit_new_window((config.width, config.height), min, (area.width, area.height));
|
||||
(config.width, config.height) = size;
|
||||
(config.min_width, config.min_height) = (Some(min.0), Some(min.1));
|
||||
}
|
||||
let window = WebviewWindowBuilder::from_config(app, &config)
|
||||
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
|
||||
.and_then(|b| dev_font_preferences(b).on_new_window(open_popup_in_browser).build())
|
||||
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
|
||||
#[cfg(target_os = "linux")]
|
||||
decorate_csd(&window);
|
||||
@@ -1699,7 +1689,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
|
||||
// display's Space, so macOS keeps it too.
|
||||
#[cfg(target_os = "linux")]
|
||||
let builder = builder.and_then(|b| b.parent(&parent));
|
||||
let window = builder.and_then(|b| dev_font_preferences(webview_profile(app, b)).build()).map_err(|e| {
|
||||
let window = builder.and_then(|b| dev_font_preferences(b).build()).map_err(|e| {
|
||||
windows.forget(&label);
|
||||
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
|
||||
})?;
|
||||
@@ -2114,18 +2104,6 @@ fn fit_over_parent(
|
||||
rx.recv_timeout(FIT_ON_MAIN_TIMEOUT).map_err(|_| tauri::Error::FailedToReceiveMessage)
|
||||
}
|
||||
|
||||
/// A new window's size and minimum size (logical pixels) shrunk to fit `area`, the work area of
|
||||
/// the monitor it opens on: the default 1440×900 is taller than a 1920×1080 laptop screen at
|
||||
/// 150 % scaling once the taskbar is taken off.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn fit_new_window(size: (f64, f64), min: (f64, f64), area: (f64, f64)) -> ((f64, f64), (f64, f64)) {
|
||||
if area.0 <= 0.0 || area.1 <= 0.0 {
|
||||
return (size, min);
|
||||
}
|
||||
let size = (size.0.min(area.0), size.1.min(area.1));
|
||||
(size, (min.0.min(size.0), min.1.min(size.1)))
|
||||
}
|
||||
|
||||
/// Centres the settings window over its owner, inside the owner's monitor work area. The window
|
||||
/// may still be on another display with a different scale, so its size is converted with its own
|
||||
/// scale and its position is given in physical pixels.
|
||||
@@ -2218,23 +2196,6 @@ fn open_popup_in_browser<R: tauri::Runtime>(
|
||||
tauri::webview::NewWindowResponse::Deny
|
||||
}
|
||||
|
||||
/// On Windows every window keeps WebView2's profile (localStorage, IndexedDB) in the local
|
||||
/// data directory, so a custom location from Settings › System Settings › Caches holds it too;
|
||||
/// Tauri would always use the default one. All windows share it: one WebView2 browser process
|
||||
/// serves a single profile folder.
|
||||
fn webview_profile<'a>(
|
||||
app: &AppHandle,
|
||||
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
|
||||
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
|
||||
#[cfg(windows)]
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
return builder.data_directory(state.host.local_data_dir.clone());
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = app;
|
||||
builder
|
||||
}
|
||||
|
||||
/// Reproduce WKWebView's user-font restriction before WKWebView creation. The
|
||||
/// private selector and environment override are absent from release builds.
|
||||
#[cfg(all(debug_assertions, target_os = "macos"))]
|
||||
@@ -2965,19 +2926,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_window_fits_the_work_area() {
|
||||
// 1920×1080 at 150 % with a 48-pixel taskbar (#5750).
|
||||
let area = (1280.0, 1032.0 / 1.5);
|
||||
assert_eq!(fit_new_window((1440.0, 900.0), (400.0, 500.0), area), ((1280.0, 688.0), (400.0, 500.0)));
|
||||
// A minimum larger than the screen gives way too.
|
||||
assert_eq!(fit_new_window((1440.0, 900.0), (400.0, 800.0), area).1, (400.0, 688.0));
|
||||
// A large screen keeps the configured size; an unknown work area changes nothing.
|
||||
let big = ((1440.0, 900.0), (400.0, 500.0));
|
||||
assert_eq!(fit_new_window(big.0, big.1, (2560.0, 1400.0)), big);
|
||||
assert_eq!(fit_new_window(big.0, big.1, (0.0, 0.0)), big);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_bounds_fit_current_work_area() {
|
||||
for (parent, size, work, expected) in [
|
||||
|
||||
@@ -1,45 +1,29 @@
|
||||
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI:
|
||||
//! not the prompt, not the title bar's close button (the window draws its own), and it never
|
||||
//! answers a close request. So the prompt is a native message box on its own thread, and the
|
||||
//! windows close without asking the page.
|
||||
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Manager, Webview, Wry, plugin};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||
use webview2_com::{
|
||||
Microsoft::Web::WebView2::Win32::{
|
||||
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED,
|
||||
COREWEBVIEW2_PROCESS_FAILED_REASON, ICoreWebView2, ICoreWebView2ProcessFailedEventArgs2,
|
||||
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED, ICoreWebView2,
|
||||
ICoreWebView2ProcessFailedEventArgs2,
|
||||
},
|
||||
ProcessFailedEventHandler,
|
||||
};
|
||||
use windows::core::Interface;
|
||||
|
||||
/// How long Restart waits for the event loop to restart the app before restarting the process
|
||||
/// itself (a main thread stuck in a call to the dead browser never handles the request).
|
||||
const RESTART_GRACE: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recovery {
|
||||
announced_browsers: Mutex<HashSet<u32>>,
|
||||
/// A browser process exited: the pages can't answer close requests any more.
|
||||
failed: AtomicBool,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
fn announce(&self, browser_pid: u32) -> bool {
|
||||
self.failed.store(true, Ordering::SeqCst);
|
||||
self.announced_browsers.lock().insert(browser_pid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the web engine has failed, so a window must close without asking its page.
|
||||
pub fn browser_failed(app: &AppHandle) -> bool {
|
||||
app.try_state::<Recovery>().is_some_and(|r| r.failed.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
plugin::Builder::new("webview-recovery")
|
||||
.setup(|app, _| {
|
||||
@@ -78,38 +62,21 @@ fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core:
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let details = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok();
|
||||
// SAFETY (all three): queried from the live callback arguments on this thread.
|
||||
let exit_code = details.as_ref().and_then(|args| {
|
||||
let exit_code = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok().and_then(|args| {
|
||||
let mut code = 0;
|
||||
// SAFETY: queried from the live callback arguments on this thread.
|
||||
unsafe { args.ExitCode(&mut code) }.ok().map(|()| code)
|
||||
});
|
||||
let reason = details.as_ref().and_then(|args| {
|
||||
let mut reason = COREWEBVIEW2_PROCESS_FAILED_REASON::default();
|
||||
unsafe { args.Reason(&mut reason) }.ok().map(|()| reason.0)
|
||||
});
|
||||
let description = details.as_ref().and_then(|args| {
|
||||
let mut description = Default::default();
|
||||
unsafe { args.ProcessDescription(&mut description) }.ok().map(|()| webview2_com::take_pwstr(description))
|
||||
});
|
||||
tracing::error!(
|
||||
window = %label,
|
||||
browser_pid,
|
||||
?exit_code,
|
||||
?reason,
|
||||
?description,
|
||||
"WebView2 browser process exited unexpectedly"
|
||||
);
|
||||
// Not through the main thread: it may be stuck in a call to the dead browser, and the
|
||||
// prompt must not run inline inside WebView2's STA callback either.
|
||||
tracing::error!(window = %label, browser_pid, ?exit_code, "WebView2 browser process exited unexpectedly");
|
||||
// Dispatch from a worker so Wry queues the prompt instead of running it
|
||||
// inline inside WebView2's STA callback.
|
||||
let app = app.clone();
|
||||
if let Err(error) = std::thread::Builder::new().name("webview-recovery".into()).spawn(move || {
|
||||
if ask_restart() {
|
||||
restart(&app);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let handle = app.clone();
|
||||
if let Err(error) = app.run_on_main_thread(move || show_recovery(handle)) {
|
||||
tracing::error!(%error, "cannot show WebView2 recovery prompt");
|
||||
}
|
||||
}) {
|
||||
tracing::error!(%error, "cannot show WebView2 recovery prompt");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}));
|
||||
let mut token = 0;
|
||||
@@ -117,37 +84,26 @@ fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core:
|
||||
unsafe { core.add_ProcessFailed(&handler, &mut token) }
|
||||
}
|
||||
|
||||
/// A native message box, on top of every window: true for Restart (OK).
|
||||
fn ask_restart() -> bool {
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
IDOK, MB_ICONERROR, MB_OKCANCEL, MB_SETFOREGROUND, MB_TOPMOST, MessageBoxW,
|
||||
};
|
||||
let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
|
||||
let text = wide(
|
||||
"The Windows web engine stopped unexpectedly, so OpenIDEA's windows can no longer respond.\n\n\
|
||||
Choose OK to restart OpenIDEA and recover the interface. This restarts all OpenIDEA windows; \
|
||||
unsaved edits may be lost.",
|
||||
);
|
||||
let title = wide("OpenIDEA");
|
||||
// SAFETY: both strings are NUL-terminated and outlive the call; no owner window.
|
||||
let answer = unsafe {
|
||||
MessageBoxW(
|
||||
std::ptr::null_mut(),
|
||||
text.as_ptr(),
|
||||
title.as_ptr(),
|
||||
MB_OKCANCEL | MB_ICONERROR | MB_TOPMOST | MB_SETFOREGROUND,
|
||||
fn show_recovery(app: AppHandle) {
|
||||
let mut dialog = app
|
||||
.dialog()
|
||||
.message(
|
||||
"The Windows web engine stopped unexpectedly. Restart OpenIDEA to recover the interface. \
|
||||
This restarts all OpenIDEA windows. Unsaved edits may be lost.",
|
||||
)
|
||||
};
|
||||
answer == IDOK
|
||||
}
|
||||
|
||||
fn restart(app: &AppHandle) {
|
||||
// The normal quit waits for a response from each webview. The failed browser cannot
|
||||
// answer, so restart through Tauri's native exit path.
|
||||
app.request_restart();
|
||||
std::thread::sleep(RESTART_GRACE);
|
||||
tracing::error!("the event loop did not restart OpenIDEA; restarting the process");
|
||||
tauri::process::restart(&app.env());
|
||||
.title("OpenIDEA")
|
||||
.kind(MessageDialogKind::Error)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Restart OpenIDEA".into(), "Cancel".into()));
|
||||
if let Some(window) = crate::windows::target_window(&app).filter(|w| w.is_visible().unwrap_or(false)) {
|
||||
dialog = dialog.parent(&window);
|
||||
}
|
||||
dialog.show(move |restart| {
|
||||
if restart {
|
||||
// The normal quit waits for a response from each webview. The failed browser
|
||||
// cannot answer, so restart through Tauri's native exit path.
|
||||
app.request_restart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -278,7 +278,6 @@ flutter_devices trusted project_host bin
|
||||
flutter_devices_refresh trusted project_host bindings sync
|
||||
flutter_devtools_url trusted project_host bindings async
|
||||
flutter_emulator_launch trusted project_host bindings async
|
||||
flutter_widget_preview_url trusted project_host bindings async
|
||||
fs_compare_directories always project_host bindings async
|
||||
fs_copy always project_host bindings async
|
||||
fs_copy_merge always project_host bindings async
|
||||
@@ -363,8 +362,6 @@ lsp_completion trusted project_host bin
|
||||
lsp_document_colors trusted project_host bindings async
|
||||
lsp_document_highlights trusted project_host bindings async
|
||||
lsp_document_links trusted project_host bindings async
|
||||
lsp_edit_argument trusted project_host bindings async
|
||||
lsp_editable_arguments trusted project_host bindings async
|
||||
lsp_exception_class_at trusted project_host bindings async
|
||||
lsp_execute_code_action trusted project_host bindings async
|
||||
lsp_execute_command trusted project_host bindings async
|
||||
@@ -613,7 +610,6 @@ scope_files always project_host bin
|
||||
sdk_container_python trusted project_host bindings sync
|
||||
sdk_container_python_refresh trusted project_host bindings async
|
||||
sdk_detect outside_restricted project_host bindings async
|
||||
sdk_flutter_at trusted project_host bindings async
|
||||
sdk_jdk_at trusted project_host bindings async
|
||||
sdk_locate_tools trusted project_host bindings async
|
||||
sdk_php_composer_install trusted project_host bindings async
|
||||
@@ -650,7 +646,6 @@ spring_route_sources trusted desktop bin
|
||||
ssh_askpass_answer always desktop bindings sync
|
||||
ssh_connected always project_host bindings sync
|
||||
ssh_disconnect always project_host bindings sync
|
||||
ssh_legacy_passwords always project_host bindings async
|
||||
ssh_needs_secret always project_host bindings sync
|
||||
ssh_open_terminal always desktop bindings async
|
||||
ssh_password_saved always project_host bindings sync
|
||||
|
||||
+1
-93
@@ -700,12 +700,6 @@ export const commands = {
|
||||
flutterDevtoolsUrl: () => typedError<string, IdeError>(__TAURI_INVOKE("flutter_devtools_url")),
|
||||
/** Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`. */
|
||||
flutterEmulatorLaunch: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("flutter_emulator_launch", { id })),
|
||||
/**
|
||||
* The address of the project's Widget Preview page, its server started on first use with the
|
||||
* project's DevTools for its inspector. A server that failed or exited is only started again by
|
||||
* the next request.
|
||||
*/
|
||||
flutterWidgetPreviewUrl: () => typedError<string, IdeError>(__TAURI_INVOKE("flutter_widget_preview_url")),
|
||||
fsCompareDirectories: (left: string, right: string, mode: DirectoryCompareMode, request: RequestId, onProgress: Channel<DirectoryCompareProgress>) => typedError<DirectoryCompareEntry[], IdeError>(__TAURI_INVOKE("fs_compare_directories", { left, right, mode, request, onProgress })),
|
||||
fsCopy: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy", { from, to })),
|
||||
fsCopyMerge: (sourceRoot: string, destinationRoot: string, path: string, overwrite: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy_merge", { sourceRoot, destinationRoot, path, overwrite })),
|
||||
@@ -906,18 +900,6 @@ export const commands = {
|
||||
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
|
||||
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
|
||||
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
|
||||
/**
|
||||
* Sets an argument of the call at `pos`; the edit reaches the document as the server's
|
||||
* `workspace/applyEdit`, undoable like any other.
|
||||
*/
|
||||
lspEditArgument: (doc: DocId, pos: Pos, name: string, value: boolean | number | number | null | string | null) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_edit_argument", { doc, pos, name, value })),
|
||||
/** The Flutter Property Editor's arguments of the call at `pos`. */
|
||||
lspEditableArguments: (doc: DocId, pos: Pos) => typedError<{
|
||||
/** The widget's (or callee's) name. */
|
||||
name: string | null,
|
||||
documentation: string | null,
|
||||
arguments: EditableArgument[],
|
||||
} | null, IdeError>(__TAURI_INVOKE("lsp_editable_arguments", { doc, pos })),
|
||||
/** The Throwable class the caret at `pos` names, for the exception breakpoint intention. */
|
||||
lspExceptionClassAt: (request: RequestId, doc: DocId, pos: Pos) => typedError<{
|
||||
/** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */
|
||||
@@ -1713,17 +1695,6 @@ export const commands = {
|
||||
} | null, IdeError>(__TAURI_INVOKE("sdk_container_python_refresh")),
|
||||
/** Installed interpreters / toolchains of `kind`; project-local ones first. */
|
||||
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
|
||||
/**
|
||||
* `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
|
||||
* search path when `path` is empty; `None` when there is no Flutter SDK.
|
||||
*/
|
||||
sdkFlutterAt: (path: string) => typedError<{
|
||||
/** SDK root (not part of Flutter's answer). */
|
||||
root?: string,
|
||||
frameworkVersion?: string,
|
||||
channel?: string | null,
|
||||
dartSdkVersion?: string | null,
|
||||
} | null, IdeError>(__TAURI_INVOKE("sdk_flutter_at", { path })),
|
||||
/** The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home. */
|
||||
sdkJdkAt: (path: string) => typedError<{
|
||||
/**
|
||||
@@ -1878,8 +1849,6 @@ export const commands = {
|
||||
/** Ids of the configurations with an open connection. */
|
||||
sshConnected: () => __TAURI_INVOKE<string[]>("ssh_connected"),
|
||||
sshDisconnect: (id: string) => __TAURI_INVOKE<void>("ssh_disconnect", { id }),
|
||||
/** `Some` means legacy credentials remain in plaintext on this host. */
|
||||
sshLegacyPasswords: (action: LegacyPasswordAction) => typedError<string | null, IdeError>(__TAURI_INVOKE("ssh_legacy_passwords", { action })),
|
||||
/** Whether connecting with configuration `id` needs a password first. */
|
||||
sshNeedsSecret: (id: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("ssh_needs_secret", { id })),
|
||||
/**
|
||||
@@ -3651,9 +3620,6 @@ export type ArduinoSettings = {
|
||||
fqbn?: string,
|
||||
};
|
||||
|
||||
/** A literal argument value. Ints stay ints: the server rejects `1.0` for an `int` parameter. */
|
||||
export type ArgumentValue = boolean | number | number | null | string;
|
||||
|
||||
/** Packaging artifact definition (Project Structure › Artifacts). */
|
||||
export type ArtifactConfig = {
|
||||
name?: string,
|
||||
@@ -6475,36 +6441,6 @@ export type DynamicItem = {
|
||||
checked?: boolean | null,
|
||||
};
|
||||
|
||||
export type EditableArgument = {
|
||||
name: string,
|
||||
documentation: string | null,
|
||||
/** How to edit it: `string`, `int`, `double`, `bool` or `enum`. */
|
||||
type: string,
|
||||
/** The literal value in the code (only while `has_argument`); an expression has `display_value`. */
|
||||
value: ArgumentValue | null,
|
||||
hasArgument?: boolean,
|
||||
defaultValue: ArgumentValue | null,
|
||||
displayValue: string | null,
|
||||
isRequired?: boolean,
|
||||
isNullable?: boolean,
|
||||
isDeprecated?: boolean,
|
||||
isEditable?: boolean,
|
||||
notEditableReason: string | null,
|
||||
/** An enum's values, as `EnumName.value`. */
|
||||
options: string[] | null,
|
||||
};
|
||||
|
||||
/**
|
||||
* The arguments the Flutter Property Editor edits: those of the widget (or other) call at a
|
||||
* position, as the Dart server's `dart/textDocument/editableArguments` reports them.
|
||||
*/
|
||||
export type EditableArguments = {
|
||||
/** The widget's (or callee's) name. */
|
||||
name: string | null,
|
||||
documentation: string | null,
|
||||
arguments: EditableArgument[],
|
||||
};
|
||||
|
||||
/** Editor › General › Appearance. */
|
||||
export type EditorAppearanceSettings = {
|
||||
caretBlinking?: boolean,
|
||||
@@ -7311,24 +7247,6 @@ export type FlutterEmulator = {
|
||||
platformType: string | null,
|
||||
};
|
||||
|
||||
/** The Flutter plugin's "Flutter SDK path". */
|
||||
export type FlutterSettings = {
|
||||
/**
|
||||
* Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
|
||||
* `PATH`. Empty = `PATH`.
|
||||
*/
|
||||
sdk?: string,
|
||||
};
|
||||
|
||||
/** What `flutter --version --machine` reports of an SDK. */
|
||||
export type FlutterVersion = {
|
||||
/** SDK root (not part of Flutter's answer). */
|
||||
root?: string,
|
||||
frameworkVersion?: string,
|
||||
channel?: string | null,
|
||||
dartSdkVersion?: string | null,
|
||||
};
|
||||
|
||||
export type FocusedEditor = {
|
||||
path: IpcPath,
|
||||
/** Zero-based lines and UTF-16 columns, end exclusive. */
|
||||
@@ -7485,11 +7403,6 @@ export type GeneratorInfo = {
|
||||
/** Offer "Create Git repository". */
|
||||
git: boolean,
|
||||
fields: Field[],
|
||||
/**
|
||||
* The project folder's name when it isn't the project name: a template over the fields
|
||||
* shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
|
||||
*/
|
||||
directory: string | null,
|
||||
/** More fields come from `scaffold_options` (a project service's metadata). */
|
||||
dynamic: boolean,
|
||||
};
|
||||
@@ -9191,7 +9104,6 @@ export type LanguagesSettings = {
|
||||
markdown?: MarkdownSettings,
|
||||
arduino?: ArduinoSettings,
|
||||
zig?: ZigSettings,
|
||||
flutter?: FlutterSettings,
|
||||
};
|
||||
|
||||
export type LargeCommitFile = {
|
||||
@@ -9285,8 +9197,6 @@ export type Launch_Serialize = {
|
||||
editor: EditorLaunch_Serialize | null,
|
||||
};
|
||||
|
||||
export type LegacyPasswordAction = "check" | "retry" | "removePlaintext";
|
||||
|
||||
/** One SDK or library with its source folders (`< Python 3.12 (.venv) >`). */
|
||||
export type LibraryGroup = {
|
||||
/** Display name, e.g. `Python 3.12 (.venv)`. */
|
||||
@@ -12680,9 +12590,7 @@ export type SdkKind = "python" | "node" |
|
||||
/** Zig toolchain directories. */
|
||||
"zig" |
|
||||
/** .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins. */
|
||||
"dotnet" |
|
||||
/** Flutter SDK roots. */
|
||||
"flutter";
|
||||
"dotnet";
|
||||
|
||||
/**
|
||||
* IDEA's search context: matches anywhere, only in, or outside comments and
|
||||
|
||||
@@ -16,16 +16,6 @@ describe("vue language mode", () => {
|
||||
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
|
||||
});
|
||||
|
||||
it('highlights Less inside <style lang="less">', async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
|
||||
const src = `<template><div/></template>\n<style lang="less">\n@c: red;\n.a { .b { color: @c; } .m(); }\n</style>`;
|
||||
const tree = support!.language.parser.parse(src).toString();
|
||||
// Less-only syntax: a top-level @-variable declaration, a mixin call and a nested rule.
|
||||
expect(tree).toContain("StyleSheet(Declaration(AtKeyword");
|
||||
expect(tree).toContain("Inclusion(ClassSelector");
|
||||
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
|
||||
});
|
||||
|
||||
it("still parses a plain <style> block as CSS", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
|
||||
const tree = support!.language.parser
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
/**
|
||||
* Vue single-file components: `@codemirror/lang-vue`'s parser over an HTML
|
||||
* base that also highlights `<style lang="scss|sass">` with the Sass grammar
|
||||
* and `<style lang="less">` with the Less one — stock `vue()` parses every
|
||||
* `<style>` as plain CSS, which loses their variables, nesting and mixins.
|
||||
* base that also highlights `<style lang="scss|sass">` with the Sass grammar —
|
||||
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
|
||||
* colours.
|
||||
*/
|
||||
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { lessLanguage } from "@codemirror/lang-less";
|
||||
import { sassLanguage } from "@codemirror/lang-sass";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
|
||||
@@ -28,14 +27,13 @@ export function vueLanguage(): LanguageSupport {
|
||||
const base = html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass/Less dialect re-parses it.
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
{ tag: "style", attrs: (a) => a.lang === "less", parser: lessLanguage.parser },
|
||||
],
|
||||
});
|
||||
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
|
||||
|
||||
@@ -90,8 +90,6 @@
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 3ch;
|
||||
text-align: end;
|
||||
}
|
||||
/* Pin and Archive appear beside the age while the pointer is on the row. */
|
||||
.rowActions {
|
||||
@@ -109,20 +107,6 @@
|
||||
.row:has(.rowActions:focus-within) .age {
|
||||
margin-left: 0;
|
||||
}
|
||||
/* The status mark sits in a fixed slot just before the age, so marks form a column. */
|
||||
.status {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
margin-left: auto;
|
||||
}
|
||||
.row:has(.status) .age,
|
||||
.row:hover .status,
|
||||
.row:has(.rowActions:focus-within) .status {
|
||||
margin-left: 0;
|
||||
}
|
||||
.rowAction {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -422,6 +422,8 @@ export function AgentsView() {
|
||||
n.task.title
|
||||
)}
|
||||
</span>
|
||||
{/* Ready tasks say so by their group; the others show what they're doing. */}
|
||||
{n.task.status !== "ready" && <TaskStatusIcon status={n.task.status} />}
|
||||
{unread.has(n.task.id) && (
|
||||
<span className={styles.unreadDot} role="img" aria-label={tx("Unread")} title={tx("Unread")} />
|
||||
)}
|
||||
@@ -440,13 +442,6 @@ export function AgentsView() {
|
||||
{canArchive(n.task) &&
|
||||
rowButton("Archive", "archive", () => void executeAction("agents.archiveTasks", [n.task.id]))}
|
||||
</span>
|
||||
{/* Ready tasks say so by their group; the others show what they're doing, in a column
|
||||
beside the age so the marks line up whatever the title length. */}
|
||||
{n.task.status !== "ready" && (
|
||||
<span className={styles.status}>
|
||||
<TaskStatusIcon status={n.task.status} />
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.age}>{age(n.task.updatedMs ?? 0)}</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
/* A framed text area (IDEA Islands surface), with compact pickers in its bottom row. */
|
||||
/* A framed text area (IDEA text field frame), with the pickers in its bottom row. */
|
||||
.composer {
|
||||
container: agent-composer / inline-size;
|
||||
min-width: 0;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-toolbar-button);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border-popup);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-field, var(--bg-button));
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
cursor: text;
|
||||
transition:
|
||||
background var(--dur-fast) var(--ease),
|
||||
box-shadow var(--dur-fast) var(--ease);
|
||||
transition: box-shadow var(--dur-fast) var(--ease);
|
||||
}
|
||||
.composer:focus-within {
|
||||
background: var(--bg-field, var(--bg-button));
|
||||
box-shadow:
|
||||
inset 0 0 0 1px var(--focus-ring),
|
||||
0 0 0 1px var(--focus-ring);
|
||||
@@ -50,8 +47,8 @@
|
||||
must land in the editable text, or they focus the bare scroller and no caret appears.
|
||||
A host sets --composer-min-height rather than overriding the rule, so stylesheet order can't undo it. */
|
||||
.field :global(.cm-content) {
|
||||
min-height: var(--composer-min-height, 38px);
|
||||
padding: 9px 12px 4px;
|
||||
min-height: var(--composer-min-height, 44px);
|
||||
padding: var(--space-2) var(--space-2) var(--space-0-5);
|
||||
caret-color: var(--fg-strong);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
@@ -89,31 +86,26 @@
|
||||
}
|
||||
.bar {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: var(--space-0-5);
|
||||
padding: 4px 6px 6px;
|
||||
cursor: default;
|
||||
}
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
flex-wrap: nowrap;
|
||||
flex: 1;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
gap: var(--space-0-5);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.toolbar > button {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
margin-left: auto;
|
||||
}
|
||||
/* Attach/reference buttons share the send button's 24px footprint and chrome. */
|
||||
/* Plain toolbar icons, framed only on hover like the rest of the IDE's toolbars. */
|
||||
@@ -122,60 +114,21 @@
|
||||
height: var(--h-control);
|
||||
}
|
||||
.spacer {
|
||||
display: none;
|
||||
flex: 1;
|
||||
}
|
||||
.configPicker,
|
||||
.modelControl {
|
||||
display: flex;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.modelControl {
|
||||
align-items: center;
|
||||
}
|
||||
.modelControl > .chip {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.configPicker > button {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.inlineSetting {
|
||||
flex: none;
|
||||
}
|
||||
.collapsed {
|
||||
display: none;
|
||||
}
|
||||
.compactDetail {
|
||||
display: none;
|
||||
}
|
||||
.settingsMenu {
|
||||
display: none;
|
||||
flex: none;
|
||||
}
|
||||
.settingsMenuVisible {
|
||||
display: flex;
|
||||
}
|
||||
/* Applied only synchronously during JS overflow measurement (never painted). */
|
||||
.toolbarMeasuring > *,
|
||||
.toolbarMeasuring .configPicker,
|
||||
.toolbarMeasuring .modelControl,
|
||||
.toolbarMeasuring .modelControl > .chip,
|
||||
.toolbarMeasuring .chip,
|
||||
.toolbarMeasuring .configPicker > button {
|
||||
flex: none;
|
||||
max-width: none;
|
||||
}
|
||||
.toolbarMeasuring .collapsed,
|
||||
.toolbarMeasuring .settingsMenu {
|
||||
display: flex;
|
||||
}
|
||||
.toolbarMeasuring .compactDetail {
|
||||
display: inline-grid;
|
||||
}
|
||||
.settingsPopup {
|
||||
width: min(320px, calc(100vw - 24px));
|
||||
@@ -201,17 +154,14 @@
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: var(--space-1-5);
|
||||
height: var(--h-control);
|
||||
min-width: 0;
|
||||
padding: 0 4px 0 6px;
|
||||
border-radius: var(--radius-toolbar-button);
|
||||
border-radius: var(--radius-control);
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background var(--dur-fast) var(--ease),
|
||||
color var(--dur-fast) var(--ease);
|
||||
transition: background var(--dur-fast) var(--ease);
|
||||
}
|
||||
.chip.chipLoading,
|
||||
.chip.chipLoading:hover {
|
||||
@@ -386,6 +336,54 @@
|
||||
padding: 8px 14px 2px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
@container agent-composer (max-width: 600px) {
|
||||
/* Narrow: keep one row of icons next to the agent picker. The model/mode pickers
|
||||
collapse into the settings menu, so nothing has to wrap onto a second line. */
|
||||
.bar {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.toolbar {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
.toolbar > button,
|
||||
.toolbar > .configPicker {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.configPicker > button {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.chipDetail {
|
||||
display: none;
|
||||
}
|
||||
.modelDetail {
|
||||
flex-shrink: 0;
|
||||
max-width: 65%;
|
||||
}
|
||||
.inlineSetting {
|
||||
display: none;
|
||||
}
|
||||
.settingsMenu {
|
||||
display: flex;
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
}
|
||||
.actions {
|
||||
width: auto;
|
||||
flex: none;
|
||||
margin-left: 0;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.actions .spacer {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
.pickerValue {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
|
||||
@@ -1323,9 +1323,7 @@ export function Composer(props: ComposerProps) {
|
||||
)}
|
||||
<div ref={hostRef} className={styles.field} />
|
||||
<div className={styles.bar} onMouseDown={(e) => e.stopPropagation()}>
|
||||
<div className={styles.toolbar} data-composer-toolbar="">
|
||||
{props.toolbar}
|
||||
</div>
|
||||
<div className={styles.toolbar}>{props.toolbar}</div>
|
||||
<div className={styles.actions}>
|
||||
<IconButton
|
||||
ref={addAnchor}
|
||||
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user