дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-23 18:10:45 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
bd79458f59 |
No files matched your search
Створено
@@ -4253,7 +4253,6 @@ dependencies = [
|
||||
name = "ide-core"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -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)");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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)?;
|
||||
@@ -228,15 +228,6 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
|
||||
ide_vfs::create_dir(&path)
|
||||
}
|
||||
|
||||
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
/// keeps its scratches on the server, where its file commands run.
|
||||
#[command(trust = always)]
|
||||
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
let dir = host.data_dir.join("scratches");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
/// state). Returns whether the file is read-only now.
|
||||
#[command(trust = always)]
|
||||
@@ -392,7 +383,6 @@ ide_command::domain!(
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_scratches_dir,
|
||||
fs_set_writable,
|
||||
fs_synchronize_directories,
|
||||
fs_undo_delete,
|
||||
|
||||
@@ -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(©.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();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -74,13 +74,6 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
|
||||
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
|
||||
|
||||
let scratch_path = base.join("data/scratches");
|
||||
assert!(!scratch_path.exists());
|
||||
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
assert!(scratch_path.is_dir());
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
|
||||
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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` 与本地命令完全一样。
|
||||
|
||||
## 命令路由
|
||||
|
||||
|
||||
@@ -93,37 +93,6 @@ for (const activation of ["double-click", "Enter"] as const) {
|
||||
});
|
||||
}
|
||||
|
||||
test("records a modified wheel gesture and runs the assigned action", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action");
|
||||
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: /Find Action/ });
|
||||
await row.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true }).click();
|
||||
const recorder = page.getByRole("dialog", { name: "Mouse Shortcut: Find Action…", exact: true });
|
||||
const pad = recorder.getByRole("textbox", { name: "Mouse shortcut" });
|
||||
await pad.hover();
|
||||
const scrollUp = async () => {
|
||||
await page.keyboard.down("Control");
|
||||
await page.mouse.wheel(0, -120);
|
||||
await page.keyboard.up("Control");
|
||||
};
|
||||
await scrollUp();
|
||||
await expect(pad).toHaveText("⌃Wheel Up");
|
||||
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
|
||||
await expect(search).toBeHidden();
|
||||
await recorder.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(row).toContainText("⌃Wheel Up");
|
||||
await settings.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(settings).toBeHidden();
|
||||
await page.mouse.move(700, 450);
|
||||
await page.mouse.wheel(0, 120);
|
||||
await expect(search).toBeHidden();
|
||||
await scrollUp();
|
||||
await expect(search).toBeVisible();
|
||||
});
|
||||
|
||||
test("rectangular drag remains configurable after removal and saves a middle mouse binding", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -12,8 +12,9 @@ test("the scratch language chooser fits short windows and keeps recents separate
|
||||
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
|
||||
const { rememberLanguage } = await import(/* @vite-ignore */ store);
|
||||
setScratchBackend({
|
||||
scratchesDir: async () => "/test-app-data/scratches",
|
||||
dataDir: async () => "/test-app-data",
|
||||
listNames: async () => [],
|
||||
createDir: async () => {},
|
||||
createFile: async () => {},
|
||||
languages: async () => [
|
||||
...Array.from({ length: 24 }, (_, i) => {
|
||||
|
||||
@@ -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'"]);
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("hovering a tinted project tab keeps its colour", async ({ workbench: page }) => {
|
||||
await page.evaluate(async () => {
|
||||
const tabColors = "/src/workbench/tabColors.ts";
|
||||
const windowGroups = "/src/platform/windowGroups.ts";
|
||||
const { setTabColorOverride } = await import(/* @vite-ignore */ tabColors);
|
||||
const { useWindowGroup } = await import(/* @vite-ignore */ windowGroups);
|
||||
setTabColorOverride("/tinted", "#d24b8f");
|
||||
useWindowGroup.setState({
|
||||
tabs: [
|
||||
{ label: "main", name: "acme-api", root: "/plain", current: true },
|
||||
{ label: "second", name: "acme-api", root: "/plain2", current: false },
|
||||
{ label: "third", name: "acme-api", root: "/tinted", current: false },
|
||||
],
|
||||
});
|
||||
});
|
||||
const plain = page.locator('[data-project-tab="second"]');
|
||||
const tinted = page.locator('[data-project-tab="third"]');
|
||||
await expect(tinted).toBeVisible();
|
||||
|
||||
// A blank strip inside the tab: right of the hover close button, left of the centred label.
|
||||
const strip = async (tab: typeof plain) => {
|
||||
const box = (await tab.boundingBox())!;
|
||||
return { x: box.x + 34, y: box.y + box.height / 2 - 5, width: 8, height: 10 };
|
||||
};
|
||||
const shoot = async (tab: typeof plain) => page.screenshot({ clip: await strip(tab), animations: "disabled" });
|
||||
|
||||
await tinted.hover();
|
||||
const tintedHover = await shoot(tinted);
|
||||
await page.mouse.move(700, 600);
|
||||
const tintedRest = await shoot(tinted);
|
||||
await plain.hover();
|
||||
const plainHover = await shoot(plain);
|
||||
|
||||
// The opaque hover surface must not swallow the tint: a tinted tab renders differently from a plain one.
|
||||
expect(tintedHover.equals(plainHover)).toBe(false);
|
||||
// Hover still gives feedback on the tinted tab itself.
|
||||
expect(tintedHover.equals(tintedRest)).toBe(false);
|
||||
});
|
||||
@@ -286,7 +286,6 @@ fs_read_range always project_host bin
|
||||
fs_read_text always project_host bindings async
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_scratches_dir always project_host bindings sync
|
||||
fs_set_writable always project_host bindings sync
|
||||
fs_synchronize_directories always project_host bindings async
|
||||
fs_undo_delete always project_host bindings async
|
||||
|
||||
+2
-10
@@ -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. */
|
||||
@@ -707,11 +707,6 @@ export const commands = {
|
||||
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
|
||||
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
|
||||
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
|
||||
/**
|
||||
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
* keeps its scratches on the server, where its file commands run.
|
||||
*/
|
||||
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
|
||||
/**
|
||||
* Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
* state). Returns whether the file is read-only now.
|
||||
@@ -1823,7 +1818,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 +8366,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;
|
||||
|
||||
|
||||
@@ -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] } }));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
@@ -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("");
|
||||
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", [0, 255], create)).toBe(
|
||||
"",
|
||||
);
|
||||
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 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] } }));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,10 +1,8 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
|
||||
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
|
||||
|
||||
@@ -59,42 +57,6 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
expect(zoomOf(view)).toBe(0);
|
||||
});
|
||||
|
||||
it("zooms when no enabled keymap action claims the gesture", () => {
|
||||
const original = useKeymap.getState();
|
||||
const view = makeView();
|
||||
const run = vi.fn();
|
||||
let enabled = true;
|
||||
const unregister = registerAction({ id: "test.wheel", title: "Test", enabled: () => enabled, run });
|
||||
const uninstall = installKeyboardDispatcher(window);
|
||||
useKeymap.setState({ overrides: { "test.wheel": ["Ctrl+WheelUp"] } });
|
||||
const scroll = (deltaY: number) => {
|
||||
const event = new WheelEvent("wheel", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
ctrlKey: true,
|
||||
deltaY,
|
||||
deltaMode: WheelEvent.DOM_DELTA_LINE,
|
||||
});
|
||||
view.contentDOM.dispatchEvent(event);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
};
|
||||
try {
|
||||
scroll(-1);
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
expect(zoomOf(view)).toBe(0);
|
||||
scroll(1);
|
||||
expect(zoomOf(view)).toBe(-1);
|
||||
enabled = false;
|
||||
scroll(-1);
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
expect(zoomOf(view)).toBe(0);
|
||||
} finally {
|
||||
uninstall();
|
||||
unregister();
|
||||
useKeymap.setState(original);
|
||||
}
|
||||
});
|
||||
|
||||
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
|
||||
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
|
||||
const first = makeView();
|
||||
|
||||
@@ -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 }));
|
||||
|
||||
@@ -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"] }],
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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));
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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"];
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,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));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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…. */
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2,17 +2,22 @@ import { EditorView } from "@codemirror/view";
|
||||
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
|
||||
import { scratchesDir } from "@/platform/scratchesDir";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { appendRequests } from "./spring/request";
|
||||
|
||||
export const GENERATED_REQUESTS = "generated-requests.http";
|
||||
|
||||
async function scratchFile(): Promise<{ path: string; created: boolean }> {
|
||||
const path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
|
||||
const dir = `${await appDataDir()}/scratches`;
|
||||
const ignoreExisting = (e: unknown) => {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
};
|
||||
await call(commands.fsCreateDir(dir)).catch(ignoreExisting);
|
||||
const path = `${dir}/${GENERATED_REQUESTS}`;
|
||||
let created = true;
|
||||
await call(commands.fsCreateFile(path)).catch((e) => {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
ignoreExisting(e);
|
||||
created = false;
|
||||
});
|
||||
return { path, created };
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
|
||||
import { executeAction, getAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { scratchesDir } from "@/platform/scratchesDir";
|
||||
import {
|
||||
editorService,
|
||||
notifications,
|
||||
@@ -116,13 +116,11 @@ function directoryArg(arg: unknown): string | null {
|
||||
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
|
||||
async function newRequest(directory?: string) {
|
||||
try {
|
||||
const dir = directory ?? (await scratchesDir());
|
||||
if (directory) {
|
||||
try {
|
||||
await call(commands.fsCreateDir(dir));
|
||||
} catch (e) {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
}
|
||||
const dir = directory ?? `${await appDataDir()}/scratches`;
|
||||
try {
|
||||
await call(commands.fsCreateDir(dir));
|
||||
} catch (e) {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
}
|
||||
const names = new Set((await call(commands.fsReadDir(dir))).map((e) => e.name.toLowerCase()));
|
||||
let name = "requests.http";
|
||||
|
||||
@@ -4,6 +4,12 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co
|
||||
import { springControllers } from "./endpoints";
|
||||
import { generateRequests } from "./editor";
|
||||
|
||||
// The backend reports the user data directory `/`-separated on every OS.
|
||||
vi.mock("@/platform/platformInfo", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/platformInfo")>()),
|
||||
appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea",
|
||||
}));
|
||||
|
||||
// No backend here: the file commands answer like a project without Spring
|
||||
// configuration files (empty configs, the files the body lookup probes missing).
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
@@ -13,8 +19,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
call: async (p: Promise<unknown>) => await p,
|
||||
commands: {
|
||||
...m.commands,
|
||||
// The backend reports the scratches folder `/`-separated on every OS.
|
||||
fsScratchesDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches",
|
||||
fsCreateDir: async () => null,
|
||||
fsCreateFile: async () => null,
|
||||
fsReadText: async () => "",
|
||||
},
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { useProjectViewRoots } from "@/workbench/contributions";
|
||||
import {
|
||||
chooserRows,
|
||||
@@ -103,8 +102,9 @@ describe("creating scratch files", () => {
|
||||
opened = [];
|
||||
carets = [];
|
||||
backend = {
|
||||
scratchesDir: async () => "/data/scratches/",
|
||||
dataDir: async () => "/data/",
|
||||
listNames: async (dir) => [...files].filter((f) => f.startsWith(dir + "/")).map((f) => f.slice(dir.length + 1)),
|
||||
createDir: async () => {},
|
||||
createFile: async (p, text) => {
|
||||
files.add(p);
|
||||
contents.set(p, text);
|
||||
@@ -177,43 +177,14 @@ describe("creating scratch files", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("scratches of a remote window", () => {
|
||||
afterEach(() => {
|
||||
useRemote.setState({ session: null });
|
||||
setScratchBackend(tauriScratchBackend);
|
||||
});
|
||||
|
||||
it("moves the Scratches root to the server's folder when the window attaches to it in place", async () => {
|
||||
const remote = () => useRemote.getState().session !== null;
|
||||
setScratchBackend({
|
||||
scratchesDir: async () => (remote() ? "/home/me/.openidea/data/scratches" : "C:/Users/me/AppData/scratches"),
|
||||
listNames: async () => [],
|
||||
createFile: async () => {},
|
||||
languages: async () => [],
|
||||
open: async () => {},
|
||||
});
|
||||
const root = () => useProjectViewRoots.getState().roots.get("scratches")?.path;
|
||||
const dispose = activate();
|
||||
try {
|
||||
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
|
||||
useRemote.setState({ session: { root: "/home/me/project" } as never });
|
||||
await vi.waitFor(() => expect(root()).toBe("/home/me/.openidea/data/scratches"));
|
||||
useRemote.setState({ session: null });
|
||||
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
expect(root()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleting scratch files", () => {
|
||||
afterEach(() => setScratchBackend(tauriScratchBackend));
|
||||
|
||||
it("reports deletions inside the scratches folder as file system changes", async () => {
|
||||
setScratchBackend({
|
||||
scratchesDir: async () => "/data/scratches",
|
||||
dataDir: async () => "/data",
|
||||
listNames: async () => [],
|
||||
createDir: async () => {},
|
||||
createFile: async () => {},
|
||||
languages: async () => [],
|
||||
open: async () => {},
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { onFileOperation } from "@/platform/fileOps";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { registerMenuGroup, registerOverlay, registerProjectViewRoot } from "@/workbench/contributions";
|
||||
import { ScratchChooserHost } from "./ScratchChooser";
|
||||
import { openChooser } from "./store";
|
||||
@@ -21,15 +20,10 @@ export function activate(): () => void {
|
||||
let disposed = false;
|
||||
let unregisterRoot = () => {};
|
||||
let dir: string | null = null;
|
||||
let generation = 0;
|
||||
const registerRoot = () => {
|
||||
const current = ++generation;
|
||||
unregisterRoot();
|
||||
unregisterRoot = () => {};
|
||||
dir = null;
|
||||
if (scratchesAvailable())
|
||||
void scratchesDir()
|
||||
.then((path) => {
|
||||
if (disposed || current !== generation) return;
|
||||
if (disposed) return;
|
||||
dir = path;
|
||||
unregisterRoot = registerProjectViewRoot({
|
||||
id: "scratches",
|
||||
@@ -41,13 +35,7 @@ export function activate(): () => void {
|
||||
});
|
||||
})
|
||||
.catch((e: unknown) => console.warn("scratch files: no scratches folder", e));
|
||||
};
|
||||
if (scratchesAvailable()) registerRoot();
|
||||
const disposers = [
|
||||
// Attaching to (or leaving) a remote server moves the scratches to that host.
|
||||
useRemote.subscribe((state, previous) => {
|
||||
if (state.session !== previous.session && scratchesAvailable()) registerRoot();
|
||||
}),
|
||||
// The file watcher covers the project only: deleted scratches close their editors like watched files.
|
||||
onFileOperation((op) => {
|
||||
const removed = dir && op.kind === "deleted" ? op.paths.filter((p) => p === dir || p.startsWith(`${dir}/`)) : [];
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
/**
|
||||
* Scratch files live in the user data dir (`<data>/scratches`) of the host that runs the
|
||||
* window's file commands (the server in a remote window), not in the project, like IDEA's
|
||||
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
|
||||
* it as a normal document.
|
||||
* Scratch files live in the app data dir (`<appData>/scratches`), not in the
|
||||
* project, like IDEA's 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 { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
|
||||
|
||||
export interface ScratchBackend {
|
||||
/** Absolute scratches folder, created. */
|
||||
scratchesDir(): Promise<string>;
|
||||
/** Absolute app data dir. */
|
||||
dataDir(): Promise<string>;
|
||||
listNames(dir: string): Promise<string[]>;
|
||||
createDir(dir: string): Promise<void>;
|
||||
createFile(path: string, text: string): Promise<void>;
|
||||
languages(): Promise<ScratchLanguage[]>;
|
||||
open(path: string, caret: { line: number; col: number } | null): Promise<void>;
|
||||
}
|
||||
|
||||
export const tauriScratchBackend: ScratchBackend = {
|
||||
scratchesDir: hostScratchesDir,
|
||||
dataDir: appDataDir,
|
||||
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
|
||||
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
|
||||
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 }) }),
|
||||
@@ -35,13 +35,30 @@ let backend: ScratchBackend = tauriScratchBackend;
|
||||
/** Tests swap the backend. */
|
||||
export function setScratchBackend(b: ScratchBackend) {
|
||||
backend = b;
|
||||
dirPromise = null;
|
||||
}
|
||||
|
||||
export const scratchBackend = () => backend;
|
||||
|
||||
/** The scratches folder, created if needed. */
|
||||
export async function scratchesDir(): Promise<string> {
|
||||
return (await backend.scratchesDir()).replace(/\/+$/, "");
|
||||
let dirPromise: Promise<string> | null = null;
|
||||
|
||||
/** `<appData>/scratches`, created on first use. */
|
||||
export function scratchesDir(): Promise<string> {
|
||||
if (!dirPromise) {
|
||||
dirPromise = (async () => {
|
||||
const dir = `${(await backend.dataDir()).replace(/\/+$/, "")}/scratches`;
|
||||
try {
|
||||
await backend.createDir(dir);
|
||||
} catch (e) {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
}
|
||||
return dir;
|
||||
})();
|
||||
dirPromise.catch(() => {
|
||||
dirPromise = null;
|
||||
});
|
||||
}
|
||||
return dirPromise;
|
||||
}
|
||||
|
||||
export const scratchesAvailable = () => isTauri() || backend !== tauriScratchBackend;
|
||||
|
||||
@@ -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 & 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 & 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 () => {
|
||||
|
||||
@@ -2,15 +2,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { RecordShortcutDialog } from "../keymap/RecordShortcutDialog";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
|
||||
afterEach(cleanup);
|
||||
const originalPlatform = usePlatform.getState();
|
||||
afterEach(() => usePlatform.setState(originalPlatform));
|
||||
const originalSettings = useProject.getState().settings;
|
||||
afterEach(() => useProject.setState({ settings: originalSettings }));
|
||||
|
||||
const action = { id: "my.action", title: "My Action", category: "Test" };
|
||||
const rectangular = {
|
||||
@@ -20,71 +15,6 @@ const rectangular = {
|
||||
};
|
||||
|
||||
describe("Mouse Shortcut dialog", () => {
|
||||
it.each([
|
||||
[{ deltaY: -1, ctrlKey: true }, "Ctrl+Wheel Up", "Ctrl+WheelUp"],
|
||||
[{ deltaY: 1, shiftKey: true, altKey: true }, "Alt+Shift+Wheel Down", "Alt+Shift+WheelDown"],
|
||||
[{ deltaY: 1 }, "Wheel Down", "WheelDown"],
|
||||
])("records and consumes %j as %s", (init, label, binding) => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
<RecordShortcutDialog
|
||||
mouse
|
||||
action={action}
|
||||
actions={[action]}
|
||||
draft={{ preset: "intellij-windows", overrides: {} }}
|
||||
onCancel={() => {}}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
const pad = screen.getByRole("textbox", { name: "Mouse shortcut" });
|
||||
const wheel = new WheelEvent("wheel", { ...init, cancelable: true, bubbles: true });
|
||||
fireEvent(pad, wheel);
|
||||
expect(pad).toHaveTextContent(label);
|
||||
expect(wheel.defaultPrevented).toBe(true);
|
||||
fireEvent.click(screen.getByRole("button", { name: "OK" }));
|
||||
expect(onSubmit).toHaveBeenCalledWith(binding, [], false);
|
||||
});
|
||||
|
||||
it("shows the assigned action and the enabled font zoom conflict without running either", () => {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
useProject.setState({
|
||||
settings: { ...originalSettings, editor: { general: { wheelZoom: true } } } as typeof originalSettings,
|
||||
});
|
||||
const existing = { id: "my.otherAction", title: "Other Action" };
|
||||
const run = vi.fn();
|
||||
const unregister = registerAction({ ...existing, run });
|
||||
const originalKeymap = useKeymap.getState();
|
||||
const overrides = { [existing.id]: ["Meta+WheelDown"] };
|
||||
useKeymap.setState({ overrides });
|
||||
const uninstall = installKeyboardDispatcher(window);
|
||||
try {
|
||||
render(
|
||||
<RecordShortcutDialog
|
||||
mouse
|
||||
action={action}
|
||||
actions={[action, existing]}
|
||||
draft={{ preset: "intellij-macos", overrides }}
|
||||
onCancel={() => {}}
|
||||
onSubmit={() => {}}
|
||||
/>,
|
||||
);
|
||||
const pad = screen.getByRole("textbox", { name: "Mouse shortcut" });
|
||||
fireEvent.wheel(pad, { deltaY: 1, metaKey: true });
|
||||
expect(pad).toHaveTextContent("⌘Wheel Down");
|
||||
expect(screen.getByText("Other Action")).toBeVisible();
|
||||
expect(screen.getByText(/takes precedence over.*font zoom/)).toBeVisible();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
fireEvent.wheel(pad, { deltaY: -1, altKey: true });
|
||||
expect(screen.queryByText(/takes precedence over.*font zoom/)).not.toBeInTheDocument();
|
||||
expect(screen.getByText("No conflicts")).toBeVisible();
|
||||
} finally {
|
||||
uninstall();
|
||||
unregister();
|
||||
useKeymap.setState(originalKeymap);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["windows", "macos", "linux"] as const)("records middle drag and explains Linux paste on %s", (os) => {
|
||||
usePlatform.setState({ os });
|
||||
const onSubmit = vi.fn();
|
||||
@@ -122,7 +52,6 @@ describe("Mouse Shortcut dialog", () => {
|
||||
);
|
||||
const pad = screen.getByRole("textbox", { name: "Mouse shortcut" });
|
||||
fireEvent.mouseDown(pad, { button, altKey: true });
|
||||
fireEvent.wheel(pad, { deltaY: -1, ctrlKey: true });
|
||||
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
|
||||
expect(pad).toHaveTextContent("Click here with Ctrl, Alt or Command held, or use the middle mouse button");
|
||||
fireEvent.mouseDown(pad, { button: 0, altKey: true });
|
||||
@@ -168,7 +97,6 @@ describe("Mouse Shortcut dialog", () => {
|
||||
);
|
||||
const pad = screen.getByRole("textbox", { name: "Mouse shortcut" });
|
||||
fireEvent.mouseDown(pad, { button: 0 });
|
||||
fireEvent.wheel(pad, { deltaX: 16, deltaY: 1 });
|
||||
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
|
||||
fireEvent.mouseDown(pad, { button: 3, altKey: true });
|
||||
fireEvent.click(screen.getByRole("button", { name: "OK" }));
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -2,21 +2,17 @@
|
||||
* IDEA's "Keyboard Shortcut" dialog: records a first (and optional second)
|
||||
* stroke and lists conflicts live; OK with conflicts asks whether to remove the
|
||||
* other assignments (Remove / Leave / Cancel). With `mouse` it is the "Mouse
|
||||
* Shortcut" dialog: the pad records mouse buttons and wheel gestures.
|
||||
* Shortcut" dialog: a click on its pad records the button and modifiers.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import { useEffect, useMemo, useState, type MouseEvent } from "react";
|
||||
import { Checkbox, Dialog, Icon, Kbd, T } from "@/ui";
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { useEditorPrefs } from "@/platform/editorSettings";
|
||||
import {
|
||||
formatBinding,
|
||||
isWheelBinding,
|
||||
mouseStrokeOf,
|
||||
normalizeBinding,
|
||||
parseDoubleModifier,
|
||||
supportsWheelShortcut,
|
||||
suspendKeyboardDispatch,
|
||||
wheelStrokeOf,
|
||||
} from "@/platform/keymap";
|
||||
import { isPageSwipe } from "@/platform/pageSwipe";
|
||||
import { ask } from "@/workbench/messages";
|
||||
@@ -34,7 +30,7 @@ export interface RecordShortcutDialogProps {
|
||||
onCancel: () => void;
|
||||
/** `removeConflicts`: also unbind the conflicting assignments. */
|
||||
onSubmit: (binding: string, conflicts: Conflict[], removeConflicts: boolean) => void;
|
||||
/** Record a mouse button or wheel shortcut. */
|
||||
/** Record a mouse shortcut (modified left clicks, middle or side buttons) instead of keys. */
|
||||
mouse?: boolean;
|
||||
}
|
||||
|
||||
@@ -46,11 +42,9 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
const tx = useTx();
|
||||
const actionName = tx(action.title);
|
||||
const rectangularSelection = action.id === "editor.createRectangularSelectionOnMouseDrag";
|
||||
const wheelZoom = useEditorPrefs().general.wheelZoom;
|
||||
|
||||
const allowsSecond = !isPageSwipe(first) && !parseDoubleModifier(first);
|
||||
const binding = !mouse && allowsSecond && first && useSecond ? (second ? `${first} ${second}` : "") : first;
|
||||
const zoomConflict = wheelZoom && isWheelBinding(binding) && /(?:^|\+)(Ctrl|Meta)\+/.test(binding);
|
||||
const conflicts = useMemo(
|
||||
() => (binding ? findConflicts(draft, binding, action.id, actions) : []),
|
||||
[binding, draft, action.id, actions],
|
||||
@@ -102,12 +96,7 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
</div>
|
||||
</div>
|
||||
{mouse ? (
|
||||
<MouseRecorder
|
||||
value={first}
|
||||
onChange={setFirst}
|
||||
sideButtons={!rectangularSelection}
|
||||
wheel={supportsWheelShortcut(action.id)}
|
||||
/>
|
||||
<MouseRecorder value={first} onChange={setFirst} sideButtons={!rectangularSelection} />
|
||||
) : (
|
||||
<KeyStrokes
|
||||
first={first}
|
||||
@@ -130,7 +119,7 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
<T>The action already has this shortcut</T>
|
||||
</span>
|
||||
)}
|
||||
{!already && binding && !zoomConflict && conflicts.length === 0 && (
|
||||
{!already && binding && conflicts.length === 0 && (
|
||||
<span className={styles.recordHint}>
|
||||
<T>No conflicts</T>
|
||||
</span>
|
||||
@@ -146,16 +135,6 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
<ConflictList conflicts={conflicts} />
|
||||
</>
|
||||
)}
|
||||
{zoomConflict && (
|
||||
<div className={styles.conflictTitle}>
|
||||
<Icon name="warning" size={14} className={styles.conflictIcon} />
|
||||
<span>
|
||||
<T>
|
||||
This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.
|
||||
</T>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
@@ -229,34 +208,17 @@ function KeyStrokes({ first, second, useSecond, allowsSecond, setFirst, setSecon
|
||||
);
|
||||
}
|
||||
|
||||
/** Shortcuts stay off while the dialog records mouse gestures. */
|
||||
/** Shortcuts stay off while the dialog records mouse buttons and modifiers. */
|
||||
function MouseRecorder({
|
||||
value,
|
||||
onChange,
|
||||
sideButtons,
|
||||
wheel,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (binding: string) => void;
|
||||
sideButtons: boolean;
|
||||
wheel: boolean;
|
||||
}) {
|
||||
const padRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => suspendKeyboardDispatch(), []);
|
||||
useEffect(() => {
|
||||
const pad = padRef.current;
|
||||
if (!pad || !wheel) return;
|
||||
const recordWheel = (e: WheelEvent) => {
|
||||
const stroke = wheelStrokeOf(e);
|
||||
if (!stroke) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onChange(stroke);
|
||||
};
|
||||
// React's wheel handler is passive.
|
||||
pad.addEventListener("wheel", recordWheel, { passive: false });
|
||||
return () => pad.removeEventListener("wheel", recordWheel);
|
||||
}, [onChange, wheel]);
|
||||
const record = (e: MouseEvent<HTMLDivElement>) => {
|
||||
// Rectangular selection only handles left and middle buttons.
|
||||
if (!sideButtons && e.button > 1) return;
|
||||
@@ -268,7 +230,6 @@ function MouseRecorder({
|
||||
};
|
||||
return (
|
||||
<div
|
||||
ref={padRef}
|
||||
role="textbox"
|
||||
aria-readonly="true"
|
||||
aria-label="Mouse shortcut"
|
||||
@@ -281,9 +242,7 @@ function MouseRecorder({
|
||||
<span className={styles.recorded}>{formatBinding(value)}</span>
|
||||
) : (
|
||||
<span className={styles.recorderPlaceholder}>
|
||||
{wheel ? (
|
||||
<T>Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button</T>
|
||||
) : sideButtons ? (
|
||||
{sideButtons ? (
|
||||
<T>Click here with Ctrl, Alt or Command held, or use a middle or side mouse button</T>
|
||||
) : (
|
||||
<T>Click here with Ctrl, Alt or Command held, or use the middle mouse button</T>
|
||||
|
||||
@@ -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"] }],
|
||||
});
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useState } from "react";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Checkbox, Dialog, Input } from "@/ui";
|
||||
import { answerAskpass, askpassAnswer, askpassTitle, useAskpass, type AskpassPrompt } from "./askpass";
|
||||
import { answerAskpass, askpassAnswer, useAskpass, type AskpassPrompt } from "./askpass";
|
||||
import styles from "./Ssh.module.css";
|
||||
|
||||
export function AskpassHost() {
|
||||
@@ -39,7 +39,7 @@ function AskpassDialog({ prompt: p }: { prompt: AskpassPrompt }) {
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title={tx(askpassTitle(p))}
|
||||
title={tx(p.kind === "secret" ? "SSH Password" : "SSH")}
|
||||
onClose={cancel}
|
||||
width={440}
|
||||
buttons={[
|
||||
|
||||
@@ -45,12 +45,3 @@ export function answerAskpass(
|
||||
// on success and drops it again when authentication fails.
|
||||
void send(p.id, answer, remember).catch(() => {});
|
||||
}
|
||||
|
||||
/** The dialog title: git asks for HTTPS credentials (any host, e.g. a token as the password) as well as ssh. */
|
||||
export function askpassTitle(
|
||||
p: Pick<AskpassPrompt, "kind" | "prompt">,
|
||||
): "Password" | "Username" | "SSH Password" | "SSH" {
|
||||
const https = /\bhttps?:\/\//i.test(p.prompt);
|
||||
if (p.kind === "secret") return https ? "Password" : "SSH Password";
|
||||
return https ? "Username" : "SSH";
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DEFAULT_SSH_CONFIG, type SshConfigValid } from "@/platform/remoteSettings";
|
||||
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
|
||||
import { answerAskpass, askpassAnswer, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
|
||||
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
|
||||
|
||||
describe("askpass queue", () => {
|
||||
@@ -40,18 +40,6 @@ describe("askpass queue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("askpass title", () => {
|
||||
it("names git HTTPS credentials without calling them SSH", () => {
|
||||
expect(askpassTitle({ kind: "secret", prompt: "Password for 'https://[email protected]': " })).toBe("Password");
|
||||
expect(askpassTitle({ kind: "text", prompt: "Username for 'https://cnb.cool': " })).toBe("Username");
|
||||
});
|
||||
|
||||
it("keeps the SSH titles for ssh prompts", () => {
|
||||
expect(askpassTitle({ kind: "secret", prompt: "dev@host's password: " })).toBe("SSH Password");
|
||||
expect(askpassTitle({ kind: "text", prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': " })).toBe("SSH");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Start SSH Session chooser", () => {
|
||||
const config = (patch: Partial<SshConfigValid>): SshConfigValid => ({ ...DEFAULT_SSH_CONFIG, ...patch });
|
||||
|
||||
|
||||
@@ -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,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?.();
|
||||
|
||||
@@ -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,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));
|
||||
|
||||
@@ -389,58 +389,6 @@ describe("terminal restart", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal startup size", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("resizes a freshly spawned PTY to the grid reached while startup was pending", async () => {
|
||||
let release: ((value: { id: number; title: string }) => void) | undefined;
|
||||
ipc.commands.termSpawn.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<{ id: number; title: string }>((resolve) => {
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
const session = new TerminalSession({ key: "s-start-size", cwd: "/repo", onChange() {}, onFocus() {} });
|
||||
try {
|
||||
session.term.resize(80, 24);
|
||||
const starting = session.start();
|
||||
await vi.waitFor(() => expect(release).toBeTypeOf("function"));
|
||||
expect(ipc.commands.termSpawn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cols: 80, rows: 24 }),
|
||||
expect.anything(),
|
||||
);
|
||||
// Resize while startup is still pending.
|
||||
session.term.resize(100, 30);
|
||||
release!({ id: 12, title: "zsh" });
|
||||
await starting;
|
||||
expect(ipc.commands.termResize).toHaveBeenCalledWith(12, 100, 30);
|
||||
} finally {
|
||||
session.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves the PTY alone when the grid did not change during startup", async () => {
|
||||
let release: ((value: { id: number; title: string }) => void) | undefined;
|
||||
ipc.commands.termSpawn.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<{ id: number; title: string }>((resolve) => {
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
const session = new TerminalSession({ key: "s-start-same", cwd: "/repo", onChange() {}, onFocus() {} });
|
||||
try {
|
||||
session.term.resize(80, 24);
|
||||
const starting = session.start();
|
||||
await vi.waitFor(() => expect(release).toBeTypeOf("function"));
|
||||
release!({ id: 13, title: "zsh" });
|
||||
await starting;
|
||||
expect(ipc.commands.termResize).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
session.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal open", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
|
||||
@@ -858,8 +858,6 @@ export class TerminalSession {
|
||||
}
|
||||
this.ptyId = info.id;
|
||||
this.update({ status: "running", title: info.title || "Local" });
|
||||
// Send the new size if it changed while the program was starting.
|
||||
if (this.term.cols !== cols || this.term.rows !== rows) this.resizePty(this.term.cols, this.term.rows);
|
||||
this.flushPendingInput();
|
||||
} catch (e) {
|
||||
this.pendingInput = "";
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)))),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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(""));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -23,8 +23,6 @@ describe("IntelliJ IDEA keymap import", () => {
|
||||
<keyboard-shortcut first-keystroke="meta shift N" />
|
||||
<keyboard-shortcut first-keystroke="meta K" second-keystroke="meta C" />
|
||||
<mouse-shortcut keystroke="alt button1" />
|
||||
<mouse-shortcut keystroke="control button143" />
|
||||
<mouse-shortcut keystroke="shift alt button142" />
|
||||
<mouse-shortcut keystroke="double button1" />
|
||||
</action>
|
||||
<action id="GotoDeclaration" />
|
||||
@@ -33,7 +31,7 @@ describe("IntelliJ IDEA keymap import", () => {
|
||||
expect(k.name).toBe("My Mac");
|
||||
expect(k.parent).toBe("intellij-macos");
|
||||
expect(k.overrides["navigate.gotoClass"]).toEqual(
|
||||
["Meta+Shift+N", "Meta+K Meta+C", "Alt+Button1", "Ctrl+WheelUp", "Alt+Shift+WheelDown"].map(normalizeBinding),
|
||||
["Meta+Shift+N", "Meta+K Meta+C", "Alt+Button1"].map(normalizeBinding),
|
||||
);
|
||||
expect(k.overrides["navigate.declaration"]).toEqual([]);
|
||||
expect(k.applied).toBe(2);
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface ImportedIdeaKeymap {
|
||||
applied: number;
|
||||
/** IDEA action ids without an OpenIDEA counterpart. */
|
||||
unknownActions: string[];
|
||||
/** Shortcuts that cannot be expressed here (double click, unknown keys). */
|
||||
/** Shortcuts that cannot be expressed here (wheel, double click, unknown keys). */
|
||||
skippedShortcuts: number;
|
||||
}
|
||||
|
||||
@@ -90,13 +90,12 @@ export function fromSwingStroke(stroke: string): string | null {
|
||||
return name ? [...words.map((w) => SWING_MODS[w.toLowerCase()]), name].join("+") : null;
|
||||
}
|
||||
|
||||
/** Converts Swing mouse buttons and wheel directions. */
|
||||
/** `"meta alt button1"` → `"Meta+Alt+Button1"`; wheel and multi-click gestures → null. */
|
||||
function fromMouseStroke(stroke: string): string | null {
|
||||
const words = stroke.trim().split(/\s+/);
|
||||
const button = words.pop()?.toLowerCase();
|
||||
if (!button || !/^button(?:\d|14[23])$/.test(button) || words.some((w) => !SWING_MODS[w.toLowerCase()])) return null;
|
||||
const key = button === "button143" ? "WheelUp" : button === "button142" ? "WheelDown" : button;
|
||||
return [...words.map((w) => SWING_MODS[w.toLowerCase()]), key].join("+");
|
||||
const button = words.pop();
|
||||
if (!button || !/^button\d$/i.test(button) || words.some((w) => !SWING_MODS[w.toLowerCase()])) return null;
|
||||
return [...words.map((w) => SWING_MODS[w.toLowerCase()]), `Button${button.slice(6)}`].join("+");
|
||||
}
|
||||
|
||||
/** Parses an IDEA keymap XML; throws when the file is not a keymap. */
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* Keys are matched by physical position (`KeyboardEvent.code`), so ⌥-letter
|
||||
* combos work on macOS where `event.key` would be a symbol. Mouse shortcuts
|
||||
* name the button 1-based (`Button1` = left, `Button4` = back side button, `Button5` = forward),
|
||||
* or the wheel direction (`WheelUp`, `WheelDown`), optionally with modifiers.
|
||||
* optionally with modifiers (`Alt+Button4`); they are single strokes.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { executeAction, executeActionFrom, getAction, isActionKeyEnabled } from "./actions";
|
||||
@@ -79,45 +79,24 @@ interface KeymapState {
|
||||
export const useKeymap = create<KeymapState>(() => ({ preset: defaultPreset(), overrides: {}, extensions: {} }));
|
||||
|
||||
const MOUSE_KEY_RE = /^Button(\d+)$/i;
|
||||
const WHEEL_KEY_RE = /^Wheel(Up|Down)$/i;
|
||||
type ModifierKeys = Pick<MouseEvent, "metaKey" | "ctrlKey" | "altKey" | "shiftKey">;
|
||||
|
||||
export function isWheelBinding(binding: string): boolean {
|
||||
const b = binding.trim();
|
||||
return !/\s/.test(b) && WHEEL_KEY_RE.test(b.split("+").pop()!);
|
||||
}
|
||||
|
||||
/** A mouse button or wheel shortcut. */
|
||||
/** A mouse shortcut (`Button4`, `Shift+Button5`) rather than a keystroke. */
|
||||
export function isMouseBinding(binding: string): boolean {
|
||||
const b = binding.trim();
|
||||
const key = b.split("+").pop()!;
|
||||
return !/\s/.test(b) && (MOUSE_KEY_RE.test(key) || WHEEL_KEY_RE.test(key));
|
||||
}
|
||||
|
||||
/** Editor mouse-selection actions require a button and pointer position. */
|
||||
export function supportsWheelShortcut(actionId: string): boolean {
|
||||
return actionId !== "editor.createRectangularSelectionOnMouseDrag" && actionId !== "editor.addOrRemoveCaret";
|
||||
}
|
||||
|
||||
function modifiedStroke(e: ModifierKeys, key: string): string {
|
||||
const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean);
|
||||
return [...mods, key].join("+");
|
||||
return !/\s/.test(b) && MOUSE_KEY_RE.test(b.split("+").pop()!);
|
||||
}
|
||||
|
||||
/**
|
||||
* Middle/side buttons, or a left click with Ctrl/Alt/Meta. Plain and Shift-only
|
||||
* left clicks keep selection semantics; right clicks keep the context menu.
|
||||
*/
|
||||
export function mouseStrokeOf(e: Pick<MouseEvent, "button"> & ModifierKeys): string | null {
|
||||
export function mouseStrokeOf(
|
||||
e: Pick<MouseEvent, "button" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
|
||||
): string | null {
|
||||
if (!Number.isInteger(e.button) || e.button < 0) return null;
|
||||
if (e.button === 2 || (e.button === 0 && !(e.ctrlKey || e.altKey || e.metaKey))) return null;
|
||||
return modifiedStroke(e, `Button${e.button + 1}`);
|
||||
}
|
||||
|
||||
/** Recognizes vertical wheel input for both capture and dispatch. */
|
||||
export function wheelStrokeOf(e: Pick<WheelEvent, "deltaX" | "deltaY"> & ModifierKeys): string | null {
|
||||
if (!e.deltaY || Math.abs(e.deltaY) < Math.abs(e.deltaX)) return null;
|
||||
return modifiedStroke(e, e.deltaY < 0 ? "WheelUp" : "WheelDown");
|
||||
const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean);
|
||||
return [...mods, `Button${e.button + 1}`].join("+");
|
||||
}
|
||||
|
||||
const STROKE_RE = /^(?:(?:Ctrl|Alt|Shift|Meta)\+)*[^\s+]+$|^(?:(?:Ctrl|Alt|Shift|Meta)\+)*\+$/i;
|
||||
@@ -139,9 +118,8 @@ export function parseDoubleModifier(binding: string): { modifier: Modifier; key:
|
||||
export function isValidBinding(binding: unknown): binding is string {
|
||||
if (typeof binding !== "string") return false;
|
||||
const b = binding.trim();
|
||||
const strokes = b.split(/\s+/);
|
||||
if (strokes.some(isWheelBinding)) return strokes.length === 1 && STROKE_RE.test(b);
|
||||
if (parseDoubleModifier(b)) return true;
|
||||
const strokes = b.split(/\s+/);
|
||||
if (strokes.some((s) => /swipe(left|right)$/i.test(s))) {
|
||||
return strokes.length === 1 && /^swipe(left|right)$/i.test(b);
|
||||
}
|
||||
@@ -320,10 +298,8 @@ export function normalizeBinding(binding: string): string {
|
||||
const key = parts.pop()!;
|
||||
const mods = MOD_ORDER.filter((m) => parts.some((p) => p.toLowerCase() === m.toLowerCase()));
|
||||
const mouse = MOUSE_KEY_RE.exec(key);
|
||||
const wheel = WHEEL_KEY_RE.exec(key);
|
||||
const swipe = /^swipe(left|right)$/i.exec(key);
|
||||
if (swipe) return `Swipe${swipe[1]!.toLowerCase() === "left" ? "Left" : "Right"}`;
|
||||
if (wheel) return [...mods, wheel[1]!.toLowerCase() === "up" ? "WheelUp" : "WheelDown"].join("+");
|
||||
return [...mods, mouse ? `Button${mouse[1]}` : key.length === 1 ? key.toUpperCase() : key].join("+");
|
||||
})
|
||||
.join(" ");
|
||||
@@ -390,7 +366,8 @@ export function strokeOf(
|
||||
if (["Shift", "Meta", "Control", "Alt"].includes(e.key)) return null;
|
||||
key = e.key.length === 1 ? e.key.toUpperCase() : e.key;
|
||||
}
|
||||
return modifiedStroke(e, key);
|
||||
const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean);
|
||||
return [...mods, key].join("+");
|
||||
}
|
||||
|
||||
const SYMBOLS: Record<string, string> = {
|
||||
@@ -427,12 +404,8 @@ export function formatBinding(binding: string, mac = isMacHost()): string {
|
||||
if (isMouseBinding(binding)) {
|
||||
const parts = normalizeBinding(binding).split("+");
|
||||
const key = parts.pop();
|
||||
let label = `${key} Click`;
|
||||
if (key === "WheelUp") label = tx("Wheel Up");
|
||||
if (key === "WheelDown") label = tx("Wheel Down");
|
||||
if (key === "Button1") label = "Left Click";
|
||||
if (key === "Button2") label = tx("Middle Click");
|
||||
return mac ? parts.map((p) => SYMBOLS[p] ?? p).join("") + label : [...parts, label].join("+");
|
||||
const button = key === "Button1" ? "Left Click" : key === "Button2" ? tx("Middle Click") : `${key} Click`;
|
||||
return mac ? parts.map((p) => SYMBOLS[p] ?? p).join("") + button : [...parts, button].join("+");
|
||||
}
|
||||
if (!mac)
|
||||
return normalizeBinding(binding)
|
||||
@@ -471,13 +444,6 @@ const CHORD_TIMEOUT = 2000;
|
||||
const DOUBLE_TAP_STEP_MS = 300;
|
||||
/** A modifier tap this soon after typing another key is part of typing, not a gesture. */
|
||||
const DOUBLE_TAP_TYPING_GUARD_MS = 100;
|
||||
const WHEEL_GESTURE_GAP_MS = 150;
|
||||
|
||||
function isDiscreteWheelEvent(e: WheelEvent): boolean {
|
||||
// WebViews also send mouse notches in pixel mode, with legacy ticks in units of 120.
|
||||
const ticks = (e as WheelEvent & { wheelDeltaY?: number }).wheelDeltaY;
|
||||
return e.deltaMode !== WheelEvent.DOM_DELTA_PIXEL || (!!ticks && ticks % 120 === 0);
|
||||
}
|
||||
|
||||
const KEY_MODIFIER: Record<string, Modifier> = { Shift: "Shift", Control: "Ctrl", Alt: "Alt", Meta: "Meta" };
|
||||
|
||||
@@ -703,7 +669,6 @@ export function installKeyboardDispatcher(
|
||||
): () => void {
|
||||
let pending: string[] = [];
|
||||
let pendingTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let wheelGesture: { direction: number; at: number; binding: string | null } | null = null;
|
||||
const doubleModifier = createDoubleModifierRecognizer(now);
|
||||
|
||||
const reset = () => {
|
||||
@@ -854,39 +819,6 @@ export function installKeyboardDispatcher(
|
||||
for (const id of ids.reverse()) if (runIfEnabled(id)) return;
|
||||
};
|
||||
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
doubleModifier.reset();
|
||||
if (suspended > 0 || e.defaultPrevented) {
|
||||
wheelGesture = null;
|
||||
return;
|
||||
}
|
||||
const stroke = wheelStrokeOf(e);
|
||||
if (!stroke) return;
|
||||
const consume = () => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
const direction = Math.sign(e.deltaY);
|
||||
// Treat a continuous burst as one gesture, including momentum. Modifiers pressed
|
||||
// during the burst must not turn an ordinary scroll into a shortcut.
|
||||
if (wheelGesture?.direction === direction && e.timeStamp - wheelGesture.at <= WHEEL_GESTURE_GAP_MS) {
|
||||
wheelGesture.at = e.timeStamp;
|
||||
if (wheelGesture.binding === stroke) consume();
|
||||
return;
|
||||
}
|
||||
wheelGesture = isDiscreteWheelEvent(e) ? null : { direction, at: e.timeStamp, binding: null };
|
||||
const match = effectiveBindings().findLast(([binding, id]) => {
|
||||
if (binding !== stroke || !supportsWheelShortcut(id)) return false;
|
||||
const action = getAction(id);
|
||||
return !!action && isActionKeyEnabled(action);
|
||||
});
|
||||
if (!match) return;
|
||||
if (wheelGesture) wheelGesture.binding = stroke;
|
||||
consume();
|
||||
reset();
|
||||
void executeActionFrom("keyboard", match[1]);
|
||||
};
|
||||
|
||||
/** The release of a side button: swallowed so the webview doesn't navigate its own history. */
|
||||
const onMouseRelease = (e: MouseEvent) => {
|
||||
if (e.button < 3) return;
|
||||
@@ -900,7 +832,6 @@ export function installKeyboardDispatcher(
|
||||
const onBlur = () => {
|
||||
reset();
|
||||
doubleModifier.reset();
|
||||
wheelGesture = null;
|
||||
};
|
||||
|
||||
const onSwipe = (event: Event) => {
|
||||
@@ -917,7 +848,6 @@ export function installKeyboardDispatcher(
|
||||
target.addEventListener("keydown", onKeyDown, true);
|
||||
target.addEventListener("keyup", onKeyUp, true);
|
||||
target.addEventListener("mousedown", onMouseDown, true);
|
||||
target.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
target.addEventListener("mouseup", onMouseRelease, true);
|
||||
target.addEventListener("auxclick", onMouseRelease, true);
|
||||
target.addEventListener("webkitmouseforcewillbegin", onForceWillBegin, true);
|
||||
@@ -927,7 +857,6 @@ export function installKeyboardDispatcher(
|
||||
target.removeEventListener("keydown", onKeyDown, true);
|
||||
target.removeEventListener("keyup", onKeyUp, true);
|
||||
target.removeEventListener("mousedown", onMouseDown, true);
|
||||
target.removeEventListener("wheel", onWheel, true);
|
||||
target.removeEventListener("mouseup", onMouseRelease, true);
|
||||
target.removeEventListener("auxclick", onMouseRelease, true);
|
||||
target.removeEventListener("webkitmouseforcewillbegin", onForceWillBegin, true);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
applyKeymapSettings,
|
||||
bindingsFor,
|
||||
formatBinding,
|
||||
dispatchMouseShortcut,
|
||||
installKeyboardDispatcher,
|
||||
@@ -78,37 +76,6 @@ describe("mouse shortcuts", () => {
|
||||
expect(shortcutLabel("t.mouseFirst")).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["en", "Wheel Up", "Wheel Down"],
|
||||
["zh", "滚轮向上", "滚轮向下"],
|
||||
])("formats wheel directions in %s", async (locale, up, down) => {
|
||||
const originalLocale = useI18n.getState().locale;
|
||||
try {
|
||||
await setLocale(locale);
|
||||
expect(formatBinding("ctrl+wheelup", false)).toBe(`Ctrl+${up}`);
|
||||
expect(formatBinding("meta+shift+wheeldown", true)).toBe(`⇧⌘${down}`);
|
||||
} finally {
|
||||
await setLocale(originalLocale);
|
||||
}
|
||||
});
|
||||
|
||||
it("loads canonical single-stroke wheel bindings from preset and custom overrides", () => {
|
||||
const original = useKeymap.getState();
|
||||
const overrides = {
|
||||
"t.wheel": ["alt+ctrl+wheelup", "Ctrl+Alt+WheelUp", "WheelDown", "Ctrl+K WheelDown", "Alt Alt+WheelUp"],
|
||||
};
|
||||
try {
|
||||
for (const id of ["intellij-windows", "user:wheel"]) {
|
||||
applyKeymapSettings(id, overrides, { "user:wheel": { parent: "intellij-windows", overrides } });
|
||||
expect(bindingsFor("t.wheel")).toEqual(["Ctrl+Alt+WheelUp", "WheelDown"]);
|
||||
expect(bindingsFor("t.wheel").every(isMouseBinding)).toBe(true);
|
||||
expect(primaryKeyBinding("t.wheel")).toBeUndefined();
|
||||
}
|
||||
} finally {
|
||||
useKeymap.setState(original);
|
||||
}
|
||||
});
|
||||
|
||||
describe("dispatch", () => {
|
||||
let uninstall = () => {};
|
||||
const back = vi.fn();
|
||||
@@ -138,45 +105,6 @@ describe("mouse shortcuts", () => {
|
||||
return events;
|
||||
};
|
||||
|
||||
const wheel = (init: WheelEventInit, at: number, ticks?: number) => {
|
||||
const event = new WheelEvent("wheel", { deltaY: -1, bubbles: true, cancelable: true, ...init });
|
||||
Object.defineProperty(event, "timeStamp", { value: at });
|
||||
if (ticks !== undefined) Object.defineProperty(event, "wheelDeltaY", { value: ticks });
|
||||
editor.dispatchEvent(event);
|
||||
return event;
|
||||
};
|
||||
|
||||
it("consumes one shortcut per notch and leaves unmatched and horizontal scroll events alone", () => {
|
||||
useKeymap.setState({ overrides: { "navigate.back": ["Ctrl+WheelUp"], "navigate.forward": ["WheelDown"] } });
|
||||
const scroll = vi.fn();
|
||||
editor.addEventListener("wheel", scroll);
|
||||
expect(wheel({ ctrlKey: true, deltaMode: WheelEvent.DOM_DELTA_LINE }, 1).defaultPrevented).toBe(true);
|
||||
expect(wheel({ ctrlKey: true }, 2, 120).defaultPrevented).toBe(true);
|
||||
expect(wheel({ ctrlKey: true }, 3, 120).defaultPrevented).toBe(true);
|
||||
expect(wheel({ deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_LINE }, 4).defaultPrevented).toBe(true);
|
||||
expect(wheel({ ctrlKey: true, deltaY: 1 }, 5).defaultPrevented).toBe(false);
|
||||
expect(wheel({ ctrlKey: true, deltaY: 0, deltaX: -10 }, 6).defaultPrevented).toBe(false);
|
||||
expect(wheel({ deltaMode: WheelEvent.DOM_DELTA_LINE }, 7).defaultPrevented).toBe(false);
|
||||
expect(back).toHaveBeenCalledTimes(3);
|
||||
expect(forward).toHaveBeenCalledOnce();
|
||||
expect(scroll).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("swallows a bound trackpad burst without repeating the action or taking over unbound momentum", () => {
|
||||
useKeymap.setState({ overrides: { "navigate.back": ["Alt+WheelUp"], "navigate.forward": ["Alt+WheelDown"] } });
|
||||
expect(wheel({ deltaY: -30 }, 0).defaultPrevented).toBe(false);
|
||||
expect(wheel({ altKey: true, deltaY: -20 }, 20).defaultPrevented).toBe(false);
|
||||
expect(back).not.toHaveBeenCalled();
|
||||
expect(wheel({ altKey: true, deltaY: -30 }, 200).defaultPrevented).toBe(true);
|
||||
expect(wheel({ altKey: true, deltaY: -20 }, 220).defaultPrevented).toBe(true);
|
||||
expect(wheel({ altKey: true, deltaY: -10 }, 240).defaultPrevented).toBe(true);
|
||||
expect(back).toHaveBeenCalledOnce();
|
||||
expect(wheel({ altKey: true, deltaY: 20 }, 260).defaultPrevented).toBe(true);
|
||||
expect(forward).toHaveBeenCalledOnce();
|
||||
expect(wheel({ altKey: true, deltaY: -30 }, 450).defaultPrevented).toBe(true);
|
||||
expect(back).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not prepare the editor for a disabled mouse action", () => {
|
||||
const run = vi.fn();
|
||||
const prepare = vi.fn(() => true);
|
||||
|
||||
@@ -981,10 +981,6 @@
|
||||
"Add or Remove Caret": "Add or Remove Caret",
|
||||
"Create Rectangular Selection on Mouse Drag": "Create Rectangular Selection on Mouse Drag",
|
||||
"Middle Click": "Middle Click",
|
||||
"Wheel Up": "Wheel Up",
|
||||
"Wheel Down": "Wheel Down",
|
||||
"This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.": "This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.",
|
||||
"Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button": "Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button",
|
||||
"On Linux, middle-button rectangular selection conflicts with primary selection paste.": "On Linux, middle-button rectangular selection conflicts with primary selection paste.",
|
||||
"Click here with Ctrl, Alt or Command held, or use a middle or side mouse button": "Click here with Ctrl, Alt or Command held, or use a middle or side mouse button",
|
||||
"Click here with Ctrl, Alt or Command held, or use the middle mouse button": "Click here with Ctrl, Alt or Command held, or use the middle mouse button",
|
||||
|
||||
@@ -988,10 +988,6 @@
|
||||
"Add or Remove Caret": "添加或移除插入点",
|
||||
"Create Rectangular Selection on Mouse Drag": "拖动鼠标创建矩形选区",
|
||||
"Middle Click": "鼠标中键",
|
||||
"Wheel Up": "滚轮向上",
|
||||
"Wheel Down": "滚轮向下",
|
||||
"This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.": "此操作可用时,该快捷键优先于 Ctrl/Command+鼠标滚轮字体缩放。",
|
||||
"Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button": "在此滚动鼠标滚轮,按住 Ctrl、Alt 或 Command 点击,或使用鼠标中键或侧键",
|
||||
"On Linux, middle-button rectangular selection conflicts with primary selection paste.": "在 Linux 上,中键矩形拖选会与主选区粘贴冲突。",
|
||||
"Add Carets to Ends of Selected Lines": "在所选行末尾添加光标",
|
||||
"Unselect Occurrence": "取消选择匹配项",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { loadPlatformInfo, usePlatform } from "./platformInfo";
|
||||
import { appDataDir, loadPlatformInfo, usePlatform } from "./platformInfo";
|
||||
|
||||
const appInfo = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/platform/ipc", () => ({ isTauri: () => true, commands: { appInfo } }));
|
||||
@@ -24,6 +24,11 @@ it("keeps platform defaults when the query fails", async () => {
|
||||
expect(usePlatform.getState()).toEqual(initialPlatform);
|
||||
});
|
||||
|
||||
it("takes the user data directory from the backend, which may have moved it", async () => {
|
||||
appInfo.mockResolvedValue({ platform: "windows", dataDir: "E:/OpenIDEA/ai.l0ng.openidea/" });
|
||||
expect(await appDataDir()).toBe("E:/OpenIDEA/ai.l0ng.openidea");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
{ left: ["close", "maximize", "minimize"], right: [] },
|
||||
|
||||
@@ -41,6 +41,14 @@ export const usePlatform = create<PlatformInfo>(() => {
|
||||
};
|
||||
});
|
||||
|
||||
let dataDir: Promise<string> | undefined;
|
||||
|
||||
/** The user data directory (scratches, plugins, Local History), which `OPENIDEA_DATA_DIR` can move. */
|
||||
export function appDataDir(): Promise<string> {
|
||||
dataDir ??= commands.appInfo().then((info) => info.dataDir.replace(/\/+$/, ""));
|
||||
return dataDir;
|
||||
}
|
||||
|
||||
export async function loadPlatformInfo() {
|
||||
if (!isTauri()) return;
|
||||
try {
|
||||
|
||||
@@ -4,7 +4,6 @@ import { call, commands, type ChannelFrame, type ExecutionEvent, type ProjectInf
|
||||
import { useProject } from "./project";
|
||||
import { disableRemote, enableRemote, useRemote } from "./remote";
|
||||
import { encodeArgs, remoteRouting } from "./remote";
|
||||
import { scratchesDir } from "./scratchesDir";
|
||||
|
||||
describe("remote invoke", () => {
|
||||
beforeAll(() => {
|
||||
@@ -55,33 +54,6 @@ describe("remote invoke", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("routes a scratch folder lookup made as soon as the remote session is published", async () => {
|
||||
const invoke = vi.fn(async (command: string, args: { cmd: string }) => {
|
||||
expect(command).toBe("remote_invoke");
|
||||
expect(args.cmd).toBe("fs_scratches_dir");
|
||||
return JSON.stringify("/home/me/.openidea/data/scratches");
|
||||
});
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", { invoke, transformCallback: () => 1 });
|
||||
const unsubscribe = useRemote.subscribe(({ session }) => {
|
||||
if (session) void scratchesDir();
|
||||
});
|
||||
try {
|
||||
enableRemote({
|
||||
target: { kind: "ssh", config: "test" },
|
||||
root: "/home/me/project",
|
||||
host: "test",
|
||||
os: "linux",
|
||||
commands: ["fs_scratches_dir"],
|
||||
});
|
||||
await expect(scratchesDir()).resolves.toBe("/home/me/.openidea/data/scratches");
|
||||
expect(invoke).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
disableRemote();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("routes served commands, keeps opening / closing local and sets global settings on both sides", () => {
|
||||
const served = new Set([
|
||||
"vcs_add_to_ignore",
|
||||
|
||||
@@ -153,8 +153,8 @@ const route: InvokeRoute = (cmd, args, options) => {
|
||||
*/
|
||||
export function enableRemote(session: RemoteSession) {
|
||||
routed = new Set(session.commands);
|
||||
setInvokeRoute(route);
|
||||
useRemote.setState({ session, lost: null, reconnecting: false });
|
||||
setInvokeRoute(route);
|
||||
}
|
||||
|
||||
export function disableRemote() {
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { useRemote } from "./remote";
|
||||
import { scratchesDir } from "./scratchesDir";
|
||||
|
||||
// Routed like every file command: the server answers in a remote window.
|
||||
const fsScratchesDir = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const m = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...m, call: async (p: Promise<unknown>) => await p, commands: { ...m.commands, fsScratchesDir } };
|
||||
});
|
||||
|
||||
afterEach(() => useRemote.setState({ session: null }));
|
||||
|
||||
it("asks the host again once the window attaches to or leaves a remote server", async () => {
|
||||
fsScratchesDir.mockResolvedValue("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches/");
|
||||
const pending = scratchesDir();
|
||||
expect(scratchesDir()).toBe(pending);
|
||||
expect(await pending).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
|
||||
expect(await scratchesDir()).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
|
||||
expect(fsScratchesDir).toHaveBeenCalledTimes(2);
|
||||
|
||||
fsScratchesDir.mockResolvedValue("/home/me/.openidea/data/scratches");
|
||||
useRemote.setState({ session: { root: "/home/me/project" } as never });
|
||||
expect(await scratchesDir()).toBe("/home/me/.openidea/data/scratches");
|
||||
|
||||
fsScratchesDir.mockResolvedValue("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
|
||||
useRemote.setState({ session: null });
|
||||
expect(await scratchesDir()).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
|
||||
expect(fsScratchesDir).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("asks again after a failure", async () => {
|
||||
useRemote.setState({ session: { root: "/p" } as never });
|
||||
fsScratchesDir.mockRejectedValueOnce(new Error("disconnected"));
|
||||
await expect(scratchesDir()).rejects.toThrow("disconnected");
|
||||
fsScratchesDir.mockResolvedValue("/home/me/.openidea/data/scratches");
|
||||
expect(await scratchesDir()).toBe("/home/me/.openidea/data/scratches");
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
|
||||
let dir: Promise<string> | null = null;
|
||||
|
||||
// A window attaches to (or leaves) a remote server in place: the folder is then another host's.
|
||||
useRemote.subscribe((state, previous) => {
|
||||
if (state.session !== previous.session) dir = null;
|
||||
});
|
||||
|
||||
/**
|
||||
* The scratch files' folder (`<user data>/scratches`) of the host that runs this window's file
|
||||
* commands: the server in a remote window, this machine otherwise. Ensures the folder exists.
|
||||
*/
|
||||
export function scratchesDir(): Promise<string> {
|
||||
if (!dir) {
|
||||
const pending = call(commands.fsScratchesDir())
|
||||
.then((path) => path.replace(/\/+$/, ""))
|
||||
.finally(() => {
|
||||
if (dir === pending) dir = null;
|
||||
});
|
||||
dir = pending;
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
@@ -56,7 +56,7 @@
|
||||
background: var(--tab-tint-mix);
|
||||
}
|
||||
.item[data-tinted]:hover {
|
||||
background: color-mix(in srgb, var(--project-color) 12%, var(--bg-hover));
|
||||
background: linear-gradient(var(--bg-hover), var(--bg-hover)), var(--tab-tint-mix);
|
||||
}
|
||||
.selected[data-tinted],
|
||||
.selected[data-tinted]:hover {
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
/>
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача