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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 8a326b3429 Merge remote-tracking branch 'origin/main' into feat/cargo-dependency-updates
# Conflicts:
#	src/platform/locales/textCatalog.test.ts
2026-11-01 19:27:14 +08:00
l0ng-ai 442f5b0407 feat: add Cargo dependency version inspections and updates 2026-11-01 19:18:31 +08:00
55 змінених файлів з 99 додано та 2626 видалено

No files matched your search

Створено
-2
Переглянути файл
@@ -4241,7 +4241,6 @@ dependencies = [
"ide-vfs",
"ide-workspace",
"parking_lot",
"rustix",
"serde",
"serde_json",
"specta",
@@ -6210,7 +6209,6 @@ dependencies = [
"tracing",
"tracing-appender",
"tracing-subscriber",
"windows-sys 0.61.2",
]
[[package]]
+2 -30
Переглянути файл
@@ -285,14 +285,6 @@ fn texts(e: &Element, path: &str, item: &str) -> Vec<String> {
e.list(path, item).iter().map(|m| m.text.trim().to_owned()).filter(|m| !m.is_empty()).collect()
}
/// Child modules of a project or profile: `<modules>` (model 4.0.0) plus `<subprojects>`,
/// which Maven 4 (model 4.1.0) uses instead.
fn module_names(e: &Element) -> Vec<String> {
let mut names = texts(e, "modules", "module");
names.extend(texts(e, "subprojects", "subproject"));
names
}
fn read_build(e: &Element, plugins: &mut Vec<RawPlugin>, managed: &mut Vec<RawPlugin>) {
plugins.extend(e.list("build/plugins", "plugin").into_iter().filter_map(read_plugin));
managed.extend(e.list("build/pluginManagement/plugins", "plugin").into_iter().filter_map(read_plugin));
@@ -316,7 +308,7 @@ fn read_raw(project: &Element) -> RawPom {
name: project.text_of("name"),
parent,
properties: read_properties(project.child("properties")),
modules: module_names(project),
modules: texts(project, "modules", "module"),
deps: project.list("dependencies", "dependency").into_iter().filter_map(read_dep).collect(),
managed: project
.list("dependencyManagement/dependencies", "dependency")
@@ -337,7 +329,7 @@ fn read_raw(project: &Element) -> RawPom {
let mut profile = RawProfile {
id: p.text_of("id").unwrap_or_else(|| "default".into()),
active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"),
modules: module_names(p),
modules: texts(p, "modules", "module"),
properties: read_properties(p.child("properties")),
deps: p.list("dependencies", "dependency").into_iter().filter_map(read_dep).collect(),
..RawProfile::default()
@@ -1284,26 +1276,6 @@ mod tests {
</profiles>
</project>"#;
#[test]
fn maven_4_subprojects_are_modules() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"pom.xml",
r#"<project xmlns="http://maven.apache.org/POM/4.1.0"><modelVersion>4.1.0</modelVersion>
<groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version><packaging>pom</packaging>
<subprojects><subproject>core</subproject></subprojects>
<profiles><profile><id>extra</id><subprojects><subproject>extra</subproject></subprojects></profile></profiles>
</project>"#,
);
write(root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(root, "extra/pom.xml", "<project><artifactId>extra</artifactId></project>");
let model = load_with_repo(root, None);
assert_eq!(model.projects[0].modules, ["core/pom.xml"]);
assert!(model.projects.iter().any(|p| p.pom == "core/pom.xml" && p.aggregated));
}
#[test]
fn multi_module_parent_properties_and_managed_versions() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -19,4 +19,4 @@ tokio-util.workspace = true
tempfile.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_Security", "Win32_System_Registry", "Win32_Foundation"] }
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_System_Registry", "Win32_Foundation"] }
+4 -119
Переглянути файл
@@ -13,10 +13,7 @@
//! they fork get them too (`spring-boot:run`, Surefire, `bootRun`, test workers).
//! Each JVM then reports "Picked up JAVA_TOOL_OPTIONS: …" on stderr (which a build tool
//! may copy to its stdout); that line is hidden again ([`NoticeFilter`]). `file.encoding` is left alone there: it would change
//! how a build reads sources that declare no encoding. The application JVMs a build
//! forks get `file.encoding=UTF-8` for a UTF-8 console instead, through the build's own
//! options: `-Dspring-boot.run.jvmArguments` for Maven `spring-boot:run`, an init script
//! ([`GRADLE_FILE_ENCODING_SCRIPT`]) for Gradle `JavaExec` tasks (`bootRun`, `run`).
//! how a build reads sources that declare no encoding.
//! - Python: `PYTHONIOENCODING`.
use std::collections::BTreeMap;
@@ -78,34 +75,16 @@ fn encoding_for_code_page(cp: u32) -> Option<&'static encoding_rs::Encoding> {
const STD_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
const FILE_ENCODING: &str = "file.encoding";
const TOOL_OPTIONS: &str = "JAVA_TOOL_OPTIONS";
const SPRING_BOOT_JVM_ARGS: &str = "-Dspring-boot.run.jvmArguments=";
/// Build tools and launcher scripts that run on (and may fork) JVMs.
const JVM_TOOLS: &[&str] = &["sbt", "ant", "kotlin", "kotlinc", "groovy", "scala", "jbang"];
const MAVEN: &[&str] = &["mvn", "mvnw", "mvnd"];
const GRADLE: &[&str] = &["gradle", "gradlew"];
/// Gradle init script giving the `JavaExec` tasks (`bootRun`, `run`, custom ones) a UTF-8
/// default charset before the build configures them, so the build can override it.
/// Gradle's own JVM and the compiler's source encoding are untouched.
pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
// Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8.
allprojects {
tasks.withType(JavaExec).configureEach {
defaultCharacterEncoding = 'UTF-8'
}
}
";
const JVM_TOOLS: &[&str] =
&["mvn", "mvnw", "mvnd", "gradle", "gradlew", "sbt", "ant", "kotlin", "kotlinc", "groovy", "scala", "jbang"];
/// What a launch needs: `-D` options to put first on a `java` command line,
/// environment variables to set, and the notice line its JVMs print because of them.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct EncodingFix {
pub java_args: Vec<String>,
/// The build tool's arguments, rewritten to pass options to the JVM it forks.
pub args: Option<Vec<String>>,
/// Gradle: pass [`GRADLE_FILE_ENCODING_SCRIPT`] with `--init-script`.
pub gradle_init_script: bool,
pub env: Vec<(String, String)>,
/// "Picked up JAVA_TOOL_OPTIONS: …" for a variable set here alone, to drop from the output.
pub notice: Option<String>,
@@ -137,8 +116,6 @@ fn options(properties: &[&str], encoding: &str) -> Vec<String> {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Java,
Maven,
Gradle,
JvmTool,
Python,
Other,
@@ -148,10 +125,6 @@ fn kind(program: &str) -> Kind {
let name = program_name(program);
if name == "java" || name == "javaw" {
Kind::Java
} else if MAVEN.contains(&name.as_str()) {
Kind::Maven
} else if GRADLE.contains(&name.as_str()) {
Kind::Gradle
} else if JVM_TOOLS.contains(&name.as_str()) {
Kind::JvmTool
} else if is_python(&name) {
@@ -220,17 +193,7 @@ fn fix_kind(
out.java_args.push(format!("-D{FILE_ENCODING}=UTF-8"));
}
}
(Kind::Java | Kind::Maven | Kind::Gradle | Kind::JvmTool, _) => {
if let Some(args) = args
&& is_utf8(encoding)
&& !sets(&tool_options, &[FILE_ENCODING])
{
match kind {
Kind::Maven => out.args = spring_boot_file_encoding(args),
Kind::Gradle => out.gradle_init_script = true,
_ => {}
}
}
(Kind::Java | Kind::JvmTool, _) => {
if !sets(&tool_options, STD_PROPERTIES) {
let added = options(STD_PROPERTIES, encoding).join(" ");
let value = match tool_options.trim() {
@@ -251,26 +214,6 @@ fn fix_kind(
out
}
fn spring_boot_file_encoding(args: &[String]) -> Option<Vec<String>> {
if !args.iter().any(|a| a == "spring-boot:run" || (a.contains(":spring-boot-maven-plugin:") && a.ends_with(":run")))
{
return None;
}
let option = format!("-D{FILE_ENCODING}=UTF-8");
let mut out = args.to_vec();
match out.iter_mut().rfind(|a| a.starts_with(SPRING_BOOT_JVM_ARGS)) {
Some(own) if sets(own, &[FILE_ENCODING]) => return None,
Some(own) => {
if own.len() > SPRING_BOOT_JVM_ARGS.len() {
own.push(' ');
}
own.push_str(&option);
}
None => out.push(format!("{SPRING_BOOT_JVM_ARGS}{option}")),
}
Some(out)
}
/// `vmArgs` of a launch by java-debug, which decodes the JVM's output as `encoding`
/// (its launch attribute, UTF-8 when unset). java-debug sets `file.encoding` only
/// when that attribute is nonblank; use the same defaults and user overrides as [`fix`].
@@ -492,64 +435,6 @@ mod tests {
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
}
#[test]
fn spring_boot_run_forks_get_a_utf8_default_charset() {
let boot = |args: &[&str], env: &[(&str, &str)]| run("mvn.cmd", args, env, "UTF-8", true).args;
let utf8 = "-Dspring-boot.run.jvmArguments=-Dfile.encoding=UTF-8";
assert_eq!(boot(&["spring-boot:run"], &[]).unwrap(), ["spring-boot:run", utf8]);
let plugin = "org.springframework.boot:spring-boot-maven-plugin:3.2.0:run";
assert_eq!(boot(&["-pl", "app", plugin], &[]).unwrap(), ["-pl", "app", plugin, utf8]);
// The user's VM options are kept; their own `file.encoding` wins.
assert_eq!(
boot(&["spring-boot:run", "-Dspring-boot.run.jvmArguments=-Xmx1g \"-Da=b c\""], &[]).unwrap(),
["spring-boot:run", "-Dspring-boot.run.jvmArguments=-Xmx1g \"-Da=b c\" -Dfile.encoding=UTF-8"]
);
assert_eq!(boot(&["spring-boot:run", "-Dspring-boot.run.jvmArguments="], &[]).unwrap()[1], utf8);
assert!(boot(&["spring-boot:run", "-Dspring-boot.run.jvmArguments=-Dfile.encoding=GBK"], &[]).is_none());
assert!(boot(&["spring-boot:run"], &[(TOOL_OPTIONS, "-Dfile.encoding=GBK")]).is_none());
// Other goals and tools, other consoles, and other platforms are left alone.
assert!(boot(&["package"], &[]).is_none());
assert!(run("mvn", &["spring-boot:run"], &[], "GBK", true).args.is_none());
assert!(run("mvn", &["spring-boot:run"], &[], "UTF-8", false).args.is_none());
}
#[test]
fn forked_application_jvms_get_a_utf8_default_charset() {
// Reported: a Spring Boot app run by the build on Chinese Windows (JDK 8–17, GBK default).
for (tool, args) in [
("C:\\p\\gradlew.bat", &["bootRun"][..]),
("gradle", &[":app:run"]),
("mvnw.cmd", &["spring-boot:run"]),
("mvnd", &["org.springframework.boot:spring-boot-maven-plugin:2.7.18:run"]),
] {
let f = run(tool, args, &[], "UTF-8", true);
let gradle = tool.contains("gradle");
assert_eq!(f.gradle_init_script, gradle, "{tool}");
assert_eq!(f.args.is_some(), !gradle, "{tool}");
// The build tool's own JVM keeps its default charset.
assert!(!tool_env(&f).unwrap().contains("file.encoding"), "{tool}");
// The user's choice, a GBK console and other platforms are left alone.
let own = run(tool, args, &[(TOOL_OPTIONS, "-Dfile.encoding=GBK")], "UTF-8", true);
assert!(!own.gradle_init_script && own.args.is_none(), "{tool}");
let gbk = run(tool, args, &[], "GBK", true);
assert!(!gbk.gradle_init_script && gbk.args.is_none(), "{tool}");
assert_eq!(run(tool, args, &[], "UTF-8", false), EncodingFix::default(), "{tool}");
}
// Shell command lines can't take arguments; other JVM tools fork no application.
assert!(!fix_command_line("gradlew bootRun", &BTreeMap::new(), |_| None, "UTF-8", true).gradle_init_script);
let sbt = run("sbt", &["run"], &[], "UTF-8", true);
assert!(!sbt.gradle_init_script && sbt.args.is_none());
}
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}");
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
}
#[test]
fn shell_command_lines_get_variables_from_their_first_word() {
let line = |l: &str| fix_command_line(l, &BTreeMap::new(), |_| None, "UTF-8", true);
+38 -133
Переглянути файл
@@ -245,7 +245,10 @@ pub fn find_executable(name: &str, search: &OsStr) -> Option<std::path::PathBuf>
#[cfg(windows)]
pub fn user_path() -> Option<OsString> {
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{HKEY, HKEY_CURRENT_USER, KEY_READ, RegCloseKey, RegOpenKeyExW};
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_READ, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, RegCloseKey, RegGetValueW,
RegOpenKeyExW,
};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
@@ -256,53 +259,45 @@ pub fn user_path() -> Option<OsString> {
if RegOpenKeyExW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), 0, KEY_READ, &mut key) != ERROR_SUCCESS {
return None;
}
let value = read_registry_string(key, &wide("Path"));
let read = || {
// Only `Path`; `REG_EXPAND_SZ` is accepted so `%USERPROFILE%\…` entries expand.
let mut kind = 0u32;
let mut len = 0u32;
let name = wide("Path");
let status = RegGetValueW(
key,
std::ptr::null(),
name.as_ptr(),
RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ,
&mut kind,
std::ptr::null_mut(),
&mut len,
);
if status != ERROR_SUCCESS || len == 0 {
return None;
}
let mut buf = vec![0u16; (len as usize).div_ceil(2)];
let status = RegGetValueW(
key,
std::ptr::null(),
name.as_ptr(),
RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ,
&mut kind,
buf.as_mut_ptr() as *mut _,
&mut len,
);
if status != ERROR_SUCCESS {
return None;
}
let text = String::from_utf16_lossy(&buf);
Some(text.trim_end_matches('\0').to_owned())
};
let value = read();
RegCloseKey(key);
value.filter(|v| !v.trim().is_empty()).map(OsString::from)
}
}
/// The string of value `name` under open `key`: `REG_SZ` as-is, `REG_EXPAND_SZ` expanded
/// against the current environment. `None` when the value is missing or unreadable.
///
/// A `REG_EXPAND_SZ` value's first size query reports the unexpanded size, so a value
/// that grows when expanded is re-read at the size the failed call reports. And the
/// terminating NUL can leak into the read buffer with a stray UTF-16 unit behind it —
/// seen with a `REG_EXPAND_SZ` user `Path`, where it made `env::set_var("PATH", …)`
/// panic with "strings passed to WinAPI cannot contain NULs" — so the text is cut at
/// the first NUL, not just stripped of trailing ones.
#[cfg(windows)]
fn read_registry_string(key: windows_sys::Win32::System::Registry::HKEY, name: &[u16]) -> Option<String> {
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, ERROR_SUCCESS};
use windows_sys::Win32::System::Registry::{RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, RegGetValueW};
const FLAGS: u32 = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ;
let mut kind = 0u32;
let mut len = 0u32;
// SAFETY: `name` is NUL-terminated and the size query writes only `kind` and `len`.
let status =
unsafe { RegGetValueW(key, std::ptr::null(), name.as_ptr(), FLAGS, &mut kind, std::ptr::null_mut(), &mut len) };
if status != ERROR_SUCCESS || len == 0 {
return None;
}
let buf = loop {
let mut buf = vec![0u16; len as usize / 2 + 1];
// SAFETY: as above; the buffer holds at least the `len` bytes the call may write.
let status = unsafe {
RegGetValueW(key, std::ptr::null(), name.as_ptr(), FLAGS, &mut kind, buf.as_mut_ptr() as *mut _, &mut len)
};
if status == ERROR_SUCCESS {
break buf;
}
if status != ERROR_MORE_DATA || len == 0 {
return None;
}
};
let text = String::from_utf16_lossy(&buf);
let end = text.find('\0').unwrap_or(text.len());
Some(text[..end].to_owned())
}
/// The user's own `PATH` entries; `None` outside Windows (see the Windows impl).
#[cfg(not(windows))]
pub fn user_path() -> Option<OsString> {
@@ -339,96 +334,6 @@ mod tests {
}
}
#[cfg(windows)]
#[test]
fn registry_strings_expand_and_stay_terminator_free() {
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_EXPAND_SZ, REG_SZ, RegCloseKey, RegCreateKeyExW,
RegDeleteTreeW, RegSetValueExW,
};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
struct TestState {
key: HKEY,
name: String,
variable: String,
previous: Option<OsString>,
}
impl Drop for TestState {
fn drop(&mut self) {
// SAFETY: the key belongs to this test; Windows environment mutation is safe.
unsafe {
RegCloseKey(self.key);
RegDeleteTreeW(HKEY_CURRENT_USER, wide(&self.name).as_ptr());
match &self.previous {
Some(value) => std::env::set_var(&self.variable, value),
None => std::env::remove_var(&self.variable),
}
}
}
}
let name = format!("Software\\ai.l0ng.openidea.registry-read-test-{}", std::process::id());
let variable = format!("OPENIDEA_TEST_REGVAR_{}", std::process::id());
let long = "x".repeat(600);
let mut key: HKEY = std::ptr::null_mut();
let opened = unsafe {
RegCreateKeyExW(
HKEY_CURRENT_USER,
wide(&name).as_ptr(),
0,
std::ptr::null(),
0,
KEY_READ | KEY_WRITE,
std::ptr::null(),
&mut key,
std::ptr::null_mut(),
)
};
assert_eq!(opened, ERROR_SUCCESS, "the test key must be creatable under HKCU\\Software");
let _cleanup = TestState { key, name, previous: std::env::var_os(&variable), variable: variable.clone() };
// SAFETY: Windows permits environment mutation. No other test uses this process-specific name.
unsafe { std::env::set_var(&variable, &long) };
let set = |value: &str, kind: u32, data: &[u16]| {
// SAFETY: `key` is open for writing and `data` holds `data.len() * 2` bytes.
assert_eq!(
unsafe {
RegSetValueExW(
key,
wide(value).as_ptr(),
0,
kind,
data.as_ptr() as *const _,
(data.len() * 2) as u32,
)
},
ERROR_SUCCESS
);
};
let read = |value: &str| read_registry_string(key, &wide(value));
set("Plain", REG_SZ, &wide("plain"));
set("Expand", REG_EXPAND_SZ, &wide(&format!("%{variable}%\\bin")));
set("ExpandLong", REG_EXPAND_SZ, &wide(&format!("%{variable}%")));
// Reproduce the reported interior terminator followed by a stale UTF-16 unit.
set("TrailingGarbage", REG_SZ, &wide("C:\\Zed\\bin\0n"));
set("ExpandTrailingGarbage", REG_EXPAND_SZ, &wide(&format!("%{variable}%\\bin\0n")));
set("Empty", REG_SZ, &wide(""));
let plain = read("Plain");
let expand = read("Expand");
let expand_long = read("ExpandLong");
assert_eq!(plain.as_deref(), Some("plain"));
assert_eq!(expand.as_deref(), Some(format!("{long}\\bin")).as_deref());
// Longer than its unexpanded form: needs the re-read at the expanded size.
assert_eq!(expand_long.as_deref(), Some(long.as_str()));
assert_eq!(read("TrailingGarbage").as_deref(), Some("C:\\Zed\\bin"));
assert_eq!(read("ExpandTrailingGarbage").as_deref(), Some(format!("{long}\\bin")).as_deref());
assert_eq!(read("Empty").as_deref(), Some(""));
assert_eq!(read("Missing"), None);
}
#[test]
fn append_path_entries_keeps_the_order_and_adds_what_is_missing() {
let join = |dirs: &[&str]| std::env::join_paths(dirs).unwrap();
-4
Переглянути файл
@@ -51,11 +51,7 @@ uuid.workspace = true
tempfile.workspace = true
[dev-dependencies]
ide-ssh = { workspace = true, features = ["testing"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
[target.'cfg(unix)'.dependencies]
rustix = { version = "1.1", features = ["fs", "process"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
+14 -21
Переглянути файл
@@ -133,29 +133,22 @@ pub async fn build_sync(
host.end_request(request);
let model = result??;
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
&& let Some(maven) = &model.maven
{
bridge.configure_maven(offline, bridge_profiles);
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436).
if let Some(bridge) = &project.kotlin_bridge {
bridge.configure_maven(offline, bridge_profiles);
}
let lsp = project.lsp.clone();
let uris = maven.projects.iter().map(|p| ide_lsp::path_to_uri_string(&project.root.join(&p.pom))).collect();
tokio::spawn(async move {
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
});
}
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436). The same
// holds for Gradle: it reuses its cached classpath on restart, so a
// dependency added to `build.gradle` stays unresolved until told to sync.
let build_files: Vec<String> = match tool {
BuildTool::Maven => model.maven.iter().flat_map(|m| m.projects.iter().map(|p| p.pom.clone())).collect(),
BuildTool::Gradle => {
model.gradle.iter().flat_map(|g| g.projects.iter().filter_map(|p| p.build_file.clone())).collect()
}
};
let lsp = project.lsp.clone();
let uris = build_files.iter().map(|f| ide_lsp::path_to_uri_string(&project.root.join(f))).collect();
tokio::spawn(async move {
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
});
Ok(model)
}
-1
Переглянути файл
@@ -91,7 +91,6 @@ mod tests {
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
-20
Переглянути файл
@@ -5,23 +5,6 @@ use crate::rpc::Dispatcher;
use ide_core::{IdeError, IdeResult};
use ide_run::RunConfig;
pub async fn run_dotnet_resolve(host: &Host, window: &str, config: RunConfig, debug: bool) -> IdeResult<RunConfig> {
host.require_trust(window)?;
if !matches!(config.kind.as_str(), "dotnet" | "dotnet-test")
|| config.extras.target.as_ref().is_some_and(|s| !s.is_empty())
{
return Err(IdeError::invalid(".NET Project requires the local machine"));
}
let project = host.project(window)?;
let mut config = host.blocking(move || ide_run::dotnet::resolve(&project.root, config)).await?;
if debug {
let root = host.project(window)?.root.clone();
let target = ide_run::dotnet::target_path(&root, &config).await?;
config.extras.params.insert("targetPath".into(), target);
}
Ok(config)
}
fn application_cache(project: &crate::project::Project, id: &str) -> std::path::PathBuf {
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
@@ -223,9 +206,6 @@ pub async fn run_tomcat_update(host: &Host, window: &str, config: RunConfig, mod
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("run_dotnet_resolve", |c| async move {
run_dotnet_resolve(&c.host, &c.window, c.arg("config")?, c.arg("debug")?).await
});
d.add("run_application_build", |c| async move {
run_application_build(&c.host, &c.window, c.arg("config")?, c.arg("module")?).await
});
-46
Переглянути файл
@@ -3,21 +3,6 @@ use crate::Host;
use ide_core::{IdeResult, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
mod images;
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
pub async fn store_image(host: &Host, id: TerminalId, data: Vec<u8>, mime: String) -> IdeResult<String> {
if data.len() > MAX_IMAGE_BYTES {
return Err(ide_core::IdeError::invalid("image is too large to paste (limit 20 MB)"));
}
if !host.terminals.contains(id) {
return Err(ide_core::IdeError::invalid("terminal session not found"));
}
let data_dir = host.data_dir.clone();
host.blocking(move || images::store(&data_dir, &data, &mime)).await
}
pub fn spawn(
host: &Host,
window: &str,
@@ -62,34 +47,3 @@ pub fn kill(host: &Host, id: TerminalId) -> IdeResult<()> {
pub fn is_busy(host: &Host, id: TerminalId) -> IdeResult<bool> {
host.terminals.is_busy(id)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
use ide_core::{NullSink, error::ErrorKind};
use std::sync::Arc;
#[tokio::test]
async fn image_size_limit_is_checked_before_storage() {
let root = tempfile::tempdir().unwrap();
let host = Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: root.path().join("data"),
local_data_dir: root.path().join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let id = TerminalId::next();
let error = store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert_eq!(error.message, "image is too large to paste (limit 20 MB)");
let error = store_image(&host, id, vec![0; MAX_IMAGE_BYTES], "image/png".into()).await.unwrap_err();
assert_eq!(error.message, "terminal session not found");
assert!(!host.data_dir.join("terminal-images").exists());
}
}
-220
Переглянути файл
@@ -1,220 +0,0 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
#[cfg(unix)]
mod unix {
use super::*;
use rustix::fs::{self, AtFlags, Dir, Mode, OFlags};
use std::fs::File;
use std::io::{self, Write};
use std::os::unix::fs::MetadataExt;
use std::time::{Duration, SystemTime};
const LIFETIME: Duration = Duration::from_secs(24 * 60 * 60);
const DIRECTORY: &str = "terminal-images";
fn extension(mime: &str) -> IdeResult<&str> {
match mime {
"image/png" => Ok("png"),
"image/jpeg" => Ok("jpg"),
"image/gif" => Ok("gif"),
"image/webp" => Ok("webp"),
"image/bmp" => Ok("bmp"),
"image/svg+xml" => Ok("svg"),
"image/tiff" => Ok("tiff"),
"image/x-icon" => Ok("ico"),
_ => Err(IdeError::invalid("unsupported image type")),
}
}
fn open_directory(data_dir: &Path) -> io::Result<File> {
if !data_dir.is_absolute() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "data directory must be absolute"));
}
// The configured data directory and its ancestors are the host's trust boundary.
let parent =
fs::open(data_dir, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?;
match fs::mkdirat(&parent, DIRECTORY, Mode::from_bits_truncate(0o700)) {
Ok(()) | Err(rustix::io::Errno::EXIST) => (),
Err(e) => return Err(e.into()),
}
let dir: File = fs::openat(
&parent,
DIRECTORY,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?
.into();
let meta = dir.metadata()?;
if meta.uid() != rustix::process::geteuid().as_raw() || meta.mode() & 0o7777 != 0o700 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"terminal image directory is not private or owned by the current user",
));
}
Ok(dir)
}
fn owned_name(name: &str) -> bool {
let name = name.strip_prefix(".partial-").unwrap_or(name);
let Some((id, ext)) = name.strip_prefix("image-").and_then(|s| s.split_once('.')) else { return false };
id.len() == 32
&& id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
&& matches!(ext, "png" | "jpg" | "gif" | "webp" | "bmp" | "svg" | "tiff" | "ico")
}
fn cleanup(dir: &File, now: SystemTime) -> io::Result<()> {
for entry in Dir::read_from(dir)? {
let entry = entry?;
let name = entry.file_name();
if !name.to_str().is_ok_and(owned_name) {
continue;
}
// Never follow symlinks; opening nonblocking avoids hanging on an unexpected FIFO.
let fd = match fs::openat(
dir,
name,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(_) => continue,
};
let file = File::from(fd);
let meta = file.metadata()?;
if meta.is_file()
&& meta.uid() == rustix::process::geteuid().as_raw()
&& meta
.modified()
.ok()
.and_then(|time| now.duration_since(time).ok())
.is_some_and(|age| age >= LIFETIME)
{
match fs::unlinkat(dir, name, AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => (),
Err(error) => return Err(error.into()),
}
}
}
Ok(())
}
fn store_with(
data_dir: &Path,
data: &[u8],
mime: &str,
now: SystemTime,
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
) -> IdeResult<String> {
let ext = extension(mime)?;
let dir = open_directory(data_dir)?;
cleanup(&dir, now)?;
let name = format!("image-{}.{}", uuid::Uuid::new_v4().simple(), ext);
let temporary = format!(".partial-{name}");
let fd = fs::openat(
&dir,
temporary.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::from_bits_truncate(0o600),
)
.map_err(io::Error::from)?;
let mut file = File::from(fd);
if let Err(error) = write(&mut file, data) {
let _ = fs::unlinkat(&dir, temporary.as_str(), AtFlags::empty());
return Err(error.into());
}
if let Err(error) = fs::linkat(&dir, temporary.as_str(), &dir, name.as_str(), AtFlags::empty()) {
let _ = fs::unlinkat(&dir, temporary.as_str(), AtFlags::empty());
return Err(io::Error::from(error).into());
}
let _ = fs::unlinkat(&dir, temporary.as_str(), AtFlags::empty());
Ok(data_dir.join(DIRECTORY).join(name).to_string_lossy().into_owned())
}
pub(in crate::ops::term) fn store(data_dir: &Path, data: &[u8], mime: &str) -> IdeResult<String> {
store_with(data_dir, data, mime, SystemTime::now(), |file, bytes| file.write_all(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
fn stores_bytes_with_private_modes_and_unpredictable_names() {
let root = tempfile::tempdir().unwrap();
let first = store(root.path(), b"image bytes", "image/png").unwrap();
let second = store(root.path(), b"other", "image/jpeg").unwrap();
assert_ne!(first, second);
assert_eq!(fs::read(&first).unwrap(), b"image bytes");
assert_eq!(fs::metadata(&first).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(fs::metadata(root.path().join(DIRECTORY)).unwrap().permissions().mode() & 0o777, 0o700);
assert!(owned_name(Path::new(&first).file_name().unwrap().to_str().unwrap()));
}
#[test]
fn expiry_only_removes_owned_regular_files_at_boundary() {
let root = tempfile::tempdir().unwrap();
let dir = open_directory(root.path()).unwrap();
let path = root.path().join(DIRECTORY);
let now = SystemTime::now();
let names = [
"image-00000000000000000000000000000001.png",
"image-00000000000000000000000000000002.png",
"image-00000000000000000000000000000003.png",
"unrelated.png",
];
for (name, time) in names.iter().zip([
now - LIFETIME,
now - LIFETIME + Duration::from_secs(1),
now + Duration::from_secs(1),
now - LIFETIME,
]) {
let file = File::create(path.join(name)).unwrap();
file.set_times(fs::FileTimes::new().set_modified(time)).unwrap();
}
let link = path.join("image-00000000000000000000000000000004.png");
symlink(path.join(names[0]), &link).unwrap();
cleanup(&dir, now).unwrap();
assert!(!path.join(names[0]).exists());
for name in &names[1..] {
assert!(path.join(name).exists());
}
assert!(fs::symlink_metadata(link).unwrap().file_type().is_symlink());
}
#[test]
fn rejects_symlink_and_insecure_directory() {
let root = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let target = root.path().join(DIRECTORY);
symlink(outside.path(), &target).unwrap();
assert!(store(root.path(), b"x", "image/png").is_err());
fs::remove_file(&target).unwrap();
fs::create_dir(&target).unwrap();
fs::set_permissions(&target, fs::Permissions::from_mode(0o755)).unwrap();
assert!(store(root.path(), b"x", "image/png").is_err());
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
}
#[test]
fn failed_write_removes_partial_file() {
let root = tempfile::tempdir().unwrap();
let result = store_with(root.path(), b"partial", "image/png", SystemTime::now(), |file, bytes| {
file.write_all(bytes)?;
Err(io::Error::other("simulated failure"))
});
assert!(result.is_err());
assert_eq!(fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), 0);
}
}
}
#[cfg(unix)]
pub(super) use unix::store;
#[cfg(not(unix))]
pub(super) fn store(_data_dir: &Path, _data: &[u8], _mime: &str) -> IdeResult<String> {
Err(IdeError::internal("private terminal image storage is unsupported on this platform"))
}
-3
Переглянути файл
@@ -231,9 +231,6 @@ impl Dispatcher {
let on_output = c.channel("onOutput")?;
ops::term::spawn(&c.host, &c.window, c.arg("options")?, on_output)
})
.add("term_store_image", |c| async move {
ops::term::store_image(&c.host, c.arg("id")?, c.arg("data")?, c.arg("mime")?).await
})
.add("term_write", |c| async move { ops::term::write(&c.host, c.arg("id")?, &c.arg::<String>("data")?) })
.add("term_resize", |c| async move { ops::term::resize(&c.host, c.arg("id")?, c.arg("cols")?, c.arg("rows")?) })
.add("term_kill", |c| async move { ops::term::kill(&c.host, c.arg("id")?) })
-2
Переглянути файл
@@ -222,7 +222,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "index_status"
| "jvm_file_presentations"
| "deploy_coverage"
| "deploy_test_connection"
| "find_files"
| "find_symbols"
| "mark_recent"
@@ -244,7 +243,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "remote_current"
| "remote_disconnect"
| "remote_connect"
| "remote_bootstrap_list"
| "remote_list"
| "remote_open"
| "remote_of"
-47
Переглянути файл
@@ -1,47 +0,0 @@
#![cfg(unix)]
use ide_core::{NullSink, TerminalId};
use ide_host::{Host, HostConfig, ops};
use ide_terminal::TerminalOptions;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn storage_requires_a_registered_terminal() {
let root = tempfile::tempdir().unwrap();
let data_dir = root.path().join("data");
std::fs::create_dir(&data_dir).unwrap();
let host = Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: data_dir.clone(),
local_data_dir: data_dir.clone(),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert!(ops::term::store_image(&host, TerminalId::next(), vec![1], "image/png".into()).await.is_err());
assert!(!data_dir.join("terminal-images").exists());
let terminal = host
.terminals
.spawn(
TerminalOptions {
cwd: root.path().into(),
shell: Some("/bin/sh".into()),
args: vec![],
env: Default::default(),
cols: 80,
rows: 24,
shell_integration: false,
},
Arc::new(NullSink),
Box::new(|_| {}),
)
.unwrap();
let path = ops::term::store_image(&host, terminal.id, vec![1, 2, 3], "image/png".into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 1);
}
-60
Переглянути файл
@@ -56,8 +56,6 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"db_console_path",
"db_export_file",
"vcs_write_patch",
"remote_bootstrap_list",
"deploy_test_connection",
] {
assert!(ide_host::trust::restricted_command_allowed(command), "{command}");
for window in ["main", "welcome"] {
@@ -77,15 +75,6 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"vcs_git_version",
"docker_compose_op",
"db_execute",
"remote_delete",
"remote_mkdir",
"remote_rename",
"remote_import_local",
"remote_bootstrap_exec",
"deploy_upload",
"deploy_download",
"deploy_delete_remote",
"deploy_sync",
"unknown_command",
] {
assert!(!ide_host::trust::restricted_command_allowed(command), "{command}");
@@ -120,55 +109,6 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
host.shutdown().await;
}
#[tokio::test]
async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
use ide_core::remote_settings::{SshAuth, SshConfiguration};
use ide_ssh::{FsConnection, SshFiles, SshManager};
let tmp = tempfile::tempdir().unwrap();
let server_root = tmp.path().join("server");
std::fs::create_dir_all(server_root.join("projects/demo")).unwrap();
std::fs::write(server_root.join("projects/README.md"), "remote file").unwrap();
let port = ide_ssh::testing::sshd(server_root, Arc::new(|cmd| panic!("unexpected SSH exec: {cmd}"))).await;
let ssh = Arc::new(SshManager::with_files(
tmp.path().join("secrets.json"),
SshFiles { known_hosts: tmp.path().join("known_hosts"), config: None },
));
ssh.set_configs(vec![SshConfiguration {
id: "selected-host".into(),
host: "127.0.0.1".into(),
port: Some(port),
user: "dev".into(),
auth: SshAuth::Password,
..Default::default()
}]);
ssh.set_secret("selected-host", Some("secret".into()), false);
assert!(ssh.session("selected-host").await.is_err());
ssh.trust_host("selected-host").await.unwrap();
let mut host = host(&tmp.path().join("app"), false);
let state = Arc::get_mut(&mut host).unwrap();
state.ssh = ssh;
state.remote = Arc::new(ide_remote::RemoteService::new(state.ssh.clone(), tmp.path().join("cache")));
assert!(host.project("welcome").is_err());
host.authorize_command("welcome", "remote_bootstrap_list").unwrap();
let connection = FsConnection::Sftp { ssh: "selected-host".into() };
let entries = host.remote.list(&connection, "/projects").await.unwrap();
assert!(entries.iter().any(|e| e.path == "/projects/demo" && e.is_dir));
assert!(entries.iter().any(|e| e.name == "README.md" && !e.is_dir));
assert!(host.remote.list(&connection, "/projects/demo").await.unwrap().is_empty());
host.authorize_command("welcome", "deploy_test_connection").unwrap();
host.remote.test_connection(&connection, "/projects").await.unwrap();
let local = tmp.path().join("local-deployment");
std::fs::create_dir(&local).unwrap();
ide_host::ops::deploy::deploy_test_connection(&host, FsConnection::Local, local.to_str().unwrap().into())
.await
.unwrap();
assert_eq!(std::fs::read_dir(local).unwrap().count(), 0, "write probe is cleaned up");
assert!(host.project("welcome").is_err());
host.shutdown().await;
}
#[test]
fn persists_user_decisions_locations_revocation_and_one_time_migration() {
let tmp = tempfile::tempdir().unwrap();
-2
Переглянути файл
@@ -4,7 +4,6 @@
//! Detection never fails: unreadable or malformed files simply contribute nothing.
pub(crate) mod cmake;
mod dotnet;
use crate::RunConfig;
use serde_json::Value as Json;
@@ -34,7 +33,6 @@ pub(crate) fn detect_with_profiles(
detect_go(root, &mut out);
detect_python(root, &mut out);
cmake::detect(root, profiles, &mut out);
dotnet::detect(root, &mut out);
detect_make(root, &mut out);
detect_just(root, &mut out);
detect_godot(root, &mut out);
-121
Переглянути файл
@@ -1,121 +0,0 @@
//! Runnable .NET projects and launch profiles, without a solution model.
use crate::{
RunConfig,
dotnet::{parse_project, profiles, solution_projects},
};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::Path,
};
pub(crate) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
let mut dirs = vec![root.to_path_buf()];
let mut projects = BTreeSet::new();
while let Some(dir) = dirs.pop() {
let Ok(entries) = fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
if !name.starts_with('.')
&& !matches!(
name.as_str(),
"bin" | "obj" | "node_modules" | "target" | "build" | "dist" | "vendor" | "packages"
)
{
dirs.push(path);
}
} else if entry.file_type().is_ok_and(|t| t.is_file()) {
match path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase().as_str() {
"csproj" => {
projects.insert(path);
}
"sln" | "slnx" => {
if let Ok(src) = fs::read_to_string(&path) {
for project in solution_projects(
&src,
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("slnx")),
) {
projects.insert(dir.join(project));
}
}
}
_ => {}
}
}
}
}
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.into());
let projects: BTreeSet<_> = projects.into_iter().filter_map(|p| dunce::canonicalize(p).ok()).collect();
for path in projects {
let Some(project) = fs::read_to_string(&path).ok().and_then(|s| parse_project(&s)) else { continue };
let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
let name = path.file_stem().unwrap_or_default().to_string_lossy();
let profiles = profiles(&path);
let mut params = BTreeMap::from([
("project".into(), rel.clone()),
("framework".into(), project.frameworks.first().cloned().unwrap_or_default()),
("frameworks".into(), project.frameworks.join(";")),
("profiles".into(), serde_json::to_string(&profiles).unwrap_or_default()),
("launchProfile".into(), String::new()),
("programArgs".into(), String::new()),
]);
if project.executable && !project.test {
out.push(detected(&rel, &name, "", params.clone(), false));
for profile in profiles.keys() {
params.insert("launchProfile".into(), profile.clone());
out.push(detected(&rel, &name, profile, params.clone(), false));
}
}
if project.test {
params.insert("launchProfile".into(), String::new());
out.push(detected(&rel, &name, "", params, true));
}
}
}
fn detected(project: &str, name: &str, profile: &str, params: BTreeMap<String, String>, test: bool) -> RunConfig {
let op = if test { "test" } else { "run" };
let mut config = super::config(
format!("dotnet:{project}:{op}:{profile}"),
if test {
format!("dotnet test ({name})")
} else if profile.is_empty() {
format!("{name} (.NET Project)")
} else {
format!("{name}: {profile}")
},
if test { "dotnet-test" } else { "dotnet" },
"dotnet",
&[],
);
config.args = command_args(&params, test);
config.is_test = test;
config.debug_adapter = (!test).then(|| "netcoredbg".into());
config.extras.params = params;
if !test {
config.extras.before_launch.push(crate::BeforeLaunchTask { kind: "dotnetBuild".into(), target: String::new() });
}
config
}
fn command_args(params: &BTreeMap<String, String>, test: bool) -> Vec<String> {
let mut args = if test {
vec!["test".into(), params.get("project").cloned().unwrap_or_default()]
} else {
vec!["run".into(), "--project".into(), params.get("project").cloned().unwrap_or_default()]
};
if let Some(framework) = params.get("framework").filter(|s| !s.is_empty()) {
args.extend(["--framework".into(), framework.clone()]);
}
if !test {
if let Some(profile) = params.get("launchProfile").filter(|s| !s.is_empty()) {
args.extend(["--launch-profile".into(), profile.clone()]);
} else {
args.push("--no-launch-profile".into());
}
}
args
}
-257
Переглянути файл
@@ -1,257 +0,0 @@
//! Lightweight .NET project discovery; MSBuild remains the authority for build outputs.
use crate::RunConfig;
use ide_core::{IdeError, IdeResult};
use quick_xml::{Reader, XmlVersion, events::Event};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Debug, Default, PartialEq)]
pub struct Project {
pub executable: bool,
pub frameworks: Vec<String>,
pub test: bool,
}
#[derive(Default)]
struct Element {
name: String,
attrs: BTreeMap<String, String>,
text: String,
conditional: bool,
}
fn elements(xml: &str) -> Option<Vec<Element>> {
let mut reader = Reader::from_str(xml);
let mut out: Vec<Element> = Vec::new();
let mut stack: Vec<usize> = Vec::new();
loop {
let event = reader.read_event().ok()?;
let empty = matches!(&event, Event::Empty(_));
match event {
Event::Start(tag) | Event::Empty(tag) => {
let attrs: BTreeMap<_, _> = tag
.attributes()
.map(|a| {
let a = a.ok()?;
Some((
a.key.as_ref().to_owned(),
a.normalized_value(XmlVersion::Implicit1_0).ok()?.into_owned(),
))
})
.collect::<Option<_>>()?;
let conditional = attrs.contains_key("Condition") || stack.last().is_some_and(|i| out[*i].conditional);
out.push(Element {
name: tag.local_name().as_ref().to_owned(),
attrs,
conditional,
..Default::default()
});
// Empty elements have no corresponding End event.
if !empty {
stack.push(out.len() - 1);
}
}
Event::End(_) => {
stack.pop()?;
}
Event::Text(text) => {
if let Some(i) = stack.last() {
out[*i].text.push_str(&text.xml_content(XmlVersion::Implicit1_0));
}
}
Event::CData(text) => {
if let Some(i) = stack.last() {
out[*i].text.push_str(text.as_ref());
}
}
Event::GeneralRef(reference) => {
let name = reference.as_ref();
let escaped = format!("&{name};");
if let Some(i) = stack.last() {
out[*i].text.push_str(&quick_xml::escape::unescape(&escaped).ok()?);
}
}
Event::Eof => return stack.is_empty().then_some(out),
_ => {}
}
}
}
pub fn parse_project(xml: &str) -> Option<Project> {
let tags = elements(xml)?;
if tags.first()?.name != "Project" {
return None;
}
let property = |name: &str| tags.iter().rev().find(|t| t.name == name && !t.conditional).map(|t| t.text.trim());
let web = tags.iter().any(|t| {
t.attrs
.get("Sdk")
.or_else(|| (t.name == "Sdk").then(|| t.attrs.get("Name")).flatten())
.is_some_and(|s| s.split(';').any(|sdk| sdk.split('/').next() == Some("Microsoft.NET.Sdk.Web")))
});
let executable = match property("OutputType") {
Some(output) => output.eq_ignore_ascii_case("exe") || output.eq_ignore_ascii_case("winexe"),
None => web,
};
let frameworks = property("TargetFramework")
.filter(|v| !v.is_empty())
.or_else(|| property("TargetFrameworks"))
.unwrap_or_default()
.split(';')
.map(str::trim)
.filter(|v| !v.is_empty())
.map(str::to_owned)
.collect();
let test = tags.iter().any(|t| {
t.name == "PackageReference"
&& t.attrs
.get("Include")
.or_else(|| t.attrs.get("Update"))
.is_some_and(|v| v.eq_ignore_ascii_case("Microsoft.NET.Test.Sdk"))
});
Some(Project { executable, frameworks, test })
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", default)]
pub struct Profile {
pub command_name: String,
pub command_line_args: String,
pub working_directory: String,
pub application_url: String,
pub environment_variables: BTreeMap<String, String>,
}
pub fn parse_profiles(json: &str) -> BTreeMap<String, Profile> {
let Ok(json) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(json)) else {
return BTreeMap::new();
};
json["profiles"]
.as_object()
.into_iter()
.flatten()
.filter_map(|(name, value)| {
let profile: Profile = serde_json::from_value(value.clone()).ok()?;
(profile.command_name == "Project").then(|| (name.clone(), profile))
})
.collect()
}
pub fn solution_projects(src: &str, xml: bool) -> Vec<PathBuf> {
let paths: Vec<String> = if xml {
elements(src)
.unwrap_or_default()
.into_iter()
.filter(|e| e.name == "Project")
.filter_map(|mut e| e.attrs.remove("Path"))
.collect()
} else {
src.lines()
.filter_map(|line| {
let line = line.trim();
if !line.starts_with("Project(") {
return None;
}
Some(line.split_once('=')?.1.split('"').nth(3)?.to_owned())
})
.collect()
};
paths
.into_iter()
.filter(|p| p.to_ascii_lowercase().ends_with(".csproj"))
.map(|p| PathBuf::from(p.replace('\\', "/")))
.collect()
}
pub(crate) fn profiles(project: &Path) -> BTreeMap<String, Profile> {
project
.parent()
.and_then(|p| fs::read_to_string(p.join("Properties/launchSettings.json")).ok())
.map(|s| parse_profiles(&s))
.unwrap_or_default()
}
/// Resolves the selected profile afresh so changing project/profile never reuses stale values.
pub fn resolve(root: &Path, mut config: RunConfig) -> IdeResult<RunConfig> {
let params = &config.extras.params;
let project = params
.get("project")
.filter(|s| !s.trim().is_empty())
.ok_or_else(|| IdeError::invalid("Select a .NET project"))?;
let project = dunce::canonicalize(root.join(project))?;
let dir = project.parent().ok_or_else(|| IdeError::invalid("Invalid .NET project path"))?;
let profile_name = params.get("launchProfile").cloned().unwrap_or_default();
let profile = if profile_name.is_empty() {
Profile::default()
} else {
profiles(&project).remove(&profile_name).ok_or_else(|| {
IdeError::invalid(format!(".NET launch profile '{profile_name}' is missing or is not a Project profile"))
})?
};
let mut env = profile.environment_variables;
if !profile.application_url.is_empty() {
env.insert("ASPNETCORE_URLS".into(), profile.application_url);
}
if !profile_name.is_empty() {
env.insert("DOTNET_LAUNCH_PROFILE".into(), profile_name);
}
env.extend(config.env);
config.env = env;
config.cwd = Some(
config
.cwd
.map(|p| root.join(&*p))
.unwrap_or_else(|| {
if profile.working_directory.is_empty() { dir.into() } else { dir.join(&profile.working_directory) }
})
.into(),
);
config.extras.params.insert("project".into(), project.to_string_lossy().into_owned());
config.extras.params.insert("profileArgs".into(), profile.command_line_args);
Ok(config)
}
/// Queries the evaluated output path, including AssemblyName, OutputPath and imported properties.
pub async fn target_path(root: &Path, config: &RunConfig) -> IdeResult<String> {
let params = &config.extras.params;
let project = params.get("project").ok_or_else(|| IdeError::invalid("Select a .NET project"))?;
let mut args = vec![
"msbuild".to_owned(),
root.join(project).to_string_lossy().into_owned(),
"-nologo".into(),
"-getProperty:TargetPath".into(),
"-p:Configuration=Debug".into(),
];
if let Some(framework) = params.get("framework").filter(|s| !s.is_empty()) {
args.push(format!("-p:TargetFramework={framework}"));
}
let mut command = std::process::Command::new(&config.command);
ide_core::process::host_env(&mut command);
command.args(args).current_dir(root);
if !config.extras.include_system_env {
command.env_clear();
} else {
command.envs(ide_core::process::shell_env());
}
command.envs(crate::resolved_env(root, config)?);
let mut command = tokio::process::Command::from(command);
command.kill_on_drop(true);
let output = tokio::time::timeout(std::time::Duration::from_secs(30), command.output())
.await
.map_err(|_| IdeError::unavailable(".NET output resolution timed out"))??;
if !output.status.success() {
return Err(IdeError::invalid(format!(
".NET output resolution failed: {}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)));
}
let target = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if target.is_empty() || !Path::new(&target).is_file() {
return Err(IdeError::invalid(".NET build output is missing; run dotnet build before debugging"));
}
Ok(target)
}
+3 -8
Переглянути файл
@@ -41,22 +41,17 @@ pub fn default_dir() -> PathBuf {
/// Writes the script for `jvm_args` under `dir` (named by its content, so launches share
/// it and nothing needs deleting) and returns its path.
pub fn write_init_script(dir: &Path, jvm_args: &[String]) -> std::io::Result<PathBuf> {
write_script(dir, "jvm-args", &init_script(jvm_args))
}
/// Writes the init script `text` under `dir` as `<prefix>-<hash>.init.gradle` (written
/// once per content, so launches share it) and returns its path.
pub fn write_script(dir: &Path, prefix: &str, text: &str) -> std::io::Result<PathBuf> {
use std::hash::{Hash, Hasher};
let text = init_script(jvm_args);
let mut h = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut h);
let file = dir.join(format!("{prefix}-{:016x}.init.gradle", h.finish()));
let file = dir.join(format!("jvm-args-{:016x}.init.gradle", h.finish()));
if std::fs::read_to_string(&file).is_ok_and(|t| t == text) {
return Ok(file);
}
std::fs::create_dir_all(dir)?;
let tmp = file.with_extension(format!("{}.tmp", std::process::id()));
std::fs::write(&tmp, text)?;
std::fs::write(&tmp, &text)?;
std::fs::rename(&tmp, &file).inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})?;
-1
Переглянути файл
@@ -2,7 +2,6 @@
mod config;
mod detect;
pub mod dotnet;
pub mod envfile;
pub mod go;
pub mod gradle_jvm;
+2 -15
Переглянути файл
@@ -195,21 +195,8 @@ fn match_console_encoding(
output_encoding::fix(&program, &inv.args, &env.vars, inherited, encoding, cfg!(windows))
};
env.vars.extend(fix.env);
let mut prepend = fix.java_args;
if fix.gradle_init_script {
match crate::gradle_jvm::write_script(
&crate::gradle_jvm::default_dir(),
"file-encoding",
output_encoding::GRADLE_FILE_ENCODING_SCRIPT,
) {
Ok(script) => prepend.extend(["--init-script".to_owned(), script.to_string_lossy().into_owned()]),
Err(e) => tracing::warn!("cannot write the Gradle file.encoding init script: {e}"),
}
}
let changed = fix.args.is_some() || !prepend.is_empty();
if changed && !inv.raw_args {
inv.args = fix.args.unwrap_or_else(|| std::mem::take(&mut inv.args));
inv.args.splice(0..0, prepend);
if !fix.java_args.is_empty() && !inv.raw_args {
inv.args.splice(0..0, fix.java_args);
let mut display = quote(config.command.trim());
for a in &inv.args {
display.push(' ');
-138
Переглянути файл
@@ -1,138 +0,0 @@
use ide_run::{
detect,
dotnet::{parse_profiles, parse_project, resolve, solution_projects},
};
use std::fs;
use std::path::PathBuf;
const CONSOLE: &str = r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net10.0; net9.0</TargetFrameworks></PropertyGroup></Project>"#;
const PROFILES: &str = r#"{
// Only Project profiles can be run with dotnet.
"profiles": {
"http": {"commandName":"Project", "applicationUrl":"http://localhost:5165", "commandLineArgs":"--message \"hello world\"", "workingDirectory":"work", "environmentVariables":{"DEMO":"profile"}},
"https": {"commandName":"Project", "environmentVariables":{"DEMO":"https"}},
"IIS Express": {"commandName":"IISExpress"},
"external": {"commandName":"Executable"},
"broken": {"commandName":"Project", "environmentVariables":7}
}
}"#;
fn write(root: &std::path::Path, file: &str, src: &str) {
let path = root.join(file);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, src).unwrap();
}
#[test]
fn project_properties_and_sdk_defaults() {
let p = parse_project(CONSOLE).unwrap();
assert!(p.executable && !p.test);
assert_eq!(p.frameworks, ["net10.0", "net9.0"]);
for (sdk, output, executable) in [
("Microsoft.NET.Sdk", "", false),
("Microsoft.NET.Sdk", "<OutputType>WinExe</OutputType>", true),
("Microsoft.NET.Sdk.Web", "", true),
("Microsoft.NET.Sdk.Web", "<OutputType>Library</OutputType>", false),
] {
let xml = format!(
r#"<Project Sdk="{sdk}"><PropertyGroup>{output}<TargetFramework>net10.0</TargetFramework></PropertyGroup></Project>"#
);
let p = parse_project(&xml).unwrap();
assert_eq!(p.executable, executable, "{xml}");
assert_eq!(p.frameworks, ["net10.0"]);
}
let p = parse_project(r#"<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><Sdk Name="Microsoft.NET.Sdk.Web"/><PropertyGroup><TargetFramework>net10.0</TargetFramework></PropertyGroup><PropertyGroup Condition="'$(Configuration)'=='Release'"><OutputType>Library</OutputType></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0" /></ItemGroup></Project>"#).unwrap();
assert!(p.executable && p.test);
assert!(parse_project("<Project><PropertyGroup>").is_none());
assert!(parse_project("garbage").is_none());
assert!(
parse_project(
r#"<Project><ItemGroup><PackageReference Update="microsoft.net.test.sdk" /></ItemGroup></Project>"#
)
.unwrap()
.test
);
assert!(
!parse_project(r#"<Project><!-- <PackageReference Include="Microsoft.NET.Test.Sdk"/> --></Project>"#)
.unwrap()
.test
);
}
#[test]
fn profiles_filter_and_preserve_launch_properties() {
let p = parse_profiles(PROFILES);
assert_eq!(p.keys().map(String::as_str).collect::<Vec<_>>(), ["http", "https"]);
assert_eq!(p["http"].application_url, "http://localhost:5165");
assert_eq!(p["http"].environment_variables["DEMO"], "profile");
assert_eq!(p["http"].command_line_args, "--message \"hello world\"");
assert_eq!(p["http"].working_directory, "work");
assert!(parse_profiles("invalid").is_empty());
}
#[test]
fn solution_paths_support_windows_separators_folders_and_entities() {
let sln = "Project(\"{guid}\") = \"App\", \"src\\App\\App.csproj\", \"{guid}\"\nEndProject\nProject(\"{folder}\") = \"Folder\", \"Folder\", \"{guid}\"\nProject(\"{guid}\") = \"External\", \"..\\other\\Other.csproj\", \"{guid}\"";
assert_eq!(
solution_projects(sln, false),
[PathBuf::from("src/App/App.csproj"), PathBuf::from("../other/Other.csproj")]
);
let slnx = r#"<Solution><Folder Name="/src/"><Project Path="src\A&amp;B\App.csproj" /></Folder><Project Path="other.vbproj" /></Solution>"#;
assert_eq!(solution_projects(slnx, true), [PathBuf::from("src/A&B/App.csproj")]);
assert!(solution_projects("<Solution><Project", true).is_empty());
}
#[test]
fn detection_deduplicates_projects_and_generates_commands() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
write(root, "src/App/App.csproj", CONSOLE);
write(root, "src/App/Properties/launchSettings.json", PROFILES);
write(
root,
"demo.slnx",
r#"<Solution><Project Path="src/App/App.csproj"/><Project Path="../external/Missing.csproj"/></Solution>"#,
);
write(
root,
"src/Test/Test.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net10.0</TargetFramework></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk"/></ItemGroup></Project>"#,
);
write(root, "bin/Ignored.csproj", CONSOLE);
write(root, "obj/Ignored.csproj", CONSOLE);
write(root, "node_modules/Ignored.csproj", CONSOLE);
write(root, "Lib.csproj", "<Project Sdk=\"Microsoft.NET.Sdk\" />");
let configs = detect(root);
assert_eq!(configs.len(), 4);
let app = configs.iter().find(|c| c.extras.params.get("launchProfile").is_some_and(|p| p == "http")).unwrap();
assert_eq!(
app.args,
["run", "--project", "src/App/App.csproj", "--framework", "net10.0", "--launch-profile", "http"]
);
assert_eq!(app.debug_adapter.as_deref(), Some("netcoredbg"));
assert_eq!(app.extras.before_launch[0].kind, "dotnetBuild");
let test = configs.iter().find(|c| c.is_test).unwrap();
assert_eq!(test.kind, "dotnet-test");
assert_eq!(test.args, ["test", "src/Test/Test.csproj", "--framework", "net10.0"]);
assert!(test.debug_adapter.is_none());
let mut edited = app.clone();
edited.env.insert("DEMO".into(), "override".into());
let resolved = resolve(root, edited.clone()).unwrap();
assert_eq!(resolved.env["DEMO"], "override");
assert_eq!(resolved.env["ASPNETCORE_URLS"], "http://localhost:5165");
assert!(resolved.cwd.unwrap().ends_with("src/App/work"));
edited.extras.params.insert("launchProfile".into(), "https".into());
let resolved = resolve(root, edited).unwrap();
assert!(!resolved.env.contains_key("ASPNETCORE_URLS"));
assert!(resolved.cwd.unwrap().ends_with("src/App"));
}
#[test]
fn solution_references_can_reach_projects_outside_the_open_directory() {
let temp = tempfile::tempdir().unwrap();
write(temp.path(), "external/App.csproj", CONSOLE);
write(temp.path(), "open/demo.sln", "Project(\"{guid}\") = \"App\", \"..\\external\\App.csproj\", \"{guid}\"");
let configs = detect(&temp.path().join("open"));
assert_eq!(configs.len(), 1);
assert!(configs[0].args[2].ends_with("external/App.csproj"));
}
-4
Переглянути файл
@@ -178,10 +178,6 @@ impl TerminalManager {
let Some(pid) = session.info.pid else { return Ok(false) };
Ok(foreground_busy(&session, pid))
}
/// Whether a terminal session is still registered.
pub fn contains(&self, id: TerminalId) -> bool {
self.sessions.lock().contains_key(&id)
}
pub fn list(&self) -> Vec<TerminalInfo> {
let mut out: Vec<TerminalInfo> = self.sessions.lock().values().map(|s| s.info.clone()).collect();
-69
Переглянути файл
@@ -2,29 +2,6 @@
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
/// Platform adapters supply the system's tab preference and active project state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabbingPreference {
Always,
InFullScreen,
Manually,
}
pub fn should_group_new_project(
preference: TabbingPreference,
fullscreen: bool,
active_project: bool,
light_edit: bool,
) -> bool {
active_project
&& !light_edit
&& match preference {
TabbingPreference::Always => true,
TabbingPreference::InFullScreen => fullscreen,
TabbingPreference::Manually => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WindowGroup {
pub members: Vec<String>,
@@ -62,13 +39,6 @@ impl WindowGroups {
Ok(())
}
/// Adds a window to the anchor's group without merging unrelated groups.
pub fn join(&mut self, anchor: &str, member: &str) -> IdeResult<()> {
let mut members = self.group(anchor).map(|g| g.members.clone()).unwrap_or_else(|| vec![anchor.to_owned()]);
members.push(member.to_owned());
self.merge(members, anchor)
}
pub fn select(&mut self, caller: &str, target: &str) -> IdeResult<WindowGroup> {
let group = self
.groups
@@ -124,45 +94,6 @@ mod tests {
values.iter().map(|s| (*s).into()).collect()
}
#[test]
fn new_project_grouping_follows_system_preference_and_excludes_light_edit() {
for preference in [TabbingPreference::Always, TabbingPreference::InFullScreen, TabbingPreference::Manually] {
for fullscreen in [false, true] {
for active_project in [false, true] {
for light_edit in [false, true] {
let expected = matches!(
(preference, fullscreen, active_project, light_edit),
(TabbingPreference::Always, _, true, false)
| (TabbingPreference::InFullScreen, true, true, false)
);
assert_eq!(
should_group_new_project(preference, fullscreen, active_project, light_edit),
expected,
"{preference:?}, fullscreen={fullscreen}, active={active_project}, light={light_edit}"
);
}
}
}
}
}
#[test]
fn joining_new_windows_preserves_the_active_group_and_other_groups() {
let mut groups = WindowGroups::default();
groups.merge(members(&["other-a", "other-b"]), "other-b").unwrap();
groups.join("a", "b").unwrap();
assert_eq!(groups.group("a").unwrap().members, members(&["a", "b"]));
let before = groups.select("a", "b").unwrap();
assert_eq!(before.selected, "a");
groups.join("b", "c").unwrap();
let before = groups.select("b", "c").unwrap();
assert_eq!(before.selected, "b");
assert_eq!(groups.group("c").unwrap().members, members(&["a", "b", "c"]));
assert_eq!(groups.group("c").unwrap().selected, "c");
assert_eq!(groups.group("other-a").unwrap().members, members(&["other-a", "other-b"]));
assert_eq!(groups.group("other-a").unwrap().selected, "other-b");
}
#[test]
fn selecting_and_detaching_preserve_the_other_sessions() {
let mut groups = WindowGroups::default();
-8
Переглянути файл
@@ -78,11 +78,3 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
-2
Переглянути файл
@@ -298,7 +298,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_changelists_save,
vcs::vcs_write_patch,
term::term_spawn,
term::term_store_image,
term::term_write,
term::term_resize,
term::term_kill,
@@ -306,7 +305,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
term::term_default_shell,
term::term_available_shells,
run::run_configs,
run::run_dotnet_resolve,
run::run_save_configs,
run::run_templates,
run::run_save_templates,
-11
Переглянути файл
@@ -8,17 +8,6 @@ use ide_run::{OutputChunk, RunConfig, RunInfo};
use tauri::ipc::Channel;
use tauri::{State, Window};
#[tauri::command]
#[specta::specta]
pub async fn run_dotnet_resolve(
window: Window,
state: State<'_, AppState>,
config: RunConfig,
debug: bool,
) -> IdeResult<RunConfig> {
ide_host::ops::run::run_dotnet_resolve(&state.host, window.label(), config, debug).await
}
#[tauri::command]
#[specta::specta]
pub async fn run_application_build(
-11
Переглянути файл
@@ -24,17 +24,6 @@ pub async fn term_spawn(
)
}
#[tauri::command]
#[specta::specta]
pub async fn term_store_image(
state: State<'_, AppState>,
id: TerminalId,
data: Vec<u8>,
mime: String,
) -> IdeResult<String> {
ide_host::ops::term::store_image(&state.host, id, data, mime).await
}
#[tauri::command]
#[specta::specta]
pub fn term_write(state: State<'_, AppState>, id: TerminalId, data: String) -> IdeResult<()> {
+1 -11
Переглянути файл
@@ -11,8 +11,6 @@ mod events;
#[cfg(any(target_os = "linux", test))]
mod linux_window_state;
mod logging;
#[cfg(target_os = "macos")]
mod macos;
mod menu;
mod remote_dev;
@@ -21,8 +19,6 @@ mod theme_frame;
#[cfg(target_os = "macos")]
mod titlebar;
mod window_groups;
#[cfg(any(windows, test))]
mod window_work_area;
mod windows;
use parking_lot::Mutex;
@@ -74,9 +70,6 @@ pub fn run() {
// Single instance first: a second launch focuses this one and opens its path argument.
// Debug builds have a separate identifier per worktree.
let app = app.plugin(tauri_plugin_single_instance::init(windows::on_second_instance));
// Install before window-state restores maximized geometry during window creation.
#[cfg(windows)]
let app = app.plugin(window_work_area::init());
let app = app.plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_dialog::init());
#[cfg(target_os = "linux")]
let app = app.plugin(linux_window_state::plugin());
@@ -174,10 +167,7 @@ pub fn run() {
tauri::WindowEvent::Focused(false) => application_focus::changed(window.app_handle(), false),
tauri::WindowEvent::Destroyed => {
#[cfg(target_os = "macos")]
{
titlebar::forget(window);
macos::forget_fullscreen(window.label());
}
titlebar::forget(window);
window_groups::destroyed(window.app_handle(), window.label());
if let Some(settings) = window.app_handle().get_webview_window(&windows::settings_label(window.label())) {
let _ = settings.destroy();
-98
Переглянути файл
@@ -1,98 +0,0 @@
//! macOS window tab preferences, applied to application-drawn project tabs.
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
use objc2::{MainThreadMarker, rc::Retained, runtime::ProtocolObject};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
use tauri::{AppHandle, Manager, WebviewWindow};
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
fn read(mtm: MainThreadMarker) -> TabbingPreference {
match NSWindow::userTabbingPreference(mtm) {
NSWindowUserTabbingPreference::Always => TabbingPreference::Always,
NSWindowUserTabbingPreference::InFullScreen => TabbingPreference::InFullScreen,
_ => TabbingPreference::Manually,
}
}
if let Some(mtm) = MainThreadMarker::new() {
return Ok(read(mtm));
}
let (tx, rx) = std::sync::mpsc::sync_channel(1);
app.run_on_main_thread(move || {
let _ = tx.send(read(MainThreadMarker::new().expect("AppKit main thread")));
})
.map_err(|e| IdeError::internal(e.to_string()))?;
rx.recv().map_err(|e| IdeError::internal(e.to_string()))
}
/// Capture before building the new window, which takes focus itself.
pub fn new_project_tab_target(app: &AppHandle, launch: &Launch) -> IdeResult<Option<WebviewWindow>> {
let windows = app.webview_windows();
let active = windows
.values()
.find(|w| w.is_focused().unwrap_or(false))
.cloned()
.or_else(|| app.state::<WindowsState>().last_focused().and_then(|label| windows.get(&label).cloned()));
let active = active.and_then(|w| {
let label = crate::windows::settings_parent(w.label()).unwrap_or(w.label());
windows.get(label).cloned()
});
let active = active.filter(|w| {
let host = app.state::<crate::state::AppState>();
host.project(w.label()).is_ok_and(|p| !p.light) || host.remote_dev.get(w.label()).is_some()
});
let fullscreen = active.as_ref().is_some_and(|w| w.is_fullscreen().unwrap_or(false));
let light_edit = launch.project.is_none() && launch.remote.is_none();
Ok(should_group_new_project(tabbing_preference(app)?, fullscreen, active.is_some(), light_edit)
.then_some(active)
.flatten())
}
struct FullscreenObserver(Retained<ProtocolObject<dyn NSObjectProtocol>>);
impl Drop for FullscreenObserver {
fn drop(&mut self) {
let observer: &ProtocolObject<dyn NSObjectProtocol> = &self.0;
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
}
thread_local! {
static FULLSCREEN_TRANSFERS: std::cell::RefCell<std::collections::HashMap<String, FullscreenObserver>> = std::cell::RefCell::default();
}
pub fn forget_fullscreen(label: &str) {
FULLSCREEN_TRANSFERS.with_borrow_mut(|observers| observers.remove(label));
}
/// AppKit cannot enter another window's fullscreen Space until the old one has exited.
pub fn transfer_fullscreen(from: &WebviewWindow, to: &WebviewWindow) -> tauri::Result<()> {
let source = from.label().to_owned();
let to = to.clone();
from.with_webview(move |webview| unsafe {
let native = &*webview.ns_window().cast::<NSWindow>();
forget_fullscreen(&source);
let label = source.clone();
let block = block2::RcBlock::new(move |_| {
forget_fullscreen(&label);
let app = to.app_handle();
let selected = app.state::<WindowsState>().groups.lock().group(to.label()).map(|g| g.selected.clone());
if let Some(selected) = selected {
// Exiting fullscreen can show the old window again; reapply group visibility.
let _ = crate::window_groups::select(app, &selected, &selected);
if selected == to.label() {
let _ = to.set_fullscreen(true);
}
}
});
let observer = NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
Some(objc2_app_kit::NSWindowDidExitFullScreenNotification),
Some(native),
None,
&block,
);
FULLSCREEN_TRANSFERS.with_borrow_mut(|observers| observers.insert(source, FullscreenObserver(observer)));
native.toggleFullScreen(None);
})
}
+3 -15
Переглянути файл
@@ -51,13 +51,8 @@ fn copy_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let fullscreen = from.is_fullscreen().map_err(err)?;
if fullscreen {
#[cfg(target_os = "macos")]
crate::macos::transfer_fullscreen(from, to).map_err(err)?;
#[cfg(not(target_os = "macos"))]
{
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
}
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
return Ok(());
}
to.set_fullscreen(false).map_err(err)?;
@@ -114,13 +109,6 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
result
}
#[cfg(target_os = "macos")]
pub fn join(app: &AppHandle, anchor: &str, new_window: &str) -> IdeResult<()> {
let state = app.state::<WindowsState>();
state.groups.lock().join(anchor, new_window)?;
select(app, anchor, new_window)
}
pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
let members = windows::project_window_labels(app)
.into_iter()
@@ -247,7 +235,7 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
} else if path.is_dir() {
let window = match windows::find_project_window(app, path) {
Some(w) => w,
None => windows::create_restored_window(app, path.clone())?,
None => windows::create_window(app, Some(path.clone()))?,
};
Some(window.label().to_owned())
} else {
-208
Переглянути файл
@@ -1,208 +0,0 @@
//! Native maximize bounds for every Windows frameless window, including state restoration.
#[cfg(windows)]
pub use native::init;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Rect {
left: i32,
top: i32,
right: i32,
bottom: i32,
}
/// All coordinates are physical pixels in the selected monitor's coordinate space.
/// Auto-hide needs one exposed pixel, but an already reserved edge needs no extra inset.
fn bounds(monitor: Rect, work: Rect, auto_hide: [bool; 4], fullscreen: bool) -> Rect {
if fullscreen {
return monitor;
}
let [left, top, right, bottom] = auto_hide;
Rect {
left: work.left + i32::from(left && work.left == monitor.left),
top: work.top + i32::from(top && work.top == monitor.top),
right: work.right - i32::from(right && work.right == monitor.right),
bottom: work.bottom - i32::from(bottom && work.bottom == monitor.bottom),
}
}
fn maximize_geometry(monitor: Rect, area: Rect) -> (i32, i32, i32, i32) {
(area.left - monitor.left, area.top - monitor.top, area.right - area.left, area.bottom - area.top)
}
#[cfg(windows)]
mod native {
use super::{Rect, bounds, maximize_geometry};
use windows_sys::Win32::{
Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM},
Graphics::Gdi::{
GetMonitorInfoW, HMONITOR, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromRect, MonitorFromWindow,
},
UI::{
Shell::{
ABE_BOTTOM, ABE_LEFT, ABE_RIGHT, ABE_TOP, ABM_GETAUTOHIDEBAREX, APPBARDATA, DefSubclassProc,
RemoveWindowSubclass, SHAppBarMessage, SetWindowSubclass,
},
WindowsAndMessaging::{
GWL_STYLE, GetWindowLongPtrW, IsZoomed, MINMAXINFO, NCCALCSIZE_PARAMS, WM_GETMINMAXINFO, WM_NCCALCSIZE,
WM_NCDESTROY, WS_CAPTION,
},
},
};
const SUBCLASS: usize = 0x410;
pub fn init() -> tauri::plugin::TauriPlugin<tauri::Wry> {
tauri::plugin::Builder::new("window-work-area")
.on_window_ready(|window| {
if window.is_decorated().unwrap_or(true) {
return;
}
let install = || -> tauri::Result<()> {
let hwnd = window.hwnd()?.0 as usize;
window.run_on_main_thread(move || {
// Subclasses must be installed and removed on the owning GUI thread.
if unsafe { SetWindowSubclass(hwnd as HWND, Some(window_proc), SUBCLASS, 0) } == 0 {
tracing::warn!(
"cannot install window work area handler: {}",
std::io::Error::last_os_error()
);
}
})
};
if let Err(error) = install() {
tracing::warn!("cannot install window work area handler: {error}");
}
})
.build()
}
fn rect(rect: RECT) -> Rect {
Rect { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }
}
fn native_rect(rect: Rect) -> RECT {
RECT { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }
}
unsafe fn monitor_bounds(monitor: HMONITOR, fullscreen: bool) -> Option<(Rect, Rect)> {
let mut info = MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, ..Default::default() };
if unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 {
return None;
}
let mut auto_hide = [false; 4];
if !fullscreen {
for (index, edge) in [ABE_LEFT, ABE_TOP, ABE_RIGHT, ABE_BOTTOM].into_iter().enumerate() {
let mut data = APPBARDATA {
cbSize: size_of::<APPBARDATA>() as u32,
uEdge: edge,
rc: info.rcMonitor,
..Default::default()
};
auto_hide[index] = unsafe { SHAppBarMessage(ABM_GETAUTOHIDEBAREX, &mut data) } != 0;
}
}
let monitor = rect(info.rcMonitor);
Some((monitor, bounds(monitor, rect(info.rcWork), auto_hide, fullscreen)))
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
_id: usize,
_data: usize,
) -> LRESULT {
// Tao keeps WS_CAPTION on frameless windows and removes it for native fullscreen.
// Read native styles here: a Tauri state query from its window procedure can deadlock.
let fullscreen = unsafe { GetWindowLongPtrW(hwnd, GWL_STYLE) } as u32 & WS_CAPTION == 0;
match message {
WM_GETMINMAXINFO if !fullscreen => {
// Keep Tao's min/max tracking constraints, then set the outer maximize bounds.
let result = unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
if let Some((monitor, area)) = unsafe { monitor_bounds(monitor, false) } {
let (x, y, width, height) = maximize_geometry(monitor, area);
let info = unsafe { &mut *(lparam as *mut MINMAXINFO) };
info.ptMaxPosition.x = x;
info.ptMaxPosition.y = y;
info.ptMaxSize.x = width;
info.ptMaxSize.y = height;
}
result
}
WM_NCCALCSIZE if wparam != 0 && (fullscreen || unsafe { IsZoomed(hwnd) } != 0) => {
let params = unsafe { &mut *(lparam as *mut NCCALCSIZE_PARAMS) };
// Use the proposed rectangle: a move/snap/DPI change can target another monitor.
let monitor = unsafe { MonitorFromRect(&params.rgrc[0], MONITOR_DEFAULTTONEAREST) };
if let Some((_, area)) = unsafe { monitor_bounds(monitor, fullscreen) } {
// Replace Tao's client-only clamp and global auto-hide query. Fullscreen
// must retain the entire display, even when entered from a maximized window.
params.rgrc[0] = native_rect(area);
0
} else {
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
}
WM_NCDESTROY => {
unsafe { RemoveWindowSubclass(hwnd, Some(window_proc), SUBCLASS) };
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
_ => unsafe { DefSubclassProc(hwnd, message, wparam, lparam) },
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn r(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
Rect { left, top, right, bottom }
}
#[test]
fn taskbars_on_every_edge_and_secondary_displays() {
for (monitor, work, expected) in [
// Reported case: maximized window must leave the bottom taskbar visible.
(r(0, 0, 1920, 1080), r(0, 0, 1920, 1040), (0, 0, 1920, 1040)),
(r(0, 0, 1920, 1080), r(48, 0, 1920, 1080), (48, 0, 1872, 1080)),
(r(0, 0, 1920, 1080), r(0, 40, 1920, 1080), (0, 40, 1920, 1040)),
(r(0, 0, 1920, 1080), r(0, 0, 1872, 1080), (0, 0, 1872, 1080)),
// Negative origin, top taskbar, 150% display beside a 100% display.
(r(-2560, -1440, 0, 0), r(-2560, -1380, 0, 0), (0, 60, 2560, 1380)),
// 250% display: physical bounds must not be scaled with the previous monitor's DPI.
(r(1920, 0, 5760, 2160), r(1920, 0, 5760, 2060), (0, 0, 3840, 2060)),
] {
let area = bounds(monitor, work, [false; 4], false);
assert_eq!(area, work);
assert_eq!(maximize_geometry(monitor, area), expected);
}
}
#[test]
fn auto_hide_leaves_a_physical_pixel_only_on_its_own_monitor_edge() {
let monitor = r(-1920, 0, 0, 1080);
for (edges, expected) in [
([true, false, false, false], r(-1919, 0, 0, 1080)),
([false, true, false, false], r(-1920, 1, 0, 1080)),
([false, false, true, false], r(-1920, 0, -1, 1080)),
([false, false, false, true], r(-1920, 0, 0, 1079)),
([false; 4], monitor),
([true; 4], r(-1919, 1, -1, 1079)),
] {
assert_eq!(bounds(monitor, monitor, edges, false), expected);
}
let reserved = r(-1920, 0, 0, 1040);
assert_eq!(bounds(monitor, reserved, [false, false, false, true], false), reserved);
}
#[test]
fn fullscreen_covers_taskbars_including_when_entered_from_maximized() {
let monitor = r(1920, -100, 5760, 2060);
let work = r(1980, -100, 5760, 1960);
assert_eq!(bounds(monitor, work, [true; 4], true), monitor);
assert_eq!(bounds(monitor, work, [false; 4], false), work);
}
}
+8 -42
Переглянути файл
@@ -357,35 +357,18 @@ pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
/// Creates a new project window; `project` is opened by its frontend on load.
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
create_window_with(app, project, Vec::new(), false)
create_window_with(app, project, Vec::new())
}
/// [`create_window`] that also opens `files` (without `project`: in LightEdit).
fn create_window_with(
app: &AppHandle,
project: Option<PathBuf>,
files: Vec<PathBuf>,
restoring: bool,
) -> IdeResult<WebviewWindow> {
fn create_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathBuf>) -> IdeResult<WebviewWindow> {
let title = project.as_deref().or(files.first().map(PathBuf::as_path)).and_then(Path::file_name);
let title = title.map(|n| n.to_string_lossy().into_owned());
let files = files.into_iter().map(Into::into).collect();
create_window_for(app, title, Launch { project: project.map(Into::into), files, ..Default::default() }, restoring)
create_window_for(app, title, Launch { project: project.map(Into::into), files, ..Default::default() })
}
/// Restoring a saved group preserves its membership and selected tab.
pub fn create_restored_window(app: &AppHandle, project: PathBuf) -> IdeResult<WebviewWindow> {
create_window_with(app, Some(project), Vec::new(), true)
}
fn create_window_for(
app: &AppHandle,
title: Option<String>,
launch: Launch,
_restoring: bool,
) -> IdeResult<WebviewWindow> {
#[cfg(target_os = "macos")]
let tab_target = if _restoring { None } else { crate::macos::new_project_tab_target(app, &launch)? };
fn create_window_for(app: &AppHandle, title: Option<String>, launch: Launch) -> IdeResult<WebviewWindow> {
let windows = app.webview_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = window_config(app)?;
@@ -405,11 +388,6 @@ fn create_window_for(
}
app.state::<WindowsState>().set_launch(&label, launch);
let window = build_project_window(app, config)?;
#[cfg(target_os = "macos")]
if let Some(target) = tab_target {
crate::window_groups::join(app, target.label(), window.label())?;
return Ok(window);
}
focus(&window);
Ok(window)
}
@@ -423,7 +401,7 @@ pub fn spawn_window(app: &AppHandle, project: Option<PathBuf>) {
fn spawn_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathBuf>) {
let app = app.clone();
tauri::async_runtime::spawn(async move {
if let Err(e) = create_window_with(&app, project, files, false) {
if let Err(e) = create_window_with(&app, project, files) {
tracing::warn!("cannot open window: {}", e.message);
}
});
@@ -462,7 +440,7 @@ pub fn open_project_window(
if !new_window {
return Ok(OpenOutcome::Current);
}
let window = create_window_with(app, Some(root), files, false)?;
let window = create_window_with(app, Some(root), files)?;
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
}
@@ -472,7 +450,7 @@ pub fn open_project_window(
/// detach an editor tab out of its window.
pub fn open_file_in_new_window(app: &AppHandle, project: Option<PathBuf>, file: PathBuf) -> IdeResult<OpenOutcome> {
tracing::info!("open_file_in_new_window {} project={:?}", file.display(), project);
let window = create_window_with(app, project, vec![file], false)?;
let window = create_window_with(app, project, vec![file])?;
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
}
@@ -500,7 +478,7 @@ pub fn open_remote_window(app: &AppHandle, ssh_config: &str, path: &str, new_win
}
let title = path.trim_end_matches('/').rsplit('/').next().filter(|n| !n.is_empty() && *n != "~").map(str::to_owned);
let remote = RemoteLaunch { ssh_config: ssh_config.to_owned(), path: path.to_owned() };
let window = create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() }, false)?;
let window = create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() })?;
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
}
@@ -863,18 +841,9 @@ fn fit_settings_window(window: &WebviewWindow, parent: &WebviewWindow) -> tauri:
/// scale and its position is given in physical pixels.
#[cfg(not(target_os = "macos"))]
pub(super) fn place_settings_window(window: &WebviewWindow, parent: &WebviewWindow) -> tauri::Result<()> {
// Placement setters leave maximized mode. Fit the restored frame, then reapply the saved state.
// A restored fullscreen window already covers its display and must not be fitted to the work area.
if window.is_fullscreen()? {
return Ok(());
}
let Some(monitor) = parent.current_monitor()?.or(parent.primary_monitor()?) else {
return Ok(());
};
let maximized = window.is_maximized()?;
if maximized {
window.unmaximize()?;
}
let scale = monitor.scale_factor();
let area = monitor.work_area();
let origin = area.position.to_logical::<f64>(scale);
@@ -903,9 +872,6 @@ pub(super) fn place_settings_window(window: &WebviewWindow, parent: &WebviewWind
)))?;
window.set_size(tauri::LogicalSize::new(width, height))?;
}
if maximized {
window.maximize()?;
}
Ok(())
}
-2
Переглянути файл
@@ -551,7 +551,6 @@ export const commands = {
* to start the shell takes tens of milliseconds, a frozen UI if run there.
*/
termSpawn: (options: TerminalOptions, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("term_spawn", { options, onOutput })),
termStoreImage: (id: TerminalId, data: number[], mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termWrite: (id: TerminalId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("term_write", { id, data })),
termResize: (id: TerminalId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("term_resize", { id, cols, rows })),
termKill: (id: TerminalId) => typedError<null, IdeError>(__TAURI_INVOKE("term_kill", { id })),
@@ -566,7 +565,6 @@ export const commands = {
termAvailableShells: () => __TAURI_INVOKE<string[]>("term_available_shells"),
/** Detected configs followed by user-defined ones (user ids win on conflict). */
runConfigs: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_configs")),
runDotnetResolve: (config: RunConfig_Deserialize, debug: boolean) => typedError<RunConfig_Serialize, IdeError>(__TAURI_INVOKE("run_dotnet_resolve", { config, debug })),
runSaveConfigs: (configs: RunConfig_Deserialize[], removedDetectedIds: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("run_save_configs", { configs, removedDetectedIds })),
/** Configuration templates: per-type defaults applied to new configurations. */
runTemplates: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_templates")),
+2 -2
Переглянути файл
@@ -5,7 +5,7 @@ import { basename, dirname, useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { tx } from "@/platform/i18n";
import { Button, Dialog, Icon, IconButton, Input, T } from "@/ui";
import { openProjectWithPolicy } from "./windows";
import { openProjectInWindow } from "./windows";
import styles from "./WorkspaceDialog.module.css";
const useWorkspaceDialog = create<{ mode: "create" | "manage" | null }>(() => ({ mode: null }));
@@ -53,7 +53,7 @@ function WorkspaceDialog({ mode, onClose }: { mode: "create" | "manage"; onClose
const included = adding.trim() ? [...new Set([...projects, adding.trim()])] : projects;
if (mode === "create") {
const root = await call(commands.workspaceCreate(path.trim(), name.trim(), included));
await openProjectWithPolicy(root);
await openProjectInWindow(root, !!project);
} else {
const updated = await call(commands.workspaceUpdate(name.trim(), included));
useProject.setState({ project: updated, settings: updated.settings });
+3 -18
Переглянути файл
@@ -3,14 +3,13 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { WorkspaceDialogHost, showWorkspaceDialog } from "../WorkspaceDialog";
import { openProjectWithPolicy } from "../windows";
import { openProjectInWindow } from "../windows";
vi.mock("../windows", () => ({ openProjectWithPolicy: vi.fn(async () => {}) }));
vi.mock("../windows", () => ({ openProjectInWindow: vi.fn(async () => {}) }));
vi.mock("@/platform/remote", () => ({ isRemoteWindow: () => false }));
beforeEach(() => {
vi.restoreAllMocks();
vi.mocked(openProjectWithPolicy).mockClear();
useProject.setState({ project: null, settings: null, lightEdit: false });
});
@@ -22,21 +21,7 @@ it("creates a workspace from the pending project field without an extra Add clic
fireEvent.change(screen.getByLabelText("Project folder path"), { target: { value: "/work/frontend" } });
fireEvent.click(screen.getByRole("button", { name: /^Create$/ }));
await waitFor(() => expect(save).toHaveBeenCalledWith("/work/full", "Workspace", ["/work/frontend"]));
expect(openProjectWithPolicy).toHaveBeenCalledWith("/work/full");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("uses the shared opening policy after creation from an already open project", async () => {
useProject.setState({
project: { root: "/work/frontend", name: "frontend", trusted: true, isGit: false, settings: {} },
settings: { general: { openProjectIn: "ask" } },
} as never);
vi.spyOn(commands, "workspaceCreate").mockResolvedValue({ status: "ok", data: "/work/full" });
showWorkspaceDialog("create");
render(<WorkspaceDialogHost />);
fireEvent.change(screen.getByLabelText("Workspace location"), { target: { value: "/work/full" } });
fireEvent.click(screen.getByRole("button", { name: /^Create$/ }));
await waitFor(() => expect(openProjectWithPolicy).toHaveBeenCalledWith("/work/full"));
expect(openProjectInWindow).toHaveBeenCalledWith("/work/full", false);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
-20
Переглянути файл
@@ -321,23 +321,3 @@ describe("Go build configuration fields", () => {
});
});
});
it("netcoredbg launches the evaluated DLL with resolved profile arguments, env and cwd", () => {
const c = rc({
kind: "dotnet",
command: "dotnet",
debugAdapter: "netcoredbg",
cwd: "/repo/work",
env: { ASPNETCORE_URLS: "http://localhost:5165", DEMO: "override" },
params: { targetPath: "/repo/custom/Renamed.dll", programArgs: "--name 'hello world'", profileArgs: "--profile" },
});
expect(launchConfigFor(c, "/repo")).toMatchObject({
adapter: "netcoredbg",
program: "/repo/custom/Renamed.dll",
args: ["--name", "hello world"],
cwd: "/repo/work",
env: c.env,
});
expect(launchConfigFor({ ...c, params: { ...c.params, programArgs: "" } }, "/repo")?.args).toEqual(["--profile"]);
expect(launchConfigFor({ ...c, params: {} }, "/repo")).toBeNull();
});
-3
Переглянути файл
@@ -21,9 +21,6 @@ describe("missing debug adapters", () => {
expect(
missingAdapter("kotlin-debug-adapter", unavailable("debug adapter `kotlin-debug-adapter` not found (x)"))?.tool,
).toBe("kotlin-debug-adapter");
expect(missingAdapter("netcoredbg", unavailable("debug adapter `netcoredbg` not found (x)"))?.tool).toBe(
"netcoredbg",
);
expect(missingAdapter("delve", unavailable("debug adapter `delve` not found (x)"))?.tool).toBe("delve");
});
+1 -3
Переглянути файл
@@ -297,9 +297,7 @@ async function startConfig(arg: unknown) {
await startJavaConfig(config, root, origin ?? config);
return;
}
const dotnet = config.kind === "dotnet" && config.debugAdapter === "netcoredbg";
const prepared = dotnet ? await call(commands.runDotnetResolve(config, true)) : config;
const launch = launchConfigFor(prepared, root);
const launch = launchConfigFor(config, root);
if (!launch) {
notifications().notify({
group: "run",
-9
Переглянути файл
@@ -313,15 +313,6 @@ export function launchConfigFor(rc: RunConfig, root: string): LaunchConfig | nul
if (adapter === "js-debug") return jsDebugLaunch(rc, cwd);
if (adapter === "delve") return delveLaunch(rc, cwd, root);
if (adapter === "godot") return godotLaunch(rc, cwd);
if (adapter === "netcoredbg" && rc.kind === "dotnet") {
if (!rc.params?.targetPath) return null;
return {
...base(rc, adapter, cwd),
program: rc.params.targetPath,
args: parseArgs(rc.params.programArgs?.trim() ? rc.params.programArgs : rc.params.profileArgs || ""),
extraJson: JSON.stringify({ justMyCode: workflowSettings().debugger.skipLibraryCode }),
};
}
// Adapters without a template (hidden in Edit Configurations): generic arguments.
return {
...base(rc, adapter, cwd),
-1
Переглянути файл
@@ -7,7 +7,6 @@ import { IpcError } from "@/platform/ipc";
/** Adapters the tools installer can provide (adapter id → tool name). */
const INSTALLABLE: Record<string, { tool: string; title: string }> = {
"kotlin-debug-adapter": { tool: "kotlin-debug-adapter", title: "The Kotlin debugger is not installed" },
netcoredbg: { tool: "netcoredbg", title: "netcoredbg is not installed" },
debugpy: { tool: "debugpy", title: "debugpy is not installed" },
"js-debug": { tool: "js-debug", title: "The JavaScript debugger (vscode-js-debug) is not installed" },
delve: { tool: "delve", title: "Delve is not installed" },
-118
Переглянути файл
@@ -1,118 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { RemoteEntry, Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemoteProgress } from "@/platform/remote";
import { ConnectHost } from "./ConnectDialog";
import { closeConnectDialog, openConnectDialog, useConnectDialog } from "./model";
const { list, openRemote, executeAction } = vi.hoisted(() => ({
list: vi.fn(),
openRemote: vi.fn(),
executeAction: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, remoteBootstrapList: list } };
});
vi.mock("@/workbench/projectWindow", () => ({ openRemoteProject: openRemote }));
vi.mock("@/platform/actions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/actions")>()),
executeAction,
}));
const entry = (path: string, isDir = true): RemoteEntry => ({
name: path.slice(path.lastIndexOf("/") + 1),
path,
isDir,
isSymlink: false,
size: 0,
mtime: null,
permissions: "rwxr-xr-x",
});
beforeEach(() => {
vi.resetAllMocks();
useProject.setState({
project: null,
opening: false,
settings: {
ssh: {
configs: [
{ id: "first", name: "First host", host: "first.example", user: "dev" },
{ id: "selected", name: "Selected host", host: "selected.example", user: "dev" },
],
},
} as Settings,
});
useRemoteProgress.setState({ progress: null, location: null });
openConnectDialog();
});
afterEach(() => closeConnectDialog());
it("browses the selected SSH host, navigates folders and opens one without a current project", async () => {
let finish!: (result: { status: "ok"; data: RemoteEntry[] }) => void;
list.mockImplementationOnce(() => new Promise((resolve) => (finish = resolve)));
openRemote.mockResolvedValue(true);
render(<ConnectHost />);
fireEvent.click(screen.getByRole("button", { name: "SSH configuration" }));
fireEvent.click(screen.getByRole("option", { name: /Selected host/ }));
fireEvent.click(screen.getByRole("button", { name: "Browse" }));
expect(list).toHaveBeenCalledWith("selected", "~");
expect(screen.getByRole("button", { name: "Browse" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Open" })).toBeDisabled();
finish({
status: "ok",
data: [entry("/home/dev/.cache"), entry("/home/dev/projects"), entry("/home/dev/README.md", false)],
});
const folders = await screen.findByRole("list", { name: "Remote folders" });
expect(
within(folders)
.getAllByRole("button")
.map((button) => button.textContent),
).toEqual(["..", "projects", ".cache"]);
expect(screen.getByLabelText("Project directory:")).toHaveValue("/home/dev");
list.mockResolvedValueOnce({ status: "ok", data: [entry("/home/dev/projects/demo")] });
fireEvent.click(within(folders).getByRole("button", { name: "projects" }));
await screen.findByRole("button", { name: "demo" });
expect(list).toHaveBeenLastCalledWith("selected", "/home/dev/projects");
list.mockResolvedValueOnce({ status: "ok", data: [entry("/home/dev/projects")] });
fireEvent.click(within(folders).getByRole("button", { name: ".." }));
await waitFor(() => expect(screen.getByLabelText("Project directory:")).toHaveValue("/home/dev"));
expect(list).toHaveBeenLastCalledWith("selected", "/home/dev");
list.mockResolvedValueOnce({ status: "ok", data: [] });
fireEvent.click(within(folders).getByRole("button", { name: "projects" }));
await waitFor(() => expect(screen.getByLabelText("Project directory:")).toHaveValue("/home/dev/projects"));
expect(within(folders).getAllByRole("button")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Open" }));
await waitFor(() => expect(openRemote).toHaveBeenCalledWith("selected", "/home/dev/projects"));
expect(useConnectDialog.getState().open).toBe(false);
expect(useProject.getState().project).toBeNull();
});
it("shows a connection error and lets the welcome window retry Browse", async () => {
list.mockRejectedValueOnce(new Error("Connection refused"));
render(<ConnectHost />);
fireEvent.change(screen.getByLabelText("Project directory:"), { target: { value: " /srv/projects " } });
fireEvent.click(screen.getByRole("button", { name: "Browse" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Connection refused");
expect(list).toHaveBeenCalledWith("first", "/srv/projects");
expect(screen.getByRole("button", { name: "Browse" })).toBeEnabled();
list.mockResolvedValueOnce({ status: "ok", data: [] });
fireEvent.click(screen.getByRole("button", { name: "Browse" }));
await screen.findByRole("list", { name: "Remote folders" });
expect(screen.queryByRole("alert")).toBeNull();
expect(openRemote).not.toHaveBeenCalled();
});
it("offers SSH configuration from the welcome window and disables Browse until one exists", () => {
useProject.setState({ settings: { ssh: { configs: [] } } as unknown as Settings });
render(<ConnectHost />);
expect(screen.getByRole("button", { name: "Browse" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Open" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Configure…" }));
expect(executeAction).toHaveBeenCalledWith("file.settings", "tools.sshConfigurations");
expect(list).not.toHaveBeenCalled();
});
+1 -5
Переглянути файл
@@ -48,12 +48,11 @@ import styles from "./Run.module.css";
/**
* Debug adapters with a real launch template (`debugger/launch.ts`, `debugger/java.ts`),
* verified against small programs. Others (dart, php-debug, …) only got
* verified against small programs. Others (netcoredbg, dart, php-debug, …) only got
* generic launch arguments and are left out until they have one; a configuration that
* already names one keeps it.
*/
const ADAPTERS: ReadonlyArray<{ id: string; label: string }> = [
{ id: "netcoredbg", label: "netcoredbg (.NET)" },
{ id: "java-debug", label: "java-debug (Java)" },
{ id: "kotlin-debug-adapter", label: "kotlin-debug-adapter (Kotlin)" },
{ id: "debugpy", label: "debugpy (Python)" },
@@ -255,9 +254,6 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
})),
},
{ label: TASK_LABELS.build, icon: "build-project", run: () => addTask("build") },
...(config.kind === "dotnet"
? [{ label: TASK_LABELS.dotnetBuild, icon: "build-project", run: () => addTask("dotnetBuild") }]
: []),
{
label: TASK_LABELS.tool,
disabled: !externalTools.length,
+1 -7
Переглянути файл
@@ -2,7 +2,6 @@
* Before launch tasks (IDEA's "Before launch" list): run in order before a
* configuration starts; the first failure aborts the launch.
*/
import { dotnetBuildConfig } from "./dotnetTypes";
import { executeAction, getAction } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { tx, txTemplate } from "@/platform/i18n";
@@ -15,12 +14,11 @@ import { startRun, useRun } from "./store";
export const BUILD_ACTION = "build.buildProject";
const BUILD_STATUS = "build.lastStatus";
export type BeforeLaunchKind = "run" | "build" | "tool" | "command" | "toolWindow" | "dotnetBuild";
export type BeforeLaunchKind = "run" | "build" | "tool" | "command" | "toolWindow";
export const TASK_LABELS: Record<BeforeLaunchKind, string> = {
run: "Run Another Configuration",
build: "Build Project",
dotnetBuild: "Build .NET project",
tool: "Run External Tool",
command: "Run Shell Command",
toolWindow: "Activate Tool Window",
@@ -34,8 +32,6 @@ export function taskLabel(task: BeforeLaunchTask, configs: readonly RunConfig[]
return `Run '${configs.find((c) => c.id === target)?.name ?? target}'`;
case "build":
return "Build Project";
case "dotnetBuild":
return "Build .NET project";
case "tool":
return `External tool '${workflowSettings().externalTools.find((t) => t.id === target)?.name ?? target}'`;
case "command":
@@ -62,8 +58,6 @@ async function runToEnd(config: RunConfig, chain: readonly string[]): Promise<bo
async function runTask(task: BeforeLaunchTask, config: RunConfig, chain: readonly string[]): Promise<string | null> {
const target = task.target ?? "";
switch (task.kind) {
case "dotnetBuild":
return (await runToEnd(dotnetBuildConfig(config), chain)) ? null : "Build failed";
case "build": {
if (!getAction(BUILD_ACTION)) return "Building is not available";
if (!(await executeAction(BUILD_ACTION, { activate: false }))) return "A build is already running";
+1 -4
Переглянути файл
@@ -67,9 +67,6 @@ export function configIcon(config: Pick<RunConfig, "kind" | "isTest">): string {
return "file-gradle";
case "maven":
return "file-maven";
case "dotnet":
case "dotnet-test":
return "file-csharp";
case "go":
return "file-go";
case "node":
@@ -223,7 +220,7 @@ export function validateConfig(config: RunConfig, all: readonly RunConfig[] = []
for (const t of config.beforeLaunch ?? []) {
if (t.kind === "run" && (t.target === config.id || !all.some((c) => c.id === t.target)))
errors.beforeLaunch = "A before launch task runs a missing configuration or this one";
else if (t.kind !== "build" && t.kind !== "dotnetBuild" && t.kind !== "run" && !(t.target ?? "").trim())
else if (t.kind !== "build" && t.kind !== "run" && !(t.target ?? "").trim())
errors.beforeLaunch = "A before launch task is incomplete";
}
for (const key of Object.keys(config.env)) {
-123
Переглянути файл
@@ -1,123 +0,0 @@
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { dotnetBuildConfig, dotnetProjectType, dotnetTestType } from "./dotnetTypes";
import { ConfigForm } from "./ConfigForm";
import { validateConfig } from "./configs";
import { newConfigOfType, registerBuiltinTypes, withParams } from "./types";
const resolveDotnet = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, runDotnetResolve: resolveDotnet } };
});
const params = {
project: "src/My App/App.csproj",
framework: "net10.0",
frameworks: "net10.0;net9.0",
launchProfile: "local web",
programArgs: "--name 'hello world'",
profiles: JSON.stringify({
"local web": { applicationUrl: "http://localhost:5165", environmentVariables: { DEMO: "profile" } },
alternate: {},
}),
};
let dispose: () => void;
beforeEach(() => {
dispose = registerBuiltinTypes();
});
afterEach(() => dispose());
function config(): RunConfig {
return withParams({ ...newConfigOfType(dotnetProjectType, []), name: "demo" }, params, dotnetProjectType);
}
describe(".NET configurations", () => {
it("generates run/test commands with spaces, framework/profile and separated program arguments", () => {
const c = config();
expect(c.args).toEqual([
"run",
"--project",
"src/My App/App.csproj",
"--framework",
"net10.0",
"--launch-profile",
"local web",
"--",
"--name",
"hello world",
]);
expect(c.debugAdapter).toBe("netcoredbg");
expect(c.beforeLaunch).toEqual([{ kind: "dotnetBuild", target: "" }]);
expect(validateConfig(c, [c])).toEqual({});
const t = withParams(
newConfigOfType(dotnetTestType, []),
{ project: params.project, framework: "net9.0", programArgs: '--filter "Category=Unit"' },
dotnetTestType,
);
expect(t.isTest).toBe(true);
expect(t.debugAdapter).toBeNull();
expect(t.args).toEqual(["test", params.project, "--framework", "net9.0", "--filter", "Category=Unit"]);
expect(dotnetProjectType.commandLine({ project: "App.csproj" })?.args).toEqual([
"run",
"--project",
"App.csproj",
"--no-launch-profile",
]);
});
it("builds edited project/framework from the open root instead of a profile cwd", () => {
useProject.setState({ project: { root: "/repo" } as never });
const c = withParams(
{ ...config(), cwd: "profile/work" },
{ ...params, project: "other/App.csproj", framework: "net9.0" },
);
const build = dotnetBuildConfig(c);
expect(build.args).toEqual(["build", "other/App.csproj", "--configuration", "Debug", "--framework", "net9.0"]);
expect(build.cwd).toBe("/repo");
expect(build.beforeLaunch).toEqual([]);
});
it("edits project, framework, profile, arguments and environment in the shared form", () => {
const c = config();
const change = vi.fn();
render(
<ConfigForm config={c} all={[c]} type={dotnetProjectType} errors={{}} modifyRequest={0} onChange={change} />,
);
expect(screen.getByText("http://localhost:5165")).toBeTruthy();
expect(screen.getByText("DEMO=profile")).toBeTruthy();
for (const [label, value] of [
[".NET project", "other/App.csproj"],
["Target framework", "net9.0"],
["Launch profile", "alternate"],
["Program arguments", "--edited"],
] as const) {
fireEvent.change(screen.getByLabelText(label), { target: { value } });
expect(change).toHaveBeenCalled();
}
fireEvent.change(screen.getByRole("textbox", { name: "Environment variables" }), {
target: { value: "DEMO=override" },
});
expect(change.mock.lastCall?.[0]).toMatchObject({ env: { DEMO: "override" } });
});
it("prepares Run from the freshly resolved profile while keeping explicit argument overrides", async () => {
const c = config();
resolveDotnet.mockResolvedValue({
status: "ok",
data: {
...c,
cwd: "/repo/work",
env: { DEMO: "override" },
params: { ...params, project: "/repo/App.csproj", profileArgs: "--from-profile" },
},
});
const prepared = await dotnetProjectType.prepareLaunch!(c);
expect(commands.runDotnetResolve).toHaveBeenCalledWith(c, false);
expect(prepared).toMatchObject({ cwd: "/repo/work", env: { DEMO: "override" } });
expect(prepared.args).toContain("--no-launch-profile");
expect(prepared.args.slice(-3)).toEqual(["--", "--name", "hello world"]);
});
});
-134
Переглянути файл
@@ -1,134 +0,0 @@
import { call, commands, type RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { parseArgs } from "./configs";
function profile(p: Readonly<Record<string, string>>): {
applicationUrl?: string;
environmentVariables?: Record<string, string>;
} {
try {
return JSON.parse(p.profiles || "{}")[p.launchProfile || ""] ?? {};
} catch {
return {};
}
}
export function dotnetCommand(p: Readonly<Record<string, string>>, test = false) {
return {
command: p.executable || "dotnet",
args: [
...(test ? ["test", p.project || ""] : ["run", "--project", p.project || ""]),
...(p.framework ? ["--framework", p.framework] : []),
...(!test ? (p.launchProfile ? ["--launch-profile", p.launchProfile] : ["--no-launch-profile"]) : []),
...(p.programArgs?.trim() ? ["--", ...parseArgs(p.programArgs)] : []),
],
};
}
/** Build the current project/framework, independently of the run's profile working directory. */
export function dotnetBuildConfig(config: RunConfig): RunConfig {
const p = config.params ?? {};
return {
...config,
id: `dotnet-build:${config.id}`,
name: `dotnet build (${p.project || ""})`,
kind: "shell",
args: ["build", p.project || "", "--configuration", "Debug", ...(p.framework ? ["--framework", p.framework] : [])],
cwd: useProject.getState().project?.root ?? null,
env: {},
params: {},
isTest: false,
debugAdapter: null,
beforeLaunch: [],
emulateTerminal: false,
stdinFile: undefined,
};
}
export const dotnetProjectType: RunConfigTypeContribution = {
id: "dotnet",
label: ".NET Project",
icon: "file-csharp",
description: "Run a .NET project with a launch profile",
debugAdapter: "netcoredbg",
fields: [
{
key: "project",
label: ".NET project",
mono: true,
required: true,
suggestions: (configs) => [
...new Set(
configs.filter((c) => c.kind === "dotnet" || c.kind === "dotnet-test").map((c) => c.params?.project || ""),
),
],
},
{
key: "framework",
label: "Target framework",
mono: true,
suggestions: (_configs, p) => (p.frameworks || "").split(";").filter(Boolean),
},
{
key: "launchProfile",
label: "Launch profile",
mono: true,
hint: "Empty disables launch profiles",
suggestions: (_configs, p) => {
try {
return Object.keys(JSON.parse(p.profiles || "{}"));
} catch {
return [];
}
},
},
{ key: "programArgs", label: "Program arguments", mono: true, hint: "Empty uses the launch profile's arguments" },
{
key: "applicationUrl",
label: "Application URL",
control: "output",
value: (p) => profile(p).applicationUrl || "",
},
{
key: "profileEnvironment",
label: "Profile environment variables",
control: "output",
value: (p) =>
Object.entries(profile(p).environmentVariables ?? {})
.map(([k, v]) => `${k}=${v}`)
.join("; "),
hint: "Environment variables below override the profile",
},
],
commandLine: (p) => dotnetCommand(p),
async prepareLaunch(config) {
const resolved = await call(commands.runDotnetResolve(config, false));
const p = resolved.params ?? {};
// Materialize the profile so explicit environment/cwd edits also apply on older SDKs.
const args = parseArgs(p.programArgs?.trim() ? p.programArgs : p.profileArgs || "");
return {
...resolved,
args: [
...dotnetCommand({ ...p, launchProfile: "", programArgs: "" }).args,
...(args.length ? ["--", ...args] : []),
],
};
},
};
export const dotnetTestType: RunConfigTypeContribution = {
id: "dotnet-test",
label: "dotnet test",
icon: "file-csharp",
description: "Run .NET tests",
fields: [...dotnetProjectType.fields.slice(0, 2), { key: "programArgs", label: "Test arguments", mono: true }],
commandLine(p) {
const line = dotnetCommand({ ...p, programArgs: "" }, true);
return { ...line, args: [...line.args, ...parseArgs(p.programArgs || "")] };
},
async prepareLaunch(config) {
const resolved = await call(commands.runDotnetResolve(config, false));
return { ...resolved, ...dotnetTestType.commandLine(resolved.params ?? {}) };
},
};
-8
Переглянути файл
@@ -22,8 +22,6 @@ import { useProject } from "@/platform/project";
import { tomcatType } from "./tomcat";
import { goBuildType, goTestType } from "./goTypes";
import { dotnetProjectType, dotnetTestType } from "./dotnetTypes";
export const COMPOUND = "compound";
const on = (v: string | undefined) => v === "true";
@@ -398,8 +396,6 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [
maven,
godot,
pytest,
dotnetProjectType,
dotnetTestType,
goBuildType,
goTestType,
applicationType,
@@ -448,10 +444,6 @@ export function withParams(config: RunConfig, params: Record<string, string>, ty
if (!line) return { ...rest, params, command: "", args: [] };
return {
...rest,
...(config.kind === "dotnet" && config.beforeLaunch === undefined
? { beforeLaunch: [{ kind: "dotnetBuild", target: "" }] }
: {}),
...(config.kind === "dotnet-test" ? { isTest: true } : {}),
params: params.goKind ? { ...params, programArgv: JSON.stringify(parseArgs(params.programArgs ?? "")) } : params,
...(config.kind === "go-test" && !config.id.startsWith("template:") ? { kind: "go" } : {}),
...(params.goKind ? { isTest: params.goKind === "test" } : {}),
-1
Переглянути файл
@@ -45,7 +45,6 @@ describe("inspections tree", () => {
it("groups servers by language with seen and configured codes, built-ins by category", () => {
expect(tree.map((g) => g.name)).toEqual([
"Cargo",
"General",
"JavaScript",
"Other",
+2 -1
Переглянути файл
@@ -31,6 +31,7 @@ import {
type PaneLayout,
type TerminalTab,
} from "./store";
import { pasteTerminalClipboard } from "./paste";
import { TerminalFindBar } from "./FindBar";
import styles from "./Terminal.module.css";
@@ -102,7 +103,7 @@ function paneMenu(e: MouseEvent, key: string) {
{
label: "Paste",
shortcut: mac ? "⌘V" : "Ctrl+Shift+V",
run: () => void session.pasteClipboard(),
run: () => void pasteTerminalClipboard((text) => session.paste(text)),
},
{ label: "Select All", run: () => session.term.selectAll() },
{ kind: "separator" },
+2 -286
Переглянути файл
@@ -1,16 +1,9 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Terminal } from "@xterm/xterm";
import { commands } from "@/platform/ipc";
import { installTerminalPaste, pasteTerminalClipboard, type RemotePasteTarget } from "./paste";
import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
const notify = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify }) }));
beforeEach(() => {
vi.stubGlobal("__TAURI_INTERNALS__", {});
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
notify.mockClear();
});
beforeEach(() => vi.stubGlobal("__TAURI_INTERNALS__", {}));
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -85,280 +78,3 @@ it("passes recovered multiline paths through xterm bracketed paste", async () =>
term.dispose();
}
});
function image(buffer: () => Promise<ArrayBuffer> = async () => new Uint8Array([1, 2]).buffer, size = 2): Blob {
return { type: "image/png", size, arrayBuffer: buffer } as Blob;
}
function imageEvent(blob: Blob, text = "") {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => text, files: [blob], types: ["Files"] },
});
return event;
}
function remoteTarget(current = () => true): RemotePasteTarget {
return { id: 42 as RemotePasteTarget["id"], supported: true, current };
}
it.each(["event", "menu"])("rejects oversized %s images before reading or uploading", async (route) => {
const read = vi.fn(async () => new ArrayBuffer(0));
const blob = image(read, 20 * 1024 * 1024 + 1);
const store = vi.spyOn(commands, "termStoreImage");
const paste = vi.fn();
const host = document.createElement("div");
const remove = installTerminalPaste(host, paste, () => remoteTarget());
if (route === "event") {
const event = imageEvent(blob);
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
} else {
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType: async () => blob }] },
});
await pasteTerminalClipboard(paste, () => remoteTarget());
}
await vi.waitFor(() =>
expect(notify).toHaveBeenCalledWith({
level: "error",
title: "Cannot paste image",
body: "Image is too large to paste (limit 20 MB).",
}),
);
expect(read).not.toHaveBeenCalled();
expect(store).not.toHaveBeenCalled();
expect(paste).not.toHaveBeenCalled();
remove();
});
it("allows images at the size limit", async () => {
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.dispatchEvent(imageEvent(image(undefined, 20 * 1024 * 1024)));
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/remote/image.png'"));
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(notify).not.toHaveBeenCalled();
remove();
});
it("claims remote image events before xterm and pastes a quoted path only after upload", async () => {
let finish!: (result: { status: "ok"; data: string }) => void;
const store = vi.spyOn(commands, "termStoreImage").mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.addEventListener("paste", () => paste("xterm"));
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png"));
expect(paste).not.toHaveBeenCalled();
finish({ status: "ok", data: "/tmp/a'b c.png" });
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/tmp/a'\\''b c.png'"));
remove();
});
it("reads an image from the explicit paste menu after text and file recovery", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/stale.png"] });
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
const getType = vi.fn(async () => image());
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType }] },
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(getType).toHaveBeenCalledWith("image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
});
it("recovers remote menu file paths when image clipboard reading is unavailable", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/file.txt"] });
const store = vi.spyOn(commands, "termStoreImage");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "" } });
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(paste).toHaveBeenCalledWith("/local/file.txt");
expect(store).not.toHaveBeenCalled();
});
it("uploads a menu image even if reading clipboard text is rejected", async () => {
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: {
readText: async () => {
throw new Error("no text");
},
read: async () => [{ types: ["image/png"], getType: async () => image() }],
},
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
expect(notify).not.toHaveBeenCalled();
});
it("uploads image events instead of recovering a local image path", async () => {
const list = vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/photo.png"] });
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/photo.png" });
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/remote/photo.png'"));
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(list).not.toHaveBeenCalled();
remove();
});
it("does not upload a menu image when the target changes while reading", async () => {
let valid = true;
let finish!: (value: Blob) => void;
const getType = vi.fn(
() =>
new Promise<Blob>((resolve) => {
finish = resolve;
}),
);
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType }] },
});
const store = vi.spyOn(commands, "termStoreImage");
const paste = vi.fn();
const pending = pasteTerminalClipboard(paste, () => remoteTarget(() => valid));
await vi.waitFor(() => expect(getType).toHaveBeenCalled());
valid = false;
finish(image());
await pending;
expect(store).not.toHaveBeenCalled();
expect(paste).not.toHaveBeenCalled();
});
it.each(["read", "upload", "unsupported"])("reports image %s failure without pasting", async (failure) => {
const store = vi.spyOn(commands, "termStoreImage").mockRejectedValue(new Error("upload failed"));
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => ({ ...remoteTarget(), supported: failure !== "unsupported" }));
host.dispatchEvent(
imageEvent(
image(
failure === "read"
? async () => {
throw new Error("read failed");
}
: undefined,
),
),
);
await vi.waitFor(() => expect(notify).toHaveBeenCalled());
expect(paste).not.toHaveBeenCalled();
if (failure !== "upload") expect(store).not.toHaveBeenCalled();
remove();
});
it.each(["read", "upload"])("ignores an image after its target is replaced during %s", async (stage) => {
let valid = true;
let finishRead!: (value: ArrayBuffer) => void;
let finishUpload!: (value: { status: "ok"; data: string }) => void;
const store = vi.spyOn(commands, "termStoreImage").mockImplementation(
() =>
new Promise((resolve) => {
finishUpload = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget(() => valid));
host.dispatchEvent(
imageEvent(
image(
() =>
new Promise((resolve) => {
finishRead = resolve;
}),
),
),
);
await vi.waitFor(() => expect(finishRead).toBeDefined());
if (stage === "upload") {
finishRead(new Uint8Array([1]).buffer);
await vi.waitFor(() => expect(store).toHaveBeenCalled());
}
valid = false;
if (stage === "read") finishRead(new Uint8Array([1]).buffer);
else finishUpload({ status: "ok", data: "/remote/image.png" });
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(paste).not.toHaveBeenCalled();
if (stage === "read") expect(store).not.toHaveBeenCalled();
remove();
});
it("does not paste after the event handler is disposed during upload", async () => {
let finish!: (value: { status: "ok"; data: string }) => void;
const store = vi.spyOn(commands, "termStoreImage").mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.dispatchEvent(imageEvent(image()));
await vi.waitFor(() => expect(store).toHaveBeenCalled());
remove();
finish({ status: "ok", data: "/remote/image.png" });
await Promise.resolve();
await Promise.resolve();
expect(paste).not.toHaveBeenCalled();
});
it("keeps local image-only file recovery unchanged", async () => {
const list = vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/photo.png"] });
const store = vi.spyOn(commands, "termStoreImage");
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste);
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("/local/photo.png"));
expect(list).toHaveBeenCalled();
expect(store).not.toHaveBeenCalled();
remove();
});
it("leaves local image and remote text events to existing paste handlers", () => {
const store = vi.spyOn(commands, "termStoreImage");
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste, () => remoteTarget());
const event = imageEvent(image(), "plain");
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
expect(store).not.toHaveBeenCalled();
remove();
const local = installTerminalPaste(host, paste);
const text = imageEvent(image(), "plain");
host.dispatchEvent(text);
expect(text.defaultPrevented).toBe(false);
expect(store).not.toHaveBeenCalled();
local();
});
+6 -85
Переглянути файл
@@ -1,50 +1,8 @@
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
import { call, commands, type TerminalId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
export interface RemotePasteTarget {
id: TerminalId;
supported: boolean;
current: () => boolean;
}
type Target = () => RemotePasteTarget | null;
const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
async function pasteImage(image: Blob, target: RemotePasteTarget, paste: (text: string) => void) {
try {
if (image.size > MAX_IMAGE_BYTES) throw new Error(tx`Image is too large to paste (limit ${20} MB).`);
const data = Array.from(new Uint8Array(await image.arrayBuffer()));
if (!target.current()) return;
if (!target.supported) throw new Error(tx("Remote server does not support image paste."));
const path = await call(commands.termStoreImage(target.id, data, image.type));
if (target.current()) paste(`'${path.replaceAll("'", "'\\''")}'`);
} catch (error) {
if (target.current())
notifications().notify({
level: "error",
title: tx("Cannot paste image"),
body: error instanceof Error ? error.message : String(error),
});
}
}
export function installTerminalPaste(host: HTMLElement, paste: (text: string) => void, getTarget?: Target): () => void {
export function installTerminalPaste(host: HTMLElement, paste: (text: string) => void): () => void {
let alive = true;
const onPaste = (event: ClipboardEvent) => {
const transfer = event.clipboardData;
const target = getTarget?.();
if (!event.defaultPrevented && target && transfer && !transfer.getData("text/plain")) {
const image = Array.from(transfer.files).find((file) => file.type.startsWith("image/"));
if (image) {
event.preventDefault();
event.stopImmediatePropagation();
void pasteImage(image, { ...target, current: () => alive && target.current() }, paste);
return;
}
}
pasteClipboardFiles(event, (text) => {
if (alive) paste(text);
});
@@ -56,48 +14,11 @@ export function installTerminalPaste(host: HTMLElement, paste: (text: string) =>
};
}
export async function pasteTerminalClipboard(paste: (text: string) => void, getTarget?: Target) {
const target = getTarget?.();
export async function pasteTerminalClipboard(paste: (text: string) => void) {
try {
// Native paste preserves clipboard blobs where Clipboard.read() is unavailable.
if (target && document.queryCommandSupported?.("paste") && document.execCommand("paste")) return;
const images =
target && navigator.clipboard?.read
? navigator.clipboard.read().then(
(items) => ({ items }),
(error: unknown) => ({ error }),
)
: null;
const text = target ? ((await navigator.clipboard?.readText().catch(() => "")) ?? "") : await readClipboardText();
if (target && !target.current()) return;
if (text) {
paste(text);
return;
}
if (!target) return;
if (images) {
const result = await images;
if ("error" in result) throw result.error;
if (!target.current()) return;
for (const item of result.items) {
const mime = item.types.find((type) => type.startsWith("image/"));
if (mime) {
const image = await item.getType(mime);
if (target.current()) await pasteImage(image, target, paste);
return;
}
}
}
const paths = await readClipboardText();
if (!target.current()) return;
if (paths) paste(paths);
else if (!images) throw new Error(tx("Clipboard image reading is unavailable."));
} catch (error) {
if (target?.current())
notifications().notify({
level: "error",
title: tx("Cannot paste image"),
body: error instanceof Error ? error.message : String(error),
});
const text = await readClipboardText();
if (text) paste(text);
} catch {
/* Clipboard access may be denied. */
}
}
+2 -23
Переглянути файл
@@ -17,7 +17,6 @@ import { ImeCommitGate } from "./imeCommit";
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
import { splitCommandLine } from "@/platform/commandLine";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings";
import { editorPrefs } from "@/platform/editorSettings";
import {
@@ -279,7 +278,7 @@ export class TerminalSession {
}),
);
this.disposables.push(
{ dispose: installTerminalPaste(this.host, (text) => this.paste(text), this.remotePasteTarget) },
{ dispose: installTerminalPaste(this.host, (text) => this.paste(text)) },
{ dispose: installTerminalDrop(this.host, (text) => this.paste(text)) },
);
this.host.addEventListener("mousedown", this.onMiddleClick);
@@ -288,29 +287,9 @@ export class TerminalSession {
private onMiddleClick = (e: MouseEvent) => {
if (e.button !== 1 || !workflowSettings().terminal.pasteOnMiddleClick) return;
e.preventDefault();
void this.pasteClipboard();
void pasteTerminalClipboard((text) => this.paste(text));
};
private remotePasteTarget = () => {
const remote = useRemote.getState().session;
const id = this.ptyId;
if (!remote || id === null || this.disposed) return null;
const generation = this.generation;
return {
id,
supported: remote.commands.includes("term_store_image"),
current: () =>
!this.disposed &&
this.ptyId === id &&
this.generation === generation &&
useRemote.getState().session === remote,
};
};
pasteClipboard() {
if (this.remotePasteTarget()) this.focus();
return pasteTerminalClipboard((text) => this.paste(text), this.remotePasteTarget);
}
/** Applies Settings › Tools › Terminal changes to a live session. */
applySettings(t: TerminalSettingsValid) {
const font = fontFor(t);
+1 -25
Переглянути файл
@@ -5470,29 +5470,5 @@
"Build arguments": "构建参数",
"CMake default": "CMake 默认",
"Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "包含空格的参数请加引号。构建参数传给 cmake --build;原生构建工具参数前请加 --。",
"CMake profile {0}": "CMake 配置 {0}",
".NET Project": ".NET 项目",
".NET project": ".NET 项目",
"Run a .NET project with a launch profile": "使用启动配置运行 .NET 项目",
"Target framework": "目标框架",
"Launch profile": "启动配置",
"Empty disables launch profiles": "留空则禁用启动配置",
"Empty uses the launch profile's arguments": "留空则使用启动配置中的参数",
"Application URL": "应用 URL",
"Profile environment variables": "启动配置中的环境变量",
"Environment variables below override the profile": "下方的环境变量会覆盖启动配置中的值",
"Build .NET project": "构建 .NET 项目",
"Run .NET tests": "运行 .NET 测试",
"Test arguments": "测试参数",
"netcoredbg is not installed": "未安装 netcoredbg",
".NET Project requires the local machine": ".NET 项目需要在本机运行",
"Select a .NET project": "请选择 .NET 项目",
"Invalid .NET project path": ".NET 项目路径无效",
".NET launch profile '{profile_name}' is missing or is not a Project profile": ".NET 启动配置“{profile_name}”不存在或不是 Project 类型",
".NET output resolution timed out": ".NET 构建产物路径查询超时",
".NET build output is missing; run dotnet build before debugging": ".NET 构建产物不存在,请在调试前运行 dotnet build",
"Cannot paste image": "无法粘贴图片",
"Remote server does not support image paste.": "远程服务器不支持粘贴图片。",
"Clipboard image reading is unavailable.": "无法读取剪贴板图片。",
"Image is too large to paste (limit {limit} MB).": "图片过大,无法粘贴(上限 {limit} MB)。"
"CMake profile {0}": "CMake 配置 {0}"
}
+1 -18
Переглянути файл
@@ -79,8 +79,6 @@ const BUILT_AT_RUNTIME = new Set<string>([]);
/** Text that stays as written in every locale: names, code, formats, shortcuts. */
const UNTRANSLATED = new Set<string>([
"dotnet test",
"netcoredbg (.NET)",
// Product names
"Cargo",
"CMake",
@@ -488,21 +486,6 @@ function scanTypeScript(): Scan {
return { translated, literals, untranslatable, spliced };
}
/** Read strings without letting a Rust character literal open a string match. */
function backendLiterals(source: string): string[] {
const out: string[] = [];
for (const m of source.matchAll(/'(?:\\.|[^'\\\r\n])'|"((?:[^"\\]|\\.)*)"/g)) {
if (m[1] !== undefined) out.push(m[1]);
}
return out;
}
it("reads backend messages after quote character literals", () => {
expect(
backendLiterals(`let quote = '"'; let message = "Select a .NET project"; let detail = "Expected 'x'";`),
).toEqual(["Select a .NET project", "Expected 'x'"]);
});
/** String literals of the Rust crates and language definitions (backend messages). */
function scanBackend(literals: Set<string>) {
const files = [
@@ -511,7 +494,7 @@ function scanBackend(literals: Set<string>) {
...walk(`${ROOT}languages`, (p) => p.endsWith(".toml")),
];
for (const file of files)
for (const literal of backendLiterals(readFileSync(file, "utf8"))) literals.add(shape(literal));
for (const m of readFileSync(file, "utf8").matchAll(/"((?:[^"\\]|\\.)*)"/g)) literals.add(shape(m[1]!));
}
/** Text that needs no translation: no words, a path / glob / option, or listed in `UNTRANSLATED`. */