Compare commits

..
70 changed files with 253 additions and 1063 deletions

No files matched your search

Generated
-1
View File
@@ -4253,7 +4253,6 @@ dependencies = [
name = "ide-core"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
+8 -56
View File
@@ -1008,7 +1008,12 @@ pub fn build_for_launches(
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
maven_launch_projects(root, m, module, test)
.iter()
.flat_map(|p| {
launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module)
})
.collect()
} else {
launch_class_dirs(plan.system, module, test)
}
@@ -1016,60 +1021,6 @@ pub fn build_for_launches(
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
}
/// Maven output directories for a launch, including directories that have yet to be created.
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
maven_launch_projects(root, model, module, test)
.into_iter()
.flat_map(|p| {
let dir = subdir(root, &p.dir);
maven_output_dirs(&dir, test && dir == module)
})
.collect()
}
/// The class directories of a Maven launch that must hold classes after its build: those of
/// the launch projects with sources in a conventional JVM source root. One that is missing
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
fn has_sources(dir: &Path, depth: u32) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let p = e.path();
if p.is_dir() {
depth > 0 && has_sources(&p, depth - 1)
} else {
// A package-info.java without annotations compiles to nothing.
p.file_name() != Some("package-info.java".as_ref())
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
}
})
}
let compiles = |dir: &Path, set: &str| {
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
};
let Some(m) = &model.maven else { return Vec::new() };
let mut dirs = Vec::new();
for p in maven_launch_projects(root, m, module, test) {
let dir = subdir(root, &p.dir);
if test && dir == module && compiles(&dir, "test") {
dirs.push(subdir(&dir, "target/test-classes"));
}
if compiles(&dir, "main") {
dirs.push(subdir(&dir, "target/classes"));
}
}
dirs
}
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if test {
dirs.push(subdir(module, "target/test-classes"));
}
dirs.push(subdir(module, "target/classes"));
dirs
}
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
let sets: &[&str] = if test { &["test", "main"] } else { &["main"] };
let dirs: Vec<PathBuf> = match system {
@@ -1080,7 +1031,8 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven => maven_output_dirs(module, test),
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
-1
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
-122
View File
@@ -1,122 +0,0 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
-2
View File
@@ -12,7 +12,6 @@ pub mod ids;
pub mod ignored;
pub mod input;
pub mod inspection_settings;
pub mod ipc_bytes;
pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
@@ -38,7 +37,6 @@ pub mod wsl;
pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath;
pub use text::*;
pub use tokio_util::sync::CancellationToken;
+2 -2
View File
@@ -1,7 +1,7 @@
use super::Channel;
use crate::{Host, Project};
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcBytes, RequestId};
use ide_core::{IdeError, IdeResult, RequestId};
use ide_vfs::FileEntry;
use ide_workspace::DeletionUndo;
use std::path::{Path, PathBuf};
@@ -209,7 +209,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()>
}
#[command(trust = always)]
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: IpcBytes) -> IdeResult<()> {
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
let project = host.project(window).ok();
host.blocking(move || {
ide_vfs::create_file_bytes(&path, &data)?;
+8 -267
View File
@@ -6,20 +6,14 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct Outputs {
fingerprint: Option<LaunchFingerprint>,
pub snapshot: PathBuf,
pub originals: Vec<PathBuf>,
/// Live output and snapshot metadata at publication. Older records may hold an
/// incomplete copy and are rebuilt once (#5404).
#[serde(default)]
output_stamps: Option<Vec<OutputStamp>>,
#[serde(skip)]
pub failure: Option<String>,
/// Whether this result replaces jdtls diagnostics with a clean Maven build or a
@@ -29,93 +23,12 @@ pub(super) struct Outputs {
}
impl Outputs {
fn reusable(
&self,
fingerprint: &Option<LaunchFingerprint>,
snapshots: &Path,
output_dirs: impl Iterator<Item = PathBuf>,
cancel: &CancellationToken,
) -> bool {
fn reusable(&self, fingerprint: &Option<LaunchFingerprint>, snapshots: &Path) -> bool {
fingerprint.is_some()
&& self.fingerprint == *fingerprint
&& self.snapshot.parent() == Some(snapshots)
&& !self.originals.is_empty()
&& self.output_stamps.as_ref().is_some_and(|stamps| {
stamps.len() == self.originals.len()
&& output_dirs.eq(self.originals.iter().cloned())
&& self.originals.iter().zip(stamps).enumerate().all(|(i, (dir, stamp))| {
Contents::scan(dir, cancel).is_some_and(|live| live.stamp() == stamp.live)
&& Contents::scan(&self.snapshot.join(i.to_string()), cancel)
.is_some_and(|copy| copy.class_stamp() == stamp.snapshot_classes)
})
})
}
}
#[derive(Debug, Serialize, Deserialize)]
struct OutputStamp {
live: u64,
// A launched app may write non-class files under its snapshot classpath root.
snapshot_classes: u64,
}
/// Relative paths, sizes and mtimes are enough to detect ordinary compiler rewrites
/// without reading class or resource bytes.
#[derive(Debug, PartialEq, Eq)]
struct Contents(Vec<(PathBuf, u64, SystemTime)>);
impl Contents {
fn scan(root: &Path, cancel: &CancellationToken) -> Option<Self> {
if !fs::metadata(root).ok()?.is_dir() {
return None;
}
let mut files = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return None;
}
for entry in fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let meta = entry.metadata().ok()?;
let path = entry.path();
if meta.is_dir() {
pending.push(path);
} else {
files.push((path.strip_prefix(root).ok()?.to_path_buf(), meta.len(), meta.modified().ok()?));
}
}
}
files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
Some(Self(files))
}
fn stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn classes(&self) -> impl Iterator<Item = &(PathBuf, u64, SystemTime)> {
self.0.iter().filter(|(path, _, _)| path.extension().is_some_and(|ext| ext == "class"))
}
fn class_stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
for file in self.classes() {
file.hash(&mut hasher);
}
hasher.finish()
}
fn matches_copy(&self, copy: &Self) -> bool {
// Copying preserves relative paths and sizes. Each tree has its own mtimes.
self.0.len() == copy.0.len()
&& self
.0
.iter()
.zip(&copy.0)
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
&& (0..self.originals.len()).all(|i| self.snapshot.join(i.to_string()).is_dir())
}
}
@@ -367,23 +280,13 @@ impl Session {
}
if let Some(outputs) = previous.as_ref()
&& policy != BuildPolicy::Rebuild
&& let Some(maven) = &model.maven
&& outputs.reusable(
&before,
&snapshots,
compile::maven_launch_output_dirs(root, maven, module, test).into_iter().filter(|dir| dir.is_dir()),
cancel,
)
&& !cancel.is_cancelled()
&& outputs.reusable(&before, &snapshots)
{
tracing::info!(module = %module.display(), test, "Reusing Maven launch snapshot");
let mut outputs = previous.unwrap();
outputs.authoritative = true;
return Ok(Ok(outputs));
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Retain a non-reusable record even on failure, so removing the final mixed
// source still delegates to Maven to clean its old classes on the next launch.
fs::create_dir_all(record.parent().unwrap())?;
@@ -414,7 +317,6 @@ impl Session {
let snapshot = tempfile::Builder::new().prefix("launch-").tempdir_in(&snapshots)?.keep();
// Retain every new snapshot even if copying or publishing its record fails.
self.unreferenced.push(snapshot.clone());
let scanned: Vec<_> = originals.iter().map(|dir| Contents::scan(dir, cancel)).collect();
for (i, source) in originals.iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -425,43 +327,8 @@ impl Session {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// The fingerprint covers build inputs only. Another build (an external `mvn`) can
// rewrite the outputs meanwhile without changing them (#5404): record the snapshot
// only if the outputs held still through the copy and hold every module's classes.
let copied: Option<Vec<Contents>> =
(0..originals.len()).map(|i| Contents::scan(&snapshot.join(i.to_string()), cancel)).collect();
let output_stamps: Option<Vec<OutputStamp>> = copied.as_ref().and_then(|copied| {
originals
.iter()
.zip(&scanned)
.zip(copied)
.map(|((dir, before), copy)| {
let before = before.as_ref()?;
let live = Contents::scan(dir, cancel)?;
(live == *before && before.matches_copy(copy))
.then(|| OutputStamp { live: live.stamp(), snapshot_classes: copy.class_stamp() })
})
.collect()
});
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let consistent = output_stamps.is_some();
let complete = copied.as_ref().is_some_and(|copied| {
compile::launch_required_class_dirs(root, model, &pending.module, test).iter().all(|dir| {
originals.iter().position(|o| o == dir).is_some_and(|i| copied[i].classes().next().is_some())
})
});
if failure.is_none() && !(consistent && complete) {
tracing::warn!(
module = %pending.module.display(),
consistent,
complete,
"Maven outputs changed or lacked classes while copying the launch snapshot; it will not be reused"
);
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, output_stamps, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after && consistent && complete {
let mut outputs = Outputs { fingerprint: None, snapshot, originals, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after {
outputs.fingerprint = pending.before;
write_record(&pending.record, &outputs)?;
self.unreferenced.retain(|path| path != &outputs.snapshot);
@@ -855,7 +722,7 @@ mod tests {
assert!(reused.authoritative);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
let rebuilt = session
.build(
root,
@@ -868,7 +735,6 @@ mod tests {
.unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
assert!(rebuilt.authoritative);
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "first");
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert_eq!(calls.lines().count(), 2);
assert!(calls.lines().last().unwrap().contains("clean"));
@@ -890,6 +756,8 @@ mod tests {
let second = build().unwrap();
assert_eq!(snapshot, second.snapshot);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
assert_eq!(snapshot, build().unwrap().snapshot);
assert_eq!(fs::read_to_string(snapshot.join("0/Main.class")).unwrap(), "first");
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
let updated = build().unwrap();
@@ -1025,7 +893,6 @@ mod tests {
fingerprint: None,
snapshot: retained.clone(),
originals: Vec::new(),
output_stamps: None,
failure: None,
authoritative: false,
};
@@ -1086,132 +953,6 @@ mod tests {
drop(session);
assert!(!outputs.snapshot.exists());
}
/// An external `mvn` removes a dependency module's classes (`clean`) while this launch
/// builds and copies the outputs, and compiles them again only after the copy (#5404).
/// The sources never change, so only the copied outputs can tell the snapshot is broken.
fn assert_outputs_cleaned_by_an_external_build_are_not_reused(clean: &str) {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = reactor_fixture(root);
let script = root.join("mvnw");
let mut text = fs::read_to_string(&script).unwrap();
text.push_str("echo resource > lib/target/classes/app.yml\n");
text.push_str(&format!("if [ -f external-build ]; then {clean}; fi\n"));
fs::write(&script, text).unwrap();
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let a = root.join("a");
fs::write(root.join("external-build"), "").unwrap();
let first = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert!(!first.snapshot.join("1/Main.class").exists());
// The external build finished: the classes are complete again, sources unchanged.
fs::remove_file(root.join("external-build")).unwrap();
fs::create_dir_all(root.join("lib/target/classes")).unwrap();
fs::write(root.join("lib/target/classes/Main.class"), "lib").unwrap();
let second = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(second.snapshot, first.snapshot, "the incomplete snapshot must not be reused");
assert_eq!(fs::read_to_string(second.snapshot.join("1/Main.class")).unwrap(), "lib");
assert_eq!(calls(root).len(), 2);
let third = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(third.snapshot, second.snapshot, "a complete snapshot is reused");
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_snapshot_of_classes_cleaned_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm lib/target/classes/Main.class");
}
#[test]
fn a_snapshot_missing_an_output_directory_removed_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm -r lib/target/classes");
}
#[test]
fn a_partially_recompiled_dependency_snapshot_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused(
"echo other > lib/target/classes/Other.class; rm lib/target/classes/Main.class",
);
}
#[test]
fn a_new_output_directory_invalidates_a_test_launch_snapshot() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let mut build =
|| session.build(root, &model, root, BuildOptions { test: true, ..Default::default() }, None, &cancel);
let first = build().unwrap();
assert_eq!(first.originals, [root.join("target/classes")]);
fs::create_dir_all(root.join("target/test-classes")).unwrap();
fs::write(root.join("target/test-classes/GeneratedTest.class"), "test").unwrap();
let second = build().unwrap();
assert_ne!(first.snapshot, second.snapshot);
assert!(second.snapshot.join("0/GeneratedTest.class").is_file());
assert_eq!(second.snapshot, build().unwrap().snapshot);
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_record_without_output_stamps_is_rebuilt_once() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
// A count-only record may still hold a partial copy.
let record = root.join("cache/java-launch/records/main.json");
let mut json: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
json.as_object_mut().unwrap().remove("output_stamps").unwrap();
json["contents"] = serde_json::json!([{ "files": 1, "bytes": 5, "classes": 1 }]);
fs::write(&record, serde_json::to_vec(&json).unwrap()).unwrap();
let rebuilt = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(reused.snapshot, rebuilt.snapshot);
// A file the launched app wrote under its classpath root keeps the snapshot.
fs::write(reused.snapshot.join("0/app.log"), "log").unwrap();
let kept = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(kept.snapshot, reused.snapshot);
// A snapshot that lost a class since it was recorded is rebuilt.
fs::remove_file(reused.snapshot.join("0/Main.class")).unwrap();
let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(again.snapshot, reused.snapshot);
assert_eq!(calls(root).len(), 3);
}
#[test]
fn contents_tell_a_rewritten_output_from_its_copy() {
let dir = tempfile::tempdir().unwrap();
let classes = dir.path().join("classes");
let cancel = CancellationToken::new();
let scan = |path: &Path| Contents::scan(path, &cancel);
fs::create_dir_all(classes.join("pkg")).unwrap();
fs::write(classes.join("pkg/A.class"), "a").unwrap();
fs::write(classes.join("app.yml"), "yml").unwrap();
let class = fs::File::options().write(true).open(classes.join("pkg/A.class")).unwrap();
let resource = fs::File::options().write(true).open(classes.join("app.yml")).unwrap();
let before = SystemTime::now();
resource.set_modified(before + std::time::Duration::from_secs(10)).unwrap();
let contents = scan(&classes).unwrap();
ide_vfs::copy(&classes, &dir.path().join("copy")).unwrap();
assert!(contents.matches_copy(&scan(&dir.path().join("copy")).unwrap()));
// A rewrite can preserve both the class file's size and the tree's newest mtime.
class.set_modified(before + std::time::Duration::from_secs(1)).unwrap();
let rewritten = scan(&classes).unwrap();
assert!(contents.matches_copy(&rewritten));
assert_ne!(rewritten.stamp(), contents.stamp());
fs::rename(classes.join("pkg/A.class"), classes.join("pkg/B.class")).unwrap();
let renamed = scan(&classes).unwrap();
assert!(!rewritten.matches_copy(&renamed));
assert_ne!(renamed.stamp(), rewritten.stamp());
assert!(scan(&dir.path().join("missing")).is_none());
}
#[test]
fn deleting_the_last_mixed_source_keeps_maven_delegation_after_failure() {
let dir = tempfile::tempdir().unwrap();
+4 -5
View File
@@ -1,7 +1,7 @@
use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, IpcBytes, TerminalId};
use ide_core::{IdeResult, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
mod images;
@@ -9,7 +9,7 @@ mod images;
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
#[command(trust = always)]
pub async fn term_store_image(host: &Host, id: TerminalId, data: IpcBytes, mime: String) -> IdeResult<String> {
pub async fn term_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)"));
}
@@ -201,11 +201,10 @@ mod tests {
project_environment: false,
});
let id = TerminalId::next();
let error =
term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1].into(), "image/png".into()).await.unwrap_err();
let error = term_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 = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES].into(), "image/png".into()).await.unwrap_err();
let error = term_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());
}
+1 -2
View File
@@ -27,8 +27,7 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
pub const PROTOCOL_VERSION: u32 = 3;
pub const PROTOCOL_VERSION: u32 = 2;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
-70
View File
@@ -1,70 +0,0 @@
//! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers.
use ide_core::{IpcBytes, NullSink};
use ide_host::rpc::{self, Dispatcher, Invoke};
use ide_host::{Host, HostConfig};
use ide_jsonrpc::{Handler, Peer};
use serde_json::{Value, json};
use std::sync::{Arc, OnceLock};
struct Client;
impl Handler for Client {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
async fn connect(base: &std::path::Path) -> Peer {
let host = Arc::new(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(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host, Dispatcher::standard(), Arc::new(OnceLock::new()), sr, sw));
let (cr, cw) = tokio::io::split(client_io);
Peer::connect(cr, cw, Arc::new(Client))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_bytes_cross_the_protocol_as_base64() {
let tmp = tempfile::tempdir().unwrap();
let peer = connect(tmp.path()).await;
let bytes: Vec<u8> = (0..=255).cycle().take(3 * 1024 * 1024 + 1).collect();
let path = tmp.path().join("image.bin");
let args = json!({ "path": path, "data": IpcBytes(bytes.clone()) });
assert!(args["data"].is_string());
// Measure the envelope separately so the assertion is independent of the temp directory.
let envelope = serde_json::to_vec(&json!({ "path": path, "data": "" })).unwrap();
let body = serde_json::to_vec(&args).unwrap();
assert_eq!(body.len(), envelope.len() + bytes.len().div_ceil(3) * 4);
let call = Invoke { window: "main".into(), cmd: "fs_create_file_bytes".into(), args };
peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_array_of_numbers_is_not_accepted_as_bytes() {
let tmp = tempfile::tempdir().unwrap();
let peer = connect(tmp.path()).await;
let path = tmp.path().join("old.bin");
let call = Invoke {
window: "main".into(),
cmd: "fs_create_file_bytes".into(),
args: json!({ "path": path, "data": [1, 2, 3] }),
};
let error = peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap_err();
assert!(error.message.contains("argument data"), "{error:?}");
assert!(!path.exists());
}
+4 -8
View File
@@ -21,7 +21,7 @@ async fn storage_requires_a_registered_terminal() {
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1].into(), "image/png".into()).await.is_err());
assert!(ops::term::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
@@ -41,15 +41,11 @@ async fn storage_requires_a_registered_terminal() {
)
.unwrap();
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3].into(), mime.into()).await.unwrap();
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3], mime.into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
}
assert!(
ops::term::term_store_image(&host, terminal.id, vec![1].into(), "application/octet-stream".into())
.await
.is_err()
);
assert!(ops::term::term_store_image(&host, terminal.id, vec![1], "application/octet-stream".into()).await.is_err());
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::term_store_image(&host, terminal.id, vec![4].into(), "image/png".into()).await.is_err());
assert!(ops::term::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(), 3);
}
+1 -1
View File
@@ -64,7 +64,7 @@ JSON-RPC 2.0 with `Content-Length` framing (`ide-jsonrpc`), over the server's st
| notification `plugin` | server → client | `{ window, event }` from code plugins of the remote project |
| request `plugin_secret` | server → client | `{ plugin, name }` → `string` or `null`: a secret from the desktop's keychain |
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`; the desktop refuses a server that speaks another one. Change it when an existing command's argument or result changes shape. A binary argument is an `IpcBytes` (a base64 string in JSON, `string` in the bindings), never a `Vec<u8>`, which is an array of numbers about 3.6 times the size. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
## Routing commands
+1 -1
View File
@@ -64,7 +64,7 @@ openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <por
| 通知 `plugin` | 服务端 → 客户端 | `{ window, event }`:远程项目中代码插件发出的事件 |
| 请求 `plugin_secret` | 服务端 → 客户端 | `{ plugin, name }` → `string` 或 `null`:从桌面端钥匙串取密钥 |
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`;桌面端会拒绝使用其他版本协议的服务端。已有命令的参数或结果形态改变时要修改它。二进制参数使用 `IpcBytes`(JSON 中是 base64 字符串,绑定中是 `string`),不要用 `Vec<u8>`——它会变成体积约 3.6 倍的数字数组。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
## 命令路由
+3 -3
View File
@@ -11,11 +11,11 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
configurable: true,
value: { transformCallback: () => 1 },
});
const stored: { id: number; data: string; mime: string }[] = [];
const stored: { id: number; data: number[]; mime: string }[] = [];
const writes: string[] = [];
commands.termSpawn = async () => ({ status: "ok", data: { id: 838, title: "pwsh", pid: 1 } });
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
commands.termStoreImage = async (id: number, data: string, mime: string) => {
commands.termStoreImage = async (id: number, data: number[], mime: string) => {
stored.push({ id, data, mime });
return { status: "ok", data: "C:\\Temp\\a'b c\\image.png" };
};
@@ -47,6 +47,6 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
}
});
expect(observed.claimed).toBe(true);
expect(observed.stored).toEqual([{ id: 838, data: "iVBORw==", mime: "image/png" }]);
expect(observed.stored).toEqual([{ id: 838, data: [137, 80, 78, 71], mime: "image/png" }]);
expect(observed.writes).toEqual(["'C:\\Temp\\a''b c\\image.png'"]);
});
+2 -5
View File
@@ -680,7 +680,7 @@ export const commands = {
* `charset` (writes the BOM for `utf-8-bom` / UTF-16).
*/
fsCreateFile: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file", { path })),
fsCreateFileBytes: (path: string, data: IpcBytes) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
/** Moving to the trash can take a while (large trees): kept off the main thread. */
fsDelete: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_delete", { path })),
/** Moves an item to the Trash and returns the snapshot for Project View Undo. */
@@ -1823,7 +1823,7 @@ 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: IpcBytes, mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
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 })),
/**
* Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
@@ -8371,9 +8371,6 @@ export type InvalidateCachesOptions = {
buildCaches?: boolean,
};
/** A binary argument or result of an IPC command. */
export type IpcBytes = string;
/** A path field of an IPC type. */
export type IpcPath = string;
+2 -2
View File
@@ -172,10 +172,10 @@ it.each([
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: string } }) => void;
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
+7 -4
View File
@@ -1,9 +1,12 @@
import { toBase64 } from "@/platform/base64";
// Keep binary conversion off the editor thread, including for large clipboard images.
self.onmessage = async (event: MessageEvent<Blob>) => {
self.onmessage = async (event: MessageEvent<Blob | string>) => {
try {
self.postMessage({ data: toBase64(new Uint8Array(await event.data.arrayBuffer())) });
const source = event.data;
const data =
typeof source === "string"
? Array.from(atob(source.slice(source.indexOf(",") + 1)), (byte) => byte.charCodeAt(0))
: Array.from(new Uint8Array(await source.arrayBuffer()));
self.postMessage({ data });
} catch (error) {
self.postMessage({ error: String(error) });
}
+8 -22
View File
@@ -3,7 +3,6 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { history, undo } from "@codemirror/commands";
import { IpcError, commands } from "@/platform/ipc";
import { handleFileDrop } from "@/workbench/fileDrop";
import { imageName, imageTarget, markdownImages, relativeImagePath, saveImage } from "./markdownImages";
const views: EditorView[] = [];
@@ -39,7 +38,9 @@ describe("Markdown images", () => {
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
.mockResolvedValue(null);
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", "AP8=", create)).toBe("![](assets/photo-2.png)");
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", [0, 255], create)).toBe(
"![](assets/photo-2.png)",
);
expect(create.mock.calls.map(([path]) => path)).toEqual([
"/p/docs/assets/photo.png",
"/p/docs/assets/photo-1.png",
@@ -48,7 +49,7 @@ describe("Markdown images", () => {
});
it("does not retry permission failures", async () => {
const create = vi.fn().mockRejectedValue(new IpcError({ kind: "permissionDenied", message: "denied" }));
await expect(saveImage("/p/a.md", "assets", "a.png", "", create)).rejects.toThrow("denied");
await expect(saveImage("/p/a.md", "assets", "a.png", [], create)).rejects.toThrow("denied");
expect(create).toHaveBeenCalledTimes(1);
});
it("computes nested paths and encodes spaces and Markdown delimiters", () => {
@@ -81,10 +82,10 @@ describe("Markdown images", () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: string } }) => void;
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
@@ -97,31 +98,16 @@ describe("Markdown images", () => {
paste(editor, [new File(["png"], "image.png", { type: "image/png" })]);
await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1));
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
});
it("writes the base64 from a native image drop directly", async () => {
const invoke = vi.fn().mockResolvedValue("data:image/png;base64,AP8=");
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const editor = view();
vi.spyOn(editor, "posAtCoords").mockReturnValue(7);
await handleFileDrop(["/source/photo.png"], 0, 0);
expect(invoke).toHaveBeenCalledWith("fs_read_image", { path: "/source/photo.png" }, undefined);
await vi.waitFor(() => expect(create).toHaveBeenCalledWith("/project/docs/assets/photo.png", "AP8="));
expect(editor.state.doc.toString()).toBe("before ![](assets/photo.png)after");
});
it("inserts a paste as one isolated undo step and tracks edits during saving", async () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: string } }) => void;
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
+4 -7
View File
@@ -65,8 +65,8 @@ export async function saveImage(
markdown: string,
folder: string,
name: string,
data: string,
create = (path: string, base64: string) => call(commands.fsCreateFileBytes(path, base64)),
data: number[],
create = (path: string, bytes: number[]) => call(commands.fsCreateFileBytes(path, bytes)),
): Promise<string> {
const dot = name.lastIndexOf(".");
const stem = dot > 0 ? name.slice(0, dot) : name;
@@ -82,15 +82,12 @@ export async function saveImage(
}
}
/** The image as base64, the form `fsCreateFileBytes` takes. */
function imageBytes(blob: Blob | string): Promise<string> {
function imageBytes(blob: Blob | string): Promise<number[]> {
if ((typeof blob === "string" ? blob.length * 0.75 : blob.size) > MAX_IMAGE_BYTES)
return Promise.reject(new Error(tx("Image exceeds 16 MB.")));
// The data URL from fs_read_image already contains standard base64.
if (typeof blob === "string") return Promise.resolve(blob.slice(blob.indexOf(",") + 1));
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./imageBytes.worker.ts", import.meta.url), { type: "module" });
worker.onmessage = (event: MessageEvent<{ data: string; error?: string }>) => {
worker.onmessage = (event: MessageEvent<{ data: number[]; error?: string }>) => {
worker.terminate();
if (event.data.error) reject(new Error(event.data.error));
else resolve(event.data.data);
+2 -3
View File
@@ -52,8 +52,7 @@ import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
@@ -1300,7 +1299,7 @@ export class EditorController implements SlotHost {
* every tab showing it becomes a file tab.
*/
private async saveUntitled(model: import("./model/document").DocModel): Promise<boolean> {
const path = await chooseSavePath({
const path = await saveFileDialog({
title: tx("Save As"),
defaultPath: this.saveAsSuggestion(model),
filters: await languageFilters(),
-1
View File
@@ -11,7 +11,6 @@ import { VirtualBanner } from "./view/Banner";
const ipc = vi.hoisted(() => ({ support: vi.fn(), sources: vi.fn(), cancel: vi.fn(), choose: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: { lspCanDownloadSources: ipc.support, lspLibrarySources: ipc.sources, cancelRequest: ipc.cancel },
}));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: ipc.choose }));
+2 -3
View File
@@ -1,7 +1,6 @@
import { useEffect, useState } from "react";
import { create } from "zustand";
import { registerActions } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isCancelled, nextRequestId, onIdeEvent, type RequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -27,8 +26,8 @@ async function retrieve(path: string, choose: boolean) {
try {
let sources: string | null = null;
if (choose) {
const selected = await choosePath({
directory: false,
const { open } = await import("@/platform/dialog");
const selected = await open({
title: tx("Choose Sources…"),
filters: [{ name: tx("Source archives"), extensions: ["jar", "zip"] }],
});
+1 -1
View File
@@ -679,7 +679,7 @@ function CustomAgentModal({
try {
const trimmed = name.trim();
const title = trimmed ? tx`Select ${trimmed}` : tx("Select executable");
const path = await backend.chooseExecutable(title, command, "desktop");
const path = await backend.chooseExecutable(title, command);
if (path) setCommand(path);
setError(null);
} catch (e) {
+3 -6
View File
@@ -1,7 +1,5 @@
/** Agents of the ACP Registry: listing, install / update / remove (`agent_registry_*`). */
import { open } from "@/platform/dialog";
import { choosePath } from "@/platform/choosePath";
import { readDesktopText } from "@/platform/desktopFiles";
import { Channel } from "@tauri-apps/api/core";
import type {
AcpImportOutcome,
@@ -33,7 +31,7 @@ export interface CommandsBackend {
providers(): Promise<AgentProvider[]>;
set(id: string, command: string | null): Promise<void>;
setEnv(id: string, env: Record<string, string>): Promise<void>;
chooseExecutable(title: string, current?: string, location?: "desktop"): Promise<string | null>;
chooseExecutable(title: string, current?: string): Promise<string | null>;
saveCustom(input: CustomAgentInput): Promise<void>;
removeCustom(id: string): Promise<void>;
importAcp(text: string): Promise<AcpImportOutcome[]>;
@@ -58,8 +56,7 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
chooseExecutable: async (title, current) => {
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
return typeof picked === "string" ? picked : null;
},
@@ -84,7 +81,7 @@ export const tauriCommands: CommandsBackend = {
filters: [{ name: tx("ACP config"), extensions: ["json"] }],
});
if (typeof picked !== "string") return null;
return readDesktopText(picked);
return call(commands.fsReadText(picked));
},
};
+5 -2
View File
@@ -4,7 +4,7 @@ import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { choosePath } from "@/platform/choosePath";
import { isTauri } from "@/platform/ipc";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
import { Button, IconButton, Input, Radio, Select, T } from "@/ui";
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
@@ -40,7 +40,10 @@ export function AnalysisDialogHost() {
}
async function browseDirectory(initial: string): Promise<string | null> {
return choosePath({ directory: true, defaultPath: initial });
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: true, multiple: false, defaultPath: initial || undefined });
return typeof picked === "string" ? picked : null;
}
const KINDS: ScopeKind[] = ["project", "directory", "file", "changed", "custom"];
+13 -5
View File
@@ -10,7 +10,6 @@ import { tx } from "@/platform/i18n";
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import { executeAction } from "@/platform/actions";
import { choosePath, choosePaths } from "@/platform/choosePath";
import {
call,
commands,
@@ -428,12 +427,15 @@ export function classifyPickedPoms(root: string, picked: readonly string[]): { l
export async function addProjects(dialogTitle?: string) {
const root = useProject.getState().project?.root;
if (!root || useProject.getState().project?.workspace || !isTauri()) return;
const paths = await choosePaths({
const { open } = await import("@/platform/dialog");
const picked = await open({
title: dialogTitle ?? tx`Add Maven Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "pom.xml", extensions: ["xml"] }],
});
const paths = typeof picked === "string" ? [picked] : (picked ?? []);
if (!paths.length) return;
const { link, rejected } = classifyPickedPoms(root, paths);
if (link.length) await setLinked(root, link, true);
@@ -468,11 +470,14 @@ export async function importModuleFromExistingSources() {
} catch {
/* Tests and hosts without the tool-window service still link the POM. */
}
const path = await choosePath({
const { open } = await import("@/platform/dialog");
const picked = await open({
title: tx`Import Module from Existing Sources`,
directory: true,
multiple: false,
defaultPath: root,
});
const path = typeof picked === "string" ? picked : picked?.[0];
if (!path) return;
const pom = mavenPomForImport(path);
if (!(await directoryListsPom(pom))) {
@@ -527,13 +532,16 @@ export async function linkGradleProjects() {
!isTauri()
)
return;
const paths = await choosePaths({
const { open } = await import("@/platform/dialog");
const picked = await open({
title: tx`Link Gradle Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "Gradle build files", extensions: ["gradle", "kts"] }],
});
if (!paths.length || useProject.getState().project?.root !== root || gen !== generation) return;
const paths = typeof picked === "string" ? [picked] : picked;
if (!paths?.length || useProject.getState().project?.root !== root || gen !== generation) return;
const model = await call(commands.gradleLinkProjects(paths));
if (useProject.getState().project?.root !== root || gen !== generation) return;
const configs = await call(commands.runConfigs()).catch(() => useBuild.getState().configs);
+4 -2
View File
@@ -5,7 +5,6 @@
*/
import { useMemo, useState } from "react";
import { create } from "zustand";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
import { Dialog, Icon, List, T } from "@/ui";
@@ -29,7 +28,9 @@ import styles from "./Coverage.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
async function pickReport(): Promise<string | null> {
return choosePath({
const { open } = await import("@/platform/dialog");
const file = await open({
multiple: false,
directory: false,
title: "Import Coverage Report",
filters: [
@@ -40,6 +41,7 @@ async function pickReport(): Promise<string | null> {
{ name: "All files", extensions: ["*"] },
],
});
return typeof file === "string" ? file : null;
}
/** Imports `path` (asks for a file without one) and shows it like a run's suite. */
+1 -2
View File
@@ -1,7 +1,6 @@
/** Query History (browse / paste / delete) and Import Data from File dialogs. */
import { useEffect, useMemo, useState } from "react";
import { call, commands, type DbHistoryEntry } from "@/platform/ipc";
import { readDesktopText } from "@/platform/desktopFiles";
import { editorsFor } from "@/editor/api";
import { Checkbox, Dialog, EmptyState, IconButton, Input, List, Select, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
@@ -158,7 +157,7 @@ export function ImportDialog({ id, schema, table }: { id: string; schema: string
filters: [{ name: "CSV / TSV", extensions: ["csv", "tsv", "txt"] }],
});
if (typeof f !== "string") return;
const content = await readDesktopText(f);
const content = await call(commands.fsReadText(f));
setFile(f);
setText(content);
setSep(guessSeparator(content));
+4 -3
View File
@@ -1,5 +1,4 @@
import { useEffect, useState } from "react";
import { choosePaths } from "@/platform/choosePath";
import { call, commands, type DbJdbcDriver } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, Dialog, IconButton, Input, Select, T } from "@/ui";
@@ -86,12 +85,14 @@ export function JdbcDriverProfiles({
setBusy(true);
setError(null);
try {
const files = await choosePaths({
const { open } = await import("@/platform/dialog");
const files = await open({
title: tx("Choose JDBC Driver and Dependency JARs"),
multiple: true,
directory: false,
filters: [{ name: tx("Java archives"), extensions: ["jar"] }],
});
if (files.length && draft) {
if (files && draft) {
const jars = [...new Set([...draft.jars, ...files])];
set({ jars });
const names = await call(commands.dbJdbcDriverClasses(jars));
@@ -16,7 +16,6 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
(...args: unknown[]) => [name, ...args];
return {
...real,
isTauri: () => true,
call: backend.call,
commands: {
...real.commands,
+3 -2
View File
@@ -21,7 +21,6 @@ import {
type DbTxMode,
} from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { tx, txPart, useTx, useTxTemplate } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { sshLabel as configLabel } from "@/platform/remoteSettings";
@@ -260,7 +259,9 @@ function blank(): DataSource {
}
async function pickFile(title: string): Promise<string | null> {
return choosePath({ directory: false, title });
const { open } = await import("@/platform/dialog");
const file = await open({ multiple: false, directory: false, title });
return typeof file === "string" ? file : null;
}
/** A path field with Browse…. */
+1 -2
View File
@@ -6,7 +6,6 @@
import { introspectSource } from "./introspection";
import { writeClipboardText } from "@/platform/clipboard";
import { call, commands, type DataSource, type DbDriver, type DbTableInfo } from "@/platform/ipc";
import { readDesktopText } from "@/platform/desktopFiles";
import { registerActions, type Action } from "@/platform/actions";
import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions";
import { splitTarget } from "./model";
@@ -201,7 +200,7 @@ async function runScriptFile(id: string) {
});
if (typeof file !== "string") return;
try {
const text = await readDesktopText(file);
const text = await call(commands.fsReadText(file));
const statements = await call(commands.dbStatements(id, text, 0, text.length));
useDatabase.setState({ activeResult: OUTPUT_TAB });
showServiceView(RESULTS_VIEW, false);
+2 -2
View File
@@ -1,5 +1,4 @@
/** Menus of the Database tool window, laid out like IDEA's (New ▸, Copy/Paste ▸, SQL Scripts ▸ …). */
import { choosePath } from "@/platform/choosePath";
import type { MenuItem } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { fileSourceName, parseSourceUrl } from "./model";
@@ -33,7 +32,8 @@ const act = (
const sep: MenuItem = { kind: "separator" };
async function sqliteFromFile() {
const file = await choosePath({ directory: false, title: "SQLite Database File" });
const { open } = await import("@/platform/dialog");
const file = await open({ multiple: false, directory: false, title: "SQLite Database File" });
if (typeof file === "string") openSourceDialog(null, { driver: "sqlite", file, name: fileSourceName(file) });
}
+1 -4
View File
@@ -19,9 +19,7 @@ vi.mock("@/ui", () => ({ copyText: vi.fn() }));
vi.mock("@/workbench/inputDialogs", () => ({ promptInput: vi.fn() }));
vi.mock("@/workbench/messages", () => ({ confirm: vi.fn() }));
vi.mock("@/platform/dialog", () => ({ open: (...args: unknown[]) => ipc.openDialog(...args) }));
vi.mock("@/platform/project", () => ({
useProject: { getState: () => ({ project: { root: "/project" } }), subscribe: vi.fn() },
}));
vi.mock("@/platform/project", () => ({ useProject: { getState: () => ({ project: { root: "/project" } }) } }));
vi.mock("@/workbench/contributions", () => ({
notifications: () => ({ notify: ipc.notify }),
projectViewSelection: () => ipc.selection(),
@@ -29,7 +27,6 @@ vi.mock("@/workbench/contributions", () => ({
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
deployServerRoot: ipc.root,
remoteList: ipc.list,
+3 -2
View File
@@ -1,6 +1,5 @@
/** Remote Host tool window operations: list, open, create, rename, delete and download remote files. */
import { tx, txTemplate } from "@/platform/i18n";
import { choosePath } from "@/platform/choosePath";
import { call, commands, type RemoteEntry } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { deploymentConnection, deploymentSecretKey, type DeploymentServerValid } from "@/platform/remoteSettings";
@@ -184,8 +183,10 @@ export async function downloadToProject(server: DeploymentServerValid, entries:
* the project root, preselected), without the server path above them. */
export async function downloadTo(server: DeploymentServerValid, entries: RemoteEntry[]) {
if (!entries.length) return;
const target = await choosePath({
const { open } = await import("@/platform/dialog");
const target = await open({
directory: true,
multiple: false,
title: tx("Download to"),
defaultPath: (await defaultDownloadFolder()) ?? undefined,
});
+2 -3
View File
@@ -6,7 +6,6 @@ import { create } from "zustand";
import { editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { tx } from "@/platform/i18n";
import { toBase64 } from "@/platform/base64";
import type { Diagnostic } from "@/bindings";
import { call, commands, isCancelled, nextRequestId, type RequestId } from "@/platform/ipc";
import type { JsonValue } from "@/platform/losslessJson";
@@ -255,7 +254,7 @@ export async function addSchemaConfiguration(): Promise<void> {
if (existing) return editorService().openFile(existing);
const path = `${root}/${CONFIG_NAMES[0]}`;
try {
await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(CONFIG_TEMPLATE))));
await call(commands.fsCreateFileBytes(path, [...new TextEncoder().encode(CONFIG_TEMPLATE)]));
} catch (e) {
notifications().notify({ level: "error", title: "Cannot create the GraphQL configuration", body: String(e) });
return;
@@ -442,7 +441,7 @@ export async function introspectEndpoint(path: string, name?: string): Promise<v
}
} else {
try {
await call(commands.fsCreateFileBytes(target, toBase64(new TextEncoder().encode(sdl))));
await call(commands.fsCreateFileBytes(target, [...new TextEncoder().encode(sdl)]));
} catch (e) {
notifications().notify({ level: "error", title: "Cannot write the GraphQL schema", body: String(e) });
return;
@@ -7,7 +7,6 @@ import { handleRuntimeEvent } from "../runtimeUi";
const nativeOpen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: nativeOpen }));
vi.mock("@/platform/ipc", async (original) => ({ ...(await original<object>()), isTauri: () => true }));
const answerPrompt = vi.fn().mockResolvedValue(undefined);
let notes: Parameters<NotificationService["notify"]>[0][];
let dispose: (() => void) | undefined;
+11 -3
View File
@@ -39,8 +39,6 @@ import type {
Viewport,
WorkbenchEvent,
} from "@/bindings";
import { toBase64 } from "@/platform/base64";
import { choosePath } from "@/platform/choosePath";
import { tx } from "@/platform/i18n";
import { useRemote } from "@/platform/remote";
import { call, commands, IpcError, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
@@ -199,6 +197,12 @@ export function webSchemeUrl(path: string, windows = /windows/i.test(navigator.u
return windows ? `http://openidea-plugin.localhost/${encoded}` : `openidea-plugin://localhost/${encoded}`;
}
function toBase64(bytes: Uint8Array): string {
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(binary);
}
function fromBase64(b64: string): Uint8Array {
const binary = atob(b64);
const out = new Uint8Array(binary.length);
@@ -223,7 +227,11 @@ export const tauriPluginsBackend: PluginsBackend = {
return chosen;
},
program: (id, program, scope) => call(commands.pluginProgram(id, program, scope)),
pickProgram: () => choosePath({ directory: false, title: tx("Choose plugin executable") }),
pickProgram: async () => {
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: false, multiple: false, title: tx("Choose plugin executable") });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
},
setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)),
revokeNetHost: (id, host) => call(commands.pluginRevokeNetHost(id, host)),
assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)),
+9 -5
View File
@@ -5,7 +5,6 @@
* batches.
*/
import { readClipboardPlainText, readClipboardPng, writeClipboardText } from "@/platform/clipboard";
import { choosePath } from "@/platform/choosePath";
import { providePluginTestParser, providePluginTestSelector } from "@/workbench/contributions";
import {
contentTabData,
@@ -513,11 +512,16 @@ async function askUser(prompt: Prompt, signal: AbortSignal): Promise<string[] |
case "pickDirectory": {
if (signal.aborted) return null;
try {
const path = await choosePath(
{ directory: true, title: prompt.title, defaultPath: prompt.initial ?? undefined },
signal,
);
const { open } = await import("@/platform/dialog");
if (signal.aborted) return null;
const selected = await open({
directory: true,
multiple: false,
title: prompt.title,
defaultPath: prompt.initial ?? undefined,
});
if (signal.aborted) return null;
const path = Array.isArray(selected) ? selected[0] : selected;
return path ? [ipcPath(path)] : null;
} catch (error) {
if (!signal.aborted)
+1 -2
View File
@@ -4,7 +4,6 @@
*/
import type { FileEntry } from "@/bindings";
import { notifyFileOperation } from "@/platform/fileOps";
import { toBase64 } from "@/platform/base64";
import { call, commands, emitLocalIdeEvent, isTauri, IpcError, nextRequestId } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
@@ -32,7 +31,7 @@ export const tauriFs: ProjectFs = {
notifyFileOperation({ kind: "created", paths: [path] });
},
createFileBytes: async (path, data) => {
await call(commands.fsCreateFileBytes(path, toBase64(data)));
await call(commands.fsCreateFileBytes(path, [...data]));
notifyFileOperation({ kind: "created", paths: [path] });
},
createDir: async (path) => void (await call(commands.fsCreateDir(path))),
@@ -1,8 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import { registerHostPathChooser } from "@/platform/choosePath";
import { useRemote } from "@/platform/remote";
import { ExportTestResultsDialog, defaultExportName, loadExportOptions } from "./ExportTestResultsDialog";
import { TestResults } from "./testing";
@@ -17,7 +15,6 @@ const messages = vi.hoisted(() => ({ confirm: vi.fn(async () => true) }));
vi.mock("@/workbench/messages", async (orig) => ({ ...(await orig<object>()), confirm: messages.confirm }));
const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise<string | null> => null) }));
vi.mock("@/platform/dialog", () => dialog);
vi.mock("@/platform/ipc", async (orig) => ({ ...(await orig<object>()), isTauri: () => true }));
const ok = { status: "ok", data: null } as const;
let onDisk: Record<string, "file" | "dir"> = {};
@@ -38,14 +35,11 @@ beforeEach(() => {
});
vi.spyOn(commands, "fsOpenWithSystem").mockResolvedValue(ok);
vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, data) => {
written.push({ path, text: new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))) });
written.push({ path, text: new TextDecoder().decode(new Uint8Array(data)) });
return ok;
});
});
afterEach(() => {
useRemote.setState({ session: null });
vi.restoreAllMocks();
});
afterEach(() => vi.restoreAllMocks());
function results() {
const r = new TestResults();
@@ -170,59 +164,6 @@ describe("ExportTestResultsDialog", () => {
expect(written.map((w) => w.path)).toEqual([path]);
});
it.each(["html", "xml"] as const)(
"browses the remote folder for a %s report and confirms replacement",
async (format) => {
useRemote.setState({ session: { root: "/work/app", os: "linux" } as never });
const choose = vi.fn(async () => ["/srv/reports"]);
const unregister = registerHostPathChooser(choose);
try {
const onClose = open();
if (format === "xml") fireEvent.click(screen.getByRole("radio", { name: "XML" }));
const name = `Test Results - go test _calc.${format}`;
const path = `/srv/reports/${name}`;
onDisk[path] = "file";
press("Browse…");
await waitFor(() => expect(folder()).toHaveValue("/srv/reports"));
expect(choose).toHaveBeenCalledWith(expect.objectContaining({ directory: true, defaultPath: "/work/app/" }));
expect(dialog.save).not.toHaveBeenCalled();
expect(file()).toHaveValue(name);
messages.confirm.mockResolvedValueOnce(false);
press("OK");
await waitFor(() => expect(messages.confirm).toHaveBeenCalledOnce());
await waitFor(() => expect(screen.getByRole("button", { name: "OK" })).toBeEnabled());
expect(commands.fsDelete).not.toHaveBeenCalled();
expect(written).toHaveLength(0);
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written.map((w) => w.path)).toEqual([path]);
} finally {
unregister();
}
},
);
it("moves an absolute report path to the browsed remote folder", async () => {
useRemote.setState({ session: { root: "/work/app", os: "linux" } as never });
const choose = vi.fn(async () => ["/srv/reports"]);
const unregister = registerHostPathChooser(choose);
try {
const onClose = open();
fireEvent.change(file(), { target: { value: "/tmp/custom.html" } });
press("Browse…");
await waitFor(() => expect(file()).toHaveValue("custom.html"));
expect(choose).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: "/tmp/" }));
fireEvent.click(screen.getByRole("checkbox", { name: "Open exported file in browser" }));
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written.map((w) => w.path)).toEqual(["/srv/reports/custom.html"]);
} finally {
unregister();
}
});
it("confirms again when the destination changes after using the save dialog", async () => {
dialog.save.mockResolvedValueOnce("/tmp/picked.html");
onDisk["/work/app/reports/picked.html"] = "file";
+1 -19
View File
@@ -4,11 +4,8 @@
*/
import { useId, useState } from "react";
import { executeAction } from "@/platform/actions";
import { toBase64 } from "@/platform/base64";
import { choosePath } from "@/platform/choosePath";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { Checkbox, Dialog, IconButton, Input, Radio, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
@@ -99,7 +96,7 @@ export async function writeTestReport(path: string, text: string, confirmed: boo
return false;
await call(commands.fsDelete(path));
}
await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(text))));
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(text))));
return true;
} catch (e) {
notifications().notify({
@@ -161,21 +158,6 @@ export function ExportTestResultsDialog({
const browse = async () => {
try {
if (isRemoteWindow()) {
const current = isAbsolutePath(fileName.trim()) ? destinationFromPicker(fileName.trim()) : destination;
const initial = current.folder.trim();
const chosen = await choosePath({
directory: true,
title: "Choose Directory…",
defaultPath: !initial
? cwd
: isAbsolutePath(initial)
? initial
: resolveDestination({ folder: cwd, fileName: initial }, cwd),
});
if (chosen) setDestination({ folder: chosen, fileName: current.fileName });
return;
}
const { save } = await import("@/platform/dialog");
const chosen = await save({
defaultPath: target || folder || cwd,
+1 -2
View File
@@ -4,7 +4,6 @@
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
* it as a normal document.
*/
import { toBase64 } from "@/platform/base64";
import { call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { scratchesDir as hostScratchesDir } from "@/platform/scratchesDir";
import { editorService, notifications } from "@/workbench/contributions";
@@ -24,7 +23,7 @@ export const tauriScratchBackend: ScratchBackend = {
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
createFile: async (path, text) =>
void (await call(
text ? commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(text))) : commands.fsCreateFile(path),
text ? commands.fsCreateFileBytes(path, [...new TextEncoder().encode(text)]) : commands.fsCreateFile(path),
)),
languages: async () => scratchLanguages(await commands.languages()),
open: (path, caret) => editorService().openFile(path, { focus: true, ...(caret && { selection: caret }) }),
+10 -3
View File
@@ -12,11 +12,10 @@ import {
import clsx from "clsx";
import { openEditorPaths, useEditorRegistry } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { setContext } from "@/platform/context";
import { t, useTxTemplate, tx, txPart } from "@/platform/i18n";
import { formatBinding, hostBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectModules } from "@/platform/projectRoots";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
@@ -99,7 +98,15 @@ import styles from "./FindInFiles.module.css";
/** The Directory scope's browse button: a folder chooser opened at the current directory. */
async function chooseDirectory(current: string): Promise<string | null> {
return choosePath({ directory: true, title: tx("Select Search Directory"), defaultPath: current });
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const picked = await open({
directory: true,
multiple: false,
title: tx("Select Search Directory"),
defaultPath: current || undefined,
});
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
}
const POPUP_MAX_MATCHES = 2000;
@@ -64,10 +64,10 @@ describe("scheme actions", () => {
expect(screen.getByRole("status")).toHaveTextContent("Applied 16 values; skipped 2");
expect(Object.values(useSettingsDialog.getState().staged).every((s) => s.scope === "global")).toBe(true);
await run("export");
expect(mocks.write).toHaveBeenCalledWith("/schemes/export.icls", expect.any(String));
expect(
new TextDecoder().decode(Uint8Array.from(atob(mocks.write.mock.calls[0]![1]), (c) => c.charCodeAt(0))),
).toContain('name="Forest &amp; Moss"');
expect(mocks.write).toHaveBeenCalledWith("/schemes/export.icls", expect.any(Array));
expect(new TextDecoder().decode(new Uint8Array(mocks.write.mock.calls[0]![1]))).toContain(
'name="Forest &amp; Moss"',
);
mocks.confirm.mockResolvedValueOnce(false);
await run("delete");
expect(value("colorScheme")).toBe(id);
@@ -88,7 +88,7 @@ describe("scheme actions", () => {
await executeAction("editor.colorScheme.export", "/chosen/custom-export.icls");
});
expect(mocks.save).not.toHaveBeenCalled();
expect(mocks.write).toHaveBeenCalledWith("/chosen/custom-export.icls", expect.any(String));
expect(mocks.write).toHaveBeenCalledWith("/chosen/custom-export.icls", expect.any(Array));
});
it("supports cancel, keep both and overwrite collisions", async () => {
+5 -3
View File
@@ -10,7 +10,7 @@ import { useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { allActions, useActions, type Action } from "@/platform/actions";
import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS } from "@/platform/keymap";
import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { ask, confirm, showError } from "@/workbench/messages";
import {
@@ -257,7 +257,7 @@ export function KeymapPage() {
if (!path) return;
let parsed;
try {
parsed = parseIdeaKeymap(await readDesktopText(path));
parsed = parseIdeaKeymap(await call(commands.fsReadText(path)));
} catch (e) {
await showError(tx("Import Keymap"), e instanceof Error ? e.message : String(e));
return;
@@ -298,7 +298,9 @@ export function KeymapPage() {
draft,
);
try {
await writeDesktopText(path, json);
// The save dialog already confirmed replacing an existing file.
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(json))));
notifications().notify({
level: "info",
title: tx("Keymap exported"),
@@ -46,7 +46,7 @@ import { Row, Select } from "../../components/Form";
import { useSetting } from "../../components/context";
import styles from "./Editor.module.css";
import { executeAction, registerActions } from "@/platform/actions";
import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles";
import { call, commands } from "@/platform/ipc";
import { ask, confirm, showError } from "@/workbench/messages";
import { useContributions } from "@/workbench/contributions";
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
@@ -1727,7 +1727,7 @@ export function ColorSchemePage({
.split(/[\\/]/)
.at(-1)
?.replace(/\.[^.]+$/, "") || "Imported scheme";
const parsed = parseIcls(await readDesktopText(path), fallbackName);
const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName);
let overwrite = false;
if (schemes.some((s) => s.name === parsed.scheme.name)) {
const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name);
@@ -1758,7 +1758,10 @@ export function ColorSchemePage({
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }],
}));
if (!path) return;
await writeDesktopText(path, exportIcls(id, customs, mine));
const bytes = Array.from(new TextEncoder().encode(exportIcls(id, customs, mine)));
// The save dialog already confirmed replacing an existing file.
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, bytes));
setReport(tx("Scheme exported."));
},
delete: async () => {
@@ -10,7 +10,6 @@
import { useId, useState } from "react";
import { Button, Checkbox, Input, type SelectOption, T } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings";
import { NATIVE_TO_ASCII_ACTION } from "../../nativeToAscii";
import { FormGroup, NumberInput, Row, Select, Toggle } from "../../components/Form";
@@ -301,8 +300,9 @@ function JavaFormatter({
}) {
const id = useId();
const browse = async () => {
const path = await choosePath({
directory: false,
const { open } = await import("@/platform/dialog");
const path = await open({
multiple: false,
title: tx("Eclipse formatter XML"),
filters: [{ name: "XML", extensions: ["xml"] }],
});
+3 -2
View File
@@ -8,7 +8,6 @@ import { FontPicker } from "../components/FontPicker";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import { quotePath } from "@/platform/commandLine";
import { choosePath } from "@/platform/choosePath";
import { commands, isTauri } from "@/platform/ipc";
import {
DEFAULT_EXTERNAL_TOOL,
@@ -138,7 +137,9 @@ function ShellPathRow() {
void commands.termAvailableShells().then(setShells, () => undefined);
}, []);
const browse = async () => {
const path = await choosePath({ directory: false, title: "Shell Path" });
const { open: pick } = await import("@/platform/dialog");
const picked = await pick({ multiple: false, title: "Shell Path" });
const path = Array.isArray(picked) ? picked[0] : picked;
if (path) set(quotePath(path));
};
return (
@@ -27,9 +27,9 @@ vi.mock("@/platform/ipc", async (original) => ({
isTauri: () => true,
call: (result: unknown) => result,
commands: {
fsCreateFileBytes: (path: string, data: string) => {
fsCreateFileBytes: (path: string, data: number[]) => {
calls.bytes(path);
files.set(path, new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))));
files.set(path, new TextDecoder().decode(new Uint8Array(data)));
return Promise.resolve(null);
},
fsCreateFile: (path: string) => {
+1 -2
View File
@@ -1,5 +1,4 @@
/** Creates a file from a template and fills it through the editor. */
import { toBase64 } from "@/platform/base64";
import { tx } from "@/platform/i18n";
import { notifyFileOperation } from "@/platform/fileOps";
import { EditorSelection } from "@codemirror/state";
@@ -192,7 +191,7 @@ export async function createFromTemplate(
// A provided editor (a notebook shows cells, not text) reads the file from
// disk and has no view to insert into, so its body is written on create.
const provided = await providedEditor(plan.path);
if (provided && text) await call(commands.fsCreateFileBytes(plan.path, toBase64(new TextEncoder().encode(text))));
if (provided && text) await call(commands.fsCreateFileBytes(plan.path, [...new TextEncoder().encode(text)]));
else await call(commands.fsCreateFile(plan.path));
notifyFileOperation({ kind: "created", paths: [plan.path] });
onCreated?.();
+7 -7
View File
@@ -218,7 +218,7 @@ it("allows images at the size limit", async () => {
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, "AQI=", "image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(notify).not.toHaveBeenCalled();
remove();
});
@@ -238,7 +238,7 @@ it("claims remote image events before xterm and pastes a quoted path only after
const event = imageEvent(image());
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png"));
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'"));
@@ -256,7 +256,7 @@ it("reads an image from the explicit paste menu after text and file recovery", a
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(getType).toHaveBeenCalledWith("image/png");
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
});
@@ -283,7 +283,7 @@ it("uploads a menu image even if reading clipboard text is rejected", async () =
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
expect(notify).not.toHaveBeenCalled();
});
@@ -298,7 +298,7 @@ it("uploads image events instead of recovering a local image path", async () =>
host.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/remote/photo.png'"));
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(list).not.toHaveBeenCalled();
remove();
});
@@ -463,7 +463,7 @@ it.each(["event", "menu"])("stores raw local clipboard media through %s paste",
await pasteTerminalClipboard(paste, () => localTarget());
}
await vi.waitFor(() => expect(paste).toHaveBeenCalledExactlyOnceWith("'/tmp/a'\\''b c.png'"));
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(notify).not.toHaveBeenCalled();
remove();
});
@@ -566,7 +566,7 @@ it.each(["audio/wav", "video/mp4"])("stores raw %s clipboard data", async (type)
const event = imageEvent({ ...image(), type } as Blob);
host.dispatchEvent(event);
await vi.waitFor(() => expect(paste).toHaveBeenCalledExactlyOnceWith("'/tmp/media'"));
expect(store).toHaveBeenCalledWith(42, "AQI=", type);
expect(store).toHaveBeenCalledWith(42, [1, 2], type);
remove();
});
+1 -2
View File
@@ -1,5 +1,4 @@
import { pasteClipboardFiles, readClipboardPlainText, readClipboardText } from "@/platform/clipboard";
import { toBase64 } from "@/platform/base64";
import { call, commands, type TerminalId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
@@ -68,7 +67,7 @@ function filePaths(transfer: DataTransfer): string[] {
async function pasteMedia(media: Blob, target: TerminalPasteTarget, paste: (text: string) => void) {
try {
if (media.size > MAX_MEDIA_BYTES) throw new Error(tx`Clipboard media is too large to paste (limit ${20} MB).`);
const data = toBase64(new Uint8Array(await media.arrayBuffer()));
const data = Array.from(new Uint8Array(await media.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, media.type));
+5 -2
View File
@@ -5,7 +5,6 @@
import { Channel } from "@tauri-apps/api/core";
import type { InstallEvent, RequestId, ToolInfo, ToolUpdate } from "@/bindings";
import { call, commands, IpcError, isTauri } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
export interface LanguageChoice {
id: string;
@@ -44,7 +43,11 @@ export const tauriToolsBackend: ToolsBackend = {
restartServers: async (name) => {
await call(commands.lspRestartNamed(name));
},
chooseExecutable: (title, defaultPath) => choosePath({ directory: false, title, defaultPath }),
chooseExecutable: async (title, defaultPath) => {
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: false, multiple: false, title, defaultPath: defaultPath || undefined });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
},
languages: async () =>
(await commands.languages())
.map((l) => ({ id: l.id, name: l.name, extensions: l.extensions, filenames: l.filenames }))
+1 -4
View File
@@ -1,6 +1,5 @@
import { useEffect, useRef, useState } from "react";
import type { Branch, RequestId, Worktree, WorktreeCreation, WorktreeInclude } from "@/bindings";
import { toBase64 } from "@/platform/base64";
import { choosePath } from "@/platform/choosePath";
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
import { tx } from "@/platform/i18n";
@@ -261,9 +260,7 @@ function WorktreeForm({
}
if (!file.exists) {
try {
await call(
commands.fsCreateFileBytes(file.path, toBase64(new TextEncoder().encode(worktreeIncludeTemplate()))),
);
await call(commands.fsCreateFileBytes(file.path, [...new TextEncoder().encode(worktreeIncludeTemplate())]));
} catch (e) {
if (!isErrorKind(e, "alreadyExists")) throw e;
}
+6 -3
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { Commit } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { call, commands, isTauri } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { notifications, type EditorInput } from "@/workbench/contributions";
import {
@@ -26,12 +26,15 @@ import { currentRepoRoot } from "./store";
import { repositoryPath } from "./repositoryPaths";
import { firstLineOf, languageFor, viewerBase } from "./cm";
import styles from "./GitLog.module.css";
import { choosePaths } from "@/platform/choosePath";
import { choosePath } from "@/platform/choosePath";
import { openLogTab } from "./logStore";
import { openRevisionFile, type RevisionData } from "./revisionInput";
export async function openExternalLog() {
const paths = await choosePaths({ title: tx("Open Git Log"), directory: true });
const picked = isTauri()
? await (await import("@/platform/dialog")).open({ title: tx("Open Git Log"), directory: true, multiple: true })
: await choosePath({ title: "Open Git Log", directory: true });
const paths = Array.isArray(picked) ? picked : picked ? [picked] : [];
if (!paths.length) return;
try {
const roots = await Promise.all(paths.map((path) => call(commands.vcsOpenExternalLog(path))));
@@ -66,9 +66,9 @@ beforeEach(() => {
exists = false;
content = "";
mocks.info.mockImplementation(async () => ok({ path, exists }));
mocks.create.mockImplementation(async (_path, base64: string) => {
mocks.create.mockImplementation(async (_path, bytes) => {
exists = true;
content = new TextDecoder().decode(Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)));
content = new TextDecoder().decode(Uint8Array.from(bytes));
return ok(null);
});
mocks.read.mockImplementation(async () => ok(content));
+4 -5
View File
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { Channel } from "@tauri-apps/api/core";
import { tx } from "@/platform/i18n";
import { callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { openProject } from "@/platform/project";
import { Checkbox, Dialog, Icon, IconButton, Input, ProgressBar, Select, T, showContextMenu } from "@/ui";
import { cloneSourceList, notifications, useCloneSources } from "@/workbench/contributions";
@@ -183,9 +183,8 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
};
const cancel = () => {
const id = request.current;
if (id === null) onClose();
else void callDesktop("cancel_request", { id });
if (request.current !== null) void commands.cancelRequest(request.current);
else onClose();
};
const clone = async (picked?: string) => {
@@ -202,7 +201,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
if (text) setProgress({ line: text, fraction: progressFraction(text) });
};
try {
await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel });
await call(commands.vcsClone(id, cloneUrl.trim(), target, depth, channel));
writeParent(parentOf(target));
rememberUrl(cloneUrl.trim());
onClose();
+6 -4
View File
@@ -4,7 +4,6 @@
*/
import { activeEditor } from "@/editor/api";
import { registerActions } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isTauri } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { maybeEditorService, notifications, projectViewSelection } from "@/workbench/contributions";
@@ -98,13 +97,16 @@ function info(title: string) {
}
async function pickFile(near: string): Promise<string | null> {
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const dir = near.slice(0, near.lastIndexOf("/")) || undefined;
return choosePath({ directory: false, title: tx("Compare With"), defaultPath: dir });
const picked = await open({ multiple: false, directory: false, title: "Compare With", defaultPath: dir });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
}
/**
* The file to compare `path` against: a project-host path in the app; a
* browser file picker's contents in the browser build,
* The file to compare `path` against: the OS file dialog on the desktop; a
* browser file picker's contents elsewhere (remote development / `pnpm dev`),
* compared as text since no absolute path is available to the backend.
*/
async function pickComparison(
+2 -2
View File
@@ -1,5 +1,5 @@
/** VCS › Create Git Repository…: `git init` in a folder chosen under the project. */
import { choosePath } from "@/platform/choosePath";
import { open } from "@/platform/dialog";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
@@ -8,7 +8,7 @@ import { discoverRoots } from "./store";
export async function createRepository() {
const root = useProject.getState().project?.root;
const dir = await choosePath({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root });
const dir = await open({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root });
if (typeof dir !== "string") return;
try {
await call(commands.vcsInit(dir));
+7 -3
View File
@@ -35,7 +35,7 @@ import {
} from "@/ui";
import { executeAction } from "@/platform/actions";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { choosePath, chooseSavePath } from "@/platform/choosePath";
import { choosePath } from "@/platform/choosePath";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
@@ -165,7 +165,8 @@ export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string)
async function browseSave(current: string): Promise<string | null> {
try {
return await chooseSavePath({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] });
const { save } = await import("@/platform/dialog");
return (await save({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] })) ?? null;
} catch {
return null;
}
@@ -413,11 +414,14 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string)
} else {
let file = path ?? null;
if (!file) {
file = await choosePath({
const { open } = await import("@/platform/dialog");
const picked = await open({
multiple: false,
directory: false,
defaultPath: useVcs.getState().root ?? undefined,
filters: [{ name: "Patch", extensions: ["patch", "diff"] }],
});
file = typeof picked === "string" ? picked : null;
}
if (!file) return;
sourcePath = file;
+6 -3
View File
@@ -4,7 +4,6 @@
* merge UI), rename and delete.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { choosePaths } from "@/platform/choosePath";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { create } from "zustand";
@@ -582,8 +581,12 @@ export async function showShelfDiff(arg?: unknown, local = false, newTab = false
export async function importShelfPatches(paths?: string[]) {
const repo = currentRepo();
const picked =
paths ?? (await choosePaths({ directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }));
for (const path of picked) {
paths ??
(await import("@/platform/dialog").then(({ open }) =>
open({ multiple: true, directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }),
));
if (!picked) return;
for (const path of typeof picked === "string" ? [picked] : picked) {
await runOp(
tx("Import patches"),
async () => call(commands.vcsShelfImport(repo, baseName(path), await call(commands.fsReadText(path)))),
-20
View File
@@ -1,20 +0,0 @@
import { expect, it } from "vitest";
import { toBase64 } from "./base64";
const decode = (text: string) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
it("encodes every byte value and the empty input to standard padded base64", () => {
expect(toBase64(new Uint8Array())).toBe("");
expect(toBase64(new Uint8Array([0, 255]))).toBe("AP8=");
const all = Uint8Array.from({ length: 256 }, (_, i) => i);
expect([...decode(toBase64(all))]).toEqual([...all]);
});
it("is a string of at most ceil(4n/3) characters, across the chunk boundary", () => {
for (const n of [0x7fff, 0x8000, 0x8001, 5 * 0x8000 + 1]) {
const bytes = Uint8Array.from({ length: n }, (_, i) => (i * 31) % 256);
const text = toBase64(bytes);
expect(text).toHaveLength(4 * Math.ceil(n / 3));
expect(decode(text)).toEqual(bytes);
}
});
-11
View File
@@ -1,11 +0,0 @@
/**
* Binary command arguments (`IpcBytes` in Rust) cross IPC as base64 text: as a JSON number array
* they take 3.6x the size and a parsed `Value` tree of roughly 50x.
*/
export function toBase64(bytes: Uint8Array): string {
const parts: string[] = [];
// `apply` with a typed array is about 5x faster than spreading it (20 MB: 70 ms vs 380 ms).
for (let i = 0; i < bytes.length; i += 0x8000)
parts.push(String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as unknown as number[]));
return btoa(parts.join(""));
}
+11 -31
View File
@@ -1,21 +1,13 @@
import { isTauri } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import type { DialogFilter, SaveDialogOptions } from "@/platform/dialog";
export interface ChoosePathOptions {
directory: boolean;
title?: string;
title: string;
defaultPath?: string;
filters?: DialogFilter[];
}
export interface HostPathOptions extends ChoosePathOptions {
multiple?: boolean;
save?: boolean;
signal?: AbortSignal;
}
type HostChooser = (opts: HostPathOptions) => Promise<string[] | null>;
type HostChooser = (opts: ChoosePathOptions) => Promise<string | null>;
let hostChooser: HostChooser | null = null;
/**
@@ -33,28 +25,16 @@ export function registerHostPathChooser(chooser: HostChooser): () => void {
* File / folder chooser for a path on the host this window's commands run on: the desktop's dialog
* locally, the in-app chooser in a remote window. Null when cancelled or outside Tauri.
*/
export async function choosePath(opts: ChoosePathOptions, signal?: AbortSignal): Promise<string | null> {
if (!isTauri() || signal?.aborted) return null;
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, signal }))?.[0] ?? null;
export async function choosePath(opts: ChoosePathOptions): Promise<string | null> {
if (!isTauri()) return null;
if (isRemoteWindow() && hostChooser) return hostChooser(opts);
// Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load.
const { open } = await import("@/platform/dialog");
if (signal?.aborted) return null;
const picked = await open({ ...opts, multiple: false, defaultPath: opts.defaultPath || undefined });
const picked = await open({
directory: opts.directory,
multiple: false,
title: opts.title,
defaultPath: opts.defaultPath || undefined,
});
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
}
/** Pick multiple existing paths on the project host. */
export async function choosePaths(opts: ChoosePathOptions): Promise<string[]> {
if (!isTauri()) return [];
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, multiple: true })) ?? [];
const { open } = await import("@/platform/dialog");
const picked = await open({ ...opts, multiple: true });
return typeof picked === "string" ? [picked] : (picked ?? []);
}
/** Choose a destination on the project host and confirm replacement if it exists. */
export async function chooseSavePath(opts: SaveDialogOptions): Promise<string | null> {
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, directory: false, save: true }))?.[0] ?? null;
const { save } = await import("@/platform/dialog");
return save(opts);
}
-40
View File
@@ -1,40 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { readDesktopText, writeDesktopText } from "./desktopFiles";
import { useRemote } from "./remote";
import { setInvokeRoute } from "./tauriCore";
const invoke = vi.fn();
const remoteInvoke = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
useRemote.setState({ session: { root: "/srv/project", os: "linux" } as never });
setInvokeRoute(remoteInvoke);
});
afterEach(() => {
setInvokeRoute(null);
useRemote.setState({ session: null });
vi.unstubAllGlobals();
});
it("reads desktop settings or import files even when project IPC is remote", async () => {
const path = "C:\\Users\\me\\settings.xml";
invoke.mockResolvedValueOnce("<settings />");
await expect(readDesktopText(path)).resolves.toBe("<settings />");
expect(invoke.mock.calls[0]?.slice(0, 2)).toEqual(["fs_read_text", { path }]);
expect(remoteInvoke).not.toHaveBeenCalled();
});
it("checks and replaces an existing desktop file on the desktop", async () => {
const path = "C:\\Users\\me\\scheme.icls";
invoke.mockResolvedValueOnce("file").mockResolvedValueOnce(null).mockResolvedValueOnce(null);
await writeDesktopText(path, "é");
expect(invoke.mock.calls.map((args) => args.slice(0, 2))).toEqual([
["fs_entry_kind", { path }],
["fs_delete", { path }],
["fs_create_file_bytes", { path, data: "w6k=" }],
]);
expect(remoteInvoke).not.toHaveBeenCalled();
});
-24
View File
@@ -1,24 +0,0 @@
import { toBase64 } from "./base64";
import { call, callDesktop, commands, isErrorKind } from "./ipc";
import { isRemoteWindow } from "./remote";
/** Text selected in the desktop's file dialog, including in a remote window. */
export function readDesktopText(path: string): Promise<string> {
return isRemoteWindow() ? callDesktop<string>("fs_read_text", { path }) : call(commands.fsReadText(path));
}
/** Write UTF-8 to a path already confirmed in the desktop's save dialog. */
export async function writeDesktopText(path: string, text: string): Promise<void> {
const data = toBase64(new TextEncoder().encode(text));
if (!isRemoteWindow()) {
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, data));
return;
}
const kind = await callDesktop<string>("fs_entry_kind", { path }).catch((e: unknown) => {
if (!isErrorKind(e, "notFound")) throw e;
return null;
});
if (kind === "file") await callDesktop("fs_delete", { path });
await callDesktop("fs_create_file_bytes", { path, data });
}
-12
View File
@@ -9,8 +9,6 @@ import type { UnlistenFn } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { commands, type IdeError, type IdeEvent, type RequestId } from "@/bindings";
import { notifyEach } from "./listeners";
import { invokeLocal } from "./tauriCore";
import type { InvokeArgs } from "@tauri-apps/api/core";
export { commands };
export type * from "@/bindings";
@@ -45,16 +43,6 @@ export async function call<T>(result: Promise<Result<T>>): Promise<T> {
return r.data;
}
/** Run a command in the desktop process when its path came from that machine. */
export async function callDesktop<T>(command: string, args: InvokeArgs): Promise<T> {
try {
return await invokeLocal<T>(command, args);
} catch (e) {
if (e && typeof e === "object" && "kind" in e && "message" in e) throw new IpcError(e as IdeError);
throw e;
}
}
export function isCancelled(e: unknown): boolean {
return e instanceof IpcError && e.kind === "cancelled";
}
+31 -86
View File
@@ -9,13 +9,11 @@
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import { create } from "zustand";
import { registerHostPathChooser, type HostPathOptions } from "@/platform/choosePath";
import { registerHostPathChooser, type ChoosePathOptions } from "@/platform/choosePath";
import { t, tx, VerbatimTextContext } from "@/platform/i18n";
import { call, commands, isErrorKind, type FileEntry } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
import { call, commands, type FileEntry } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Checkbox, Dialog, Given, Icon, IconButton, Input, List, T } from "@/ui";
import { confirm } from "./messages";
import styles from "./inputDialogs.module.css";
export interface PromptInputOptions {
@@ -65,7 +63,7 @@ type Request =
| { kind: "prompt"; id: number; options: PromptInputOptions; resolve: (v: string | null) => void }
| { kind: "choose"; id: number; options: ChooseItemOptions; resolve: (v: string | null) => void }
| { kind: "pick"; id: number; options: PickItemsOptions; resolve: (v: string[] | null) => void }
| { kind: "path"; id: number; options: HostPathOptions; resolve: (v: string[] | null) => void };
| { kind: "path"; id: number; options: ChoosePathOptions; resolve: (v: string | null) => void };
const useInputDialogs = create<{ stack: Request[] }>(() => ({ stack: [] }));
let seq = 0;
@@ -104,8 +102,8 @@ export function pickItems(options: PickItemsOptions): Promise<string[] | null> {
}
/** A file or folder on the host this window's commands run on, browsed in the IDE (a remote window's chooser). */
function choosePathOnHost(options: HostPathOptions): Promise<string[] | null> {
return open<string[]>((id, resolve) => ({ kind: "path", id, options, resolve }), options.signal);
export function choosePathOnHost(options: ChoosePathOptions): Promise<string | null> {
return open<string>((id, resolve) => ({ kind: "path", id, options, resolve }));
}
registerHostPathChooser(choosePathOnHost);
@@ -353,10 +351,8 @@ function PickDialog({ options, done }: { options: PickItemsOptions; done: (v: st
/** The folder that holds `path` (either separator), or null at a root. */
export function parentPath(path: string): string | null {
if (/^(?:[\\/]+|[A-Za-z]:[\\/]*)$/.test(path)) return null;
const posix = path.startsWith("/") && !path.startsWith("//");
const trimmed = path.replace(posix ? /\/+$/ : /[\\/]+$/, "");
const slash = trimmed.lastIndexOf("/");
const cut = posix ? slash : Math.max(slash, trimmed.lastIndexOf("\\"));
const trimmed = path.length > 1 ? path.replace(/[\\/]+$/, "") : path;
const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
if (cut < 0) return null;
const parent = trimmed.slice(0, cut);
// `/a` → `/`; `C:\a` → `C:\`.
@@ -364,44 +360,30 @@ export function parentPath(path: string): string | null {
return parent === trimmed ? null : parent;
}
function PathDialog({ options, done }: { options: HostPathOptions; done: (v: string[] | null) => void }) {
function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: string | null) => void }) {
const root = useProject((s) => s.project?.root ?? null);
const title =
options.title ?? (options.save ? tx("Save As") : options.directory ? tx("Choose Directory…") : tx("Choose File…"));
const [dir, setDir] = useState<string | null>(null);
const [entries, setEntries] = useState<FileEntry[]>([]);
const [active, setActive] = useState(-1);
const [value, setValue] = useState(options.defaultPath || root || "");
const [selected, setSelected] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [submitting, setSubmitting] = useState(false);
const request = useRef(0);
const inDir = (dir: string, name: string) => `${ipcPath(dir).replace(/\/$/, "")}/${name}`;
const isAbsolute = (path: string) => /^(?:\/|[A-Za-z]:\/)/.test(ipcPath(path));
const isDir = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.targetKind === "dir");
const nameOf = (path: string) => ipcPath(path).split("/").at(-1) ?? "";
const accepts = (entry: FileEntry) =>
isDir(entry) ||
(!options.directory &&
(!options.filters?.length ||
options.filters.some(({ extensions }) =>
extensions.some((ext) => ext === "*" || entry.name.toLowerCase().endsWith(`.${ext.toLowerCase()}`)),
)));
const visit = async (path: string, filename = "") => {
const visit = async (path: string) => {
const id = ++request.current;
setLoading(true);
try {
const listed = await call(commands.fsReadDir(path));
if (id !== request.current) return true;
const shown = listed
.filter(accepts)
.filter((e) => !options.directory || isDir(e))
.sort((a, b) => Number(isDir(b)) - Number(isDir(a)) || a.name.localeCompare(b.name));
setDir(path);
setEntries(shown);
setActive(-1);
setValue(filename ? inDir(path, filename) : path);
setValue(path);
setError(null);
return true;
} catch (e) {
@@ -413,12 +395,7 @@ function PathDialog({ options, done }: { options: HostPathOptions; done: (v: str
};
useEffect(() => {
const initial = options.defaultPath || root || "/";
const start = root && !isAbsolute(initial) ? inDir(root, initial) : initial;
if (options.save) {
void visit(parentPath(start) ?? root ?? "/", nameOf(start));
return;
}
const start = options.defaultPath || root || "/";
// A file path starts in its folder, with the file in the field.
void visit(start).then((ok) => {
const parent = parentPath(start);
@@ -427,42 +404,23 @@ function PathDialog({ options, done }: { options: HostPathOptions; done: (v: str
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const move = (path: string) => visit(path, options.save && value !== dir ? nameOf(value) : "");
const toggle = (path: string) =>
setSelected((paths) => (paths.includes(path) ? paths.filter((p) => p !== path) : [...paths, path]));
const choose = (entry: FileEntry) => {
if (isDir(entry)) void move(entry.path);
else if (options.multiple) toggle(entry.path);
else if (options.save) setValue(entry.path);
else done([entry.path]);
if (isDir(entry)) void visit(entry.path);
else done(entry.path);
};
const submit = async () => {
const input = value.trim();
if (loading || submitting) return;
if (options.multiple && selected.length) return done(selected);
if (!input) return;
const path = dir && !isAbsolute(input) ? inDir(dir, input) : input;
setSubmitting(true);
const path = value.trim();
if (!path) return;
let kind: string;
try {
const kind = await call(commands.fsEntryKind(path));
const folder = kind === "dir";
if (options.directory) return folder ? done([path]) : setError(tx("Choose a folder"));
if (folder) return void visit(path);
if (
!options.save ||
(await confirm({
title,
message: tx`File '${nameOf(path)}' already exists. Do you want to overwrite it?`,
ok: "Overwrite",
}))
)
done([path]);
} catch (e) {
if (options.save && isErrorKind(e, "notFound")) done([path]);
else setError(options.save && e instanceof Error ? e.message : tx("No such file or folder"));
} finally {
setSubmitting(false);
kind = await call(commands.fsEntryKind(path));
} catch {
return setError(tx("No such file or folder"));
}
const folder = kind === "dir";
if (options.directory) return folder ? done(path) : setError(tx("Choose a folder"));
if (folder) return void visit(path);
done(path);
};
const up = dir === null ? null : parentPath(dir);
@@ -470,16 +428,11 @@ function PathDialog({ options, done }: { options: HostPathOptions; done: (v: str
<Dialog
open
blockWorkbenchShortcuts
title={title}
title={options.title}
onClose={() => done(null)}
width={520}
buttons={[
{
label: tx("OK"),
role: "default",
disabled: loading || submitting || (!value.trim() && !selected.length),
onClick: () => void submit(),
},
{ label: tx("OK"), role: "default", disabled: !value.trim(), onClick: () => void submit() },
{ label: t("common.cancel"), role: "cancel" },
]}
>
@@ -495,12 +448,12 @@ function PathDialog({ options, done }: { options: HostPathOptions; done: (v: str
icon="arrow-up"
title={tx("Parent Folder")}
disabled={!up || loading}
onClick={() => up && void move(up)}
onClick={() => up && void visit(up)}
/>
<Input
data-autofocus
className={styles.pathInput}
aria-label={title}
aria-label={options.title}
value={value}
invalid={!!error}
onChange={(e) => {
@@ -516,12 +469,12 @@ function PathDialog({ options, done }: { options: HostPathOptions; done: (v: str
onActiveChange={(i) => {
setActive(i);
const entry = entries[i];
if (entry && (!options.save || !isDir(entry))) setValue(entry.path);
if (entry) setValue(entry.path);
}}
// A click selects; a double click or Enter opens the folder or chooses the file.
onActivate={(entry, _i, e) => (e.type !== "click" || e.detail > 1) && choose(entry)}
className={styles.pathList}
aria-label={dir ?? title}
aria-label={dir ?? options.title}
empty={
<div className={styles.hint}>
<T>{loading ? "Loading…" : "Empty folder"}</T>
@@ -530,15 +483,7 @@ function PathDialog({ options, done }: { options: HostPathOptions; done: (v: str
renderItem={(entry, state) => (
<div className={`${state.active ? styles.activeRow : styles.row} ${styles.entry}`}>
<Icon name={isDir(entry) ? "folder" : "file"} />
{options.multiple && (options.directory || !isDir(entry)) ? (
<Checkbox
label={<Given>{entry.name}</Given>}
checked={selected.includes(entry.path)}
onChange={() => toggle(entry.path)}
/>
) : (
<span className={styles.entryName}>{entry.name}</span>
)}
<span className={styles.entryName}>{entry.name}</span>
</div>
)}
/>
+2 -61
View File
@@ -6,8 +6,6 @@ const mocks = vi.hoisted(() => ({
readDir: vi.fn(),
entryKind: vi.fn(),
nativeOpen: vi.fn(),
nativeSave: vi.fn(),
confirm: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -18,10 +16,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
commands: { ...real.commands, fsReadDir: mocks.readDir, fsEntryKind: mocks.entryKind },
};
});
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: mocks.nativeSave }));
vi.mock("./messages", async (original) => ({ ...(await original<object>()), confirm: mocks.confirm }));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: vi.fn() }));
import { choosePath, choosePaths, chooseSavePath } from "@/platform/choosePath";
import { choosePath } from "@/platform/choosePath";
import { useRemote } from "@/platform/remote";
import { InputDialogsHost, parentPath } from "./inputDialogs";
@@ -29,8 +26,6 @@ const tree: Record<string, [string, "dir" | "file"][]> = {
"/srv/app": [
["runner", "dir"],
["pom.xml", "file"],
["build.xml", "file"],
["README.txt", "file"],
],
"/srv/app/runner": [
["plugins", "dir"],
@@ -124,58 +119,6 @@ describe("choosePath in a remote window", () => {
fireEvent.click(dialog().getByRole("button", { name: "Cancel" }));
await expect(result).resolves.toBeNull();
});
it("selects multiple matching files on the host", async () => {
let result!: Promise<string[]>;
act(() => {
result = choosePaths({
directory: false,
title: "Add Maven Projects",
defaultPath: "/srv/app",
filters: [{ name: "XML", extensions: ["xml"] }],
});
});
fireEvent.click(await dialog().findByRole("checkbox", { name: "pom.xml" }));
fireEvent.click(dialog().getByRole("checkbox", { name: "build.xml" }));
expect(dialog().queryByText("README.txt")).toBeNull();
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toEqual(["/srv/app/pom.xml", "/srv/app/build.xml"]);
expect(mocks.nativeOpen).not.toHaveBeenCalled();
});
it("keeps a proposed name while browsing to a new save destination", async () => {
let result!: Promise<string | null>;
act(() => {
result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/new.txt" });
});
await dialog().findByText("runner");
expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/new.txt");
fireEvent.click(dialog().getByText("runner"), { detail: 2 });
await dialog().findByText("plugins");
expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/runner/new.txt");
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toBe("/srv/app/runner/new.txt");
expect(mocks.nativeSave).not.toHaveBeenCalled();
expect(mocks.confirm).not.toHaveBeenCalled();
});
it("asks before accepting an existing save destination", async () => {
mocks.confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
let result!: Promise<string | null>;
act(() => {
result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/pom.xml" });
});
await dialog().findByText("runner");
const ok = dialog().getByRole("button", { name: "OK" });
fireEvent.click(ok);
await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
await waitFor(() => expect(ok).toBeEnabled());
fireEvent.click(ok);
await expect(result).resolves.toBe("/srv/app/pom.xml");
expect(mocks.confirm).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining("pom.xml") }),
);
});
});
describe("parentPath", () => {
@@ -184,10 +127,8 @@ describe("parentPath", () => {
expect(parentPath("/srv")).toBe("/");
expect(parentPath("/")).toBeNull();
expect(parentPath("C:\\Users\\me")).toBe("C:\\Users");
expect(parentPath("C:/Users\\me")).toBe("C:/Users");
expect(parentPath("C:\\Users")).toBe("C:\\");
expect(parentPath("C:\\")).toBeNull();
expect(parentPath("/srv/app/")).toBe("/srv");
expect(parentPath("/srv/app/file\\name")).toBe("/srv/app");
});
});