Compare commits

...
Author SHA1 Message Date
l0ng-ai 0177ee52bc fix(keymap): support mouse wheel shortcuts 2026-11-23 23:57:00 +08:00
l0ng-ai 431b87c717 fix(remote): use the correct filesystem for file dialogs (#5479)
In an SSH or WSL window, Export Test Results passed a path picked in the desktop's Save dialog to the project host. Project-side pickers (Export Test Results, Save As, patch and Git dialogs, Maven/Gradle linking, scopes, coverage and Java sources, database source files, deployment destinations, tool and plugin paths) now browse the project host, with overwrite confirmation kept; flows whose files belong to the desktop (keymap and color scheme import/export, database and ACP imports, Clone) read and write through the desktop process. Follow-up to #5439.
2026-11-23 23:22:47 +08:00
l0ng-ai 3a53d13315 fix(editor): refresh Java inheritance markers after Maven import (#5478)
Interface methods could show no "is implemented" marker: the gutter cached the empty implementation results jdtls gave before the Maven import put the implementations on the classpath, and nothing invalidated them. When jdtls reports the project status after an import (generated sources attached first), the backend now emits an inheritance refresh next to the semantic-token refresh, and the gutter drops its cached markers and asks again. Covers implemented/overridden markers on interfaces, abstract classes and concrete overrides.
2026-11-23 23:20:57 +08:00
Mr0Bread 23f591289c perf(ipc): send binary command arguments as base64 instead of number arrays (#5436)
Pasting an image into a terminal or a Markdown file, or saving bytes from the UI, sent the data as a JSON array of numbers (3.6x the size), which Tauri and the remote server parse into a serde_json::Value first (~50x the bytes in memory: a 20 MB image took ~2.2 GB peak heap and 640 ms). Binary command arguments (fs_create_file_bytes, term_store_image) now travel as base64 text (IpcBytes): the same 20 MB takes ~112 MB and 32 ms. Native image drops reuse the base64 they already have.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 22:32:58 +08:00
l0ng-ai 8684e95778 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH (#5474) 2026-11-23 22:27:28 +08:00
Bert Verhelstandbertyhell 9d9e3f1c4f fix(java): don't reuse a launch snapshot copied while another build rewrote the outputs (#5420)
A Java launch that delegates to Maven could snapshot a dependency module's target/classes while an external mvn was rewriting it, then reuse that incomplete snapshot on every later launch (NoClassDefFoundError until the cache was cleared). A snapshot is now reused only while the live module outputs still match it (paths, sizes and modification times of the output tree, read from metadata only); output directories that appear after capture also invalidate it.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:59 +08:00
88 changed files with 1541 additions and 301 deletions

No files matched your search

Generated
+1
View File
@@ -4253,6 +4253,7 @@ dependencies = [
name = "ide-core"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
+56 -8
View File
@@ -1008,12 +1008,7 @@ pub fn build_for_launches(
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
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()
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
} else {
launch_class_dirs(plan.system, module, test)
}
@@ -1021,6 +1016,60 @@ 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 {
@@ -1031,8 +1080,7 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
BuildSystem::Maven => maven_output_dirs(module, test),
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
+1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
+2
View File
@@ -324,6 +324,8 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
+122
View File
@@ -0,0 +1,122 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
+2
View File
@@ -12,6 +12,7 @@ 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;
@@ -37,6 +38,7 @@ pub mod wsl;
pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath;
pub use text::*;
pub use tokio_util::sync::CancellationToken;
+2 -2
View File
@@ -1,7 +1,7 @@
use super::Channel;
use crate::{Host, Project};
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_core::{IdeError, IdeResult, IpcBytes, 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: Vec<u8>) -> IdeResult<()> {
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: IpcBytes) -> IdeResult<()> {
let project = host.project(window).ok();
host.blocking(move || {
ide_vfs::create_file_bytes(&path, &data)?;
+267 -8
View File
@@ -6,14 +6,20 @@ 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
@@ -23,12 +29,93 @@ pub(super) struct Outputs {
}
impl Outputs {
fn reusable(&self, fingerprint: &Option<LaunchFingerprint>, snapshots: &Path) -> bool {
fn reusable(
&self,
fingerprint: &Option<LaunchFingerprint>,
snapshots: &Path,
output_dirs: impl Iterator<Item = PathBuf>,
cancel: &CancellationToken,
) -> bool {
fingerprint.is_some()
&& self.fingerprint == *fingerprint
&& self.snapshot.parent() == Some(snapshots)
&& !self.originals.is_empty()
&& (0..self.originals.len()).all(|i| self.snapshot.join(i.to_string()).is_dir())
&& self.output_stamps.as_ref().is_some_and(|stamps| {
stamps.len() == self.originals.len()
&& output_dirs.eq(self.originals.iter().cloned())
&& self.originals.iter().zip(stamps).enumerate().all(|(i, (dir, stamp))| {
Contents::scan(dir, cancel).is_some_and(|live| live.stamp() == stamp.live)
&& Contents::scan(&self.snapshot.join(i.to_string()), cancel)
.is_some_and(|copy| copy.class_stamp() == stamp.snapshot_classes)
})
})
}
}
#[derive(Debug, Serialize, Deserialize)]
struct OutputStamp {
live: u64,
// A launched app may write non-class files under its snapshot classpath root.
snapshot_classes: u64,
}
/// Relative paths, sizes and mtimes are enough to detect ordinary compiler rewrites
/// without reading class or resource bytes.
#[derive(Debug, PartialEq, Eq)]
struct Contents(Vec<(PathBuf, u64, SystemTime)>);
impl Contents {
fn scan(root: &Path, cancel: &CancellationToken) -> Option<Self> {
if !fs::metadata(root).ok()?.is_dir() {
return None;
}
let mut files = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return None;
}
for entry in fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let meta = entry.metadata().ok()?;
let path = entry.path();
if meta.is_dir() {
pending.push(path);
} else {
files.push((path.strip_prefix(root).ok()?.to_path_buf(), meta.len(), meta.modified().ok()?));
}
}
}
files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
Some(Self(files))
}
fn stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn classes(&self) -> impl Iterator<Item = &(PathBuf, u64, SystemTime)> {
self.0.iter().filter(|(path, _, _)| path.extension().is_some_and(|ext| ext == "class"))
}
fn class_stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
for file in self.classes() {
file.hash(&mut hasher);
}
hasher.finish()
}
fn matches_copy(&self, copy: &Self) -> bool {
// Copying preserves relative paths and sizes. Each tree has its own mtimes.
self.0.len() == copy.0.len()
&& self
.0
.iter()
.zip(&copy.0)
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
}
}
@@ -280,13 +367,23 @@ impl Session {
}
if let Some(outputs) = previous.as_ref()
&& policy != BuildPolicy::Rebuild
&& outputs.reusable(&before, &snapshots)
&& 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()
{
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())?;
@@ -317,6 +414,7 @@ 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());
@@ -327,8 +425,43 @@ impl Session {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after {
// 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 {
outputs.fingerprint = pending.before;
write_record(&pending.record, &outputs)?;
self.unreferenced.retain(|path| path != &outputs.snapshot);
@@ -722,7 +855,7 @@ mod tests {
assert!(reused.authoritative);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
let rebuilt = session
.build(
root,
@@ -735,6 +868,7 @@ 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"));
@@ -756,8 +890,6 @@ 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();
@@ -893,6 +1025,7 @@ mod tests {
fingerprint: None,
snapshot: retained.clone(),
originals: Vec::new(),
output_stamps: None,
failure: None,
authoritative: false,
};
@@ -953,6 +1086,132 @@ 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();
+5 -4
View File
@@ -1,7 +1,7 @@
use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, TerminalId};
use ide_core::{IdeResult, IpcBytes, 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: Vec<u8>, mime: String) -> IdeResult<String> {
pub async fn term_store_image(host: &Host, id: TerminalId, data: IpcBytes, 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,10 +201,11 @@ mod tests {
project_environment: false,
});
let id = TerminalId::next();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
let error =
term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1].into(), "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], "image/png".into()).await.unwrap_err();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES].into(), "image/png".into()).await.unwrap_err();
assert_eq!(error.message, "terminal session not found");
assert!(!host.data_dir.join("terminal-images").exists());
}
+2 -1
View File
@@ -27,7 +27,8 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
pub const PROTOCOL_VERSION: u32 = 2;
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
pub const PROTOCOL_VERSION: u32 = 3;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
+70
View File
@@ -0,0 +1,70 @@
//! 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());
}
+8 -4
View File
@@ -21,7 +21,7 @@ async fn storage_requires_a_registered_terminal() {
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1], "image/png".into()).await.is_err());
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1].into(), "image/png".into()).await.is_err());
assert!(!data_dir.join("terminal-images").exists());
let terminal = host
.terminals
@@ -41,11 +41,15 @@ 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], mime.into()).await.unwrap();
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3].into(), 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], "application/octet-stream".into()).await.is_err());
assert!(
ops::term::term_store_image(&host, terminal.id, vec![1].into(), "application/octet-stream".into())
.await
.is_err()
);
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::term_store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
assert!(ops::term::term_store_image(&host, terminal.id, vec![4].into(), "image/png".into()).await.is_err());
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 3);
}
+6 -8
View File
@@ -8,6 +8,7 @@
use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::ErrorKind;
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -646,10 +647,8 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
/// Open editors may have cached empty tokens or inheritance results during the import.
/// Attach generated Maven sources before refreshing either, so both see the new classpath.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -666,10 +665,9 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
}
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
+9 -7
View File
@@ -3166,7 +3166,7 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_semantic_tokens() {
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
@@ -3175,20 +3175,22 @@ async fn a_project_update_refreshes_java_semantic_tokens() {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
.filter_map(|e| match e {
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
_ => None,
})
.collect::<Vec<_>>()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(refreshes(), 0);
assert!(refreshes().is_empty());
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
// A later import may add tokens and implementation targets to open editors.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == 1).await;
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
}
#[tokio::test(flavor = "multi_thread")]
+1 -1
View File
@@ -64,7 +64,7 @@ JSON-RPC 2.0 with `Content-Length` framing (`ide-jsonrpc`), over the server's st
| notification `plugin` | server → client | `{ window, event }` from code plugins of the remote project |
| request `plugin_secret` | server → client | `{ plugin, name }` → `string` or `null`: a secret from the desktop's keychain |
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`. 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`; 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.
## Routing commands
+1 -1
View File
@@ -64,7 +64,7 @@ openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <por
| 通知 `plugin` | 服务端 → 客户端 | `{ window, event }`:远程项目中代码插件发出的事件 |
| 请求 `plugin_secret` | 服务端 → 客户端 | `{ plugin, name }` → `string` 或 `null`:从桌面端钥匙串取密钥 |
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`;桌面端会拒绝使用其他版本协议的服务端。已有命令的参数或结果形态改变时要修改它。二进制参数使用 `IpcBytes`(JSON 中是 base64 字符串,绑定中是 `string`),不要用 `Vec<u8>`——它会变成体积约 3.6 倍的数字数组。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
## 命令路由
+31
View File
@@ -93,6 +93,37 @@ 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,
}) => {
+3 -3
View File
@@ -11,11 +11,11 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
configurable: true,
value: { transformCallback: () => 1 },
});
const stored: { id: number; data: number[]; mime: string }[] = [];
const stored: { id: number; data: string; 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: number[], mime: string) => {
commands.termStoreImage = async (id: number, data: string, 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: [137, 80, 78, 71], mime: "image/png" }]);
expect(observed.stored).toEqual([{ id: 838, data: "iVBORw==", mime: "image/png" }]);
expect(observed.writes).toEqual(["'C:\\Temp\\a''b c\\image.png'"]);
});
+7 -2
View File
@@ -680,7 +680,7 @@ export const commands = {
* `charset` (writes the BOM for `utf-8-bom` / UTF-16).
*/
fsCreateFile: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file", { path })),
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
fsCreateFileBytes: (path: string, data: IpcBytes) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
/** Moving to the trash can take a while (large trees): kept off the main thread. */
fsDelete: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_delete", { path })),
/** Moves an item to the Trash and returns the snapshot for Project View Undo. */
@@ -1823,7 +1823,7 @@ export const commands = {
* to start the shell takes tens of milliseconds, a frozen UI if run there.
*/
termSpawn: (options: TerminalOptions, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("term_spawn", { options, onOutput })),
termStoreImage: (id: TerminalId, data: number[], mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termStoreImage: (id: TerminalId, data: IpcBytes, 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,6 +8371,9 @@ 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;
@@ -9202,6 +9205,8 @@ export type LogcatLine = {
};
export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" |
/** An import or classpath update may have changed inheritance search results. */
"inheritance" |
/** The Dart server published a document's Flutter outline. */
"flutterOutline";
+2 -2
View File
@@ -172,10 +172,10 @@ it.each([
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
onmessage?: (e: { data: { data: string } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
}
},
);
+4 -7
View File
@@ -1,12 +1,9 @@
import { toBase64 } from "@/platform/base64";
// Keep binary conversion off the editor thread, including for large clipboard images.
self.onmessage = async (event: MessageEvent<Blob | string>) => {
self.onmessage = async (event: MessageEvent<Blob>) => {
try {
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 });
self.postMessage({ data: toBase64(new Uint8Array(await event.data.arrayBuffer())) });
} catch (error) {
self.postMessage({ error: String(error) });
}
+22 -8
View File
@@ -3,6 +3,7 @@ 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[] = [];
@@ -38,9 +39,7 @@ 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", [0, 255], create)).toBe(
"![](assets/photo-2.png)",
);
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", "AP8=", create)).toBe("![](assets/photo-2.png)");
expect(create.mock.calls.map(([path]) => path)).toEqual([
"/p/docs/assets/photo.png",
"/p/docs/assets/photo-1.png",
@@ -49,7 +48,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", () => {
@@ -82,10 +81,10 @@ describe("Markdown images", () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
onmessage?: (e: { data: { data: string } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
}
},
);
@@ -98,16 +97,31 @@ describe("Markdown images", () => {
paste(editor, [new File(["png"], "image.png", { type: "image/png" })]);
await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1));
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
});
it("writes the base64 from a native image drop directly", async () => {
const invoke = vi.fn().mockResolvedValue("data:image/png;base64,AP8=");
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const editor = view();
vi.spyOn(editor, "posAtCoords").mockReturnValue(7);
await handleFileDrop(["/source/photo.png"], 0, 0);
expect(invoke).toHaveBeenCalledWith("fs_read_image", { path: "/source/photo.png" }, undefined);
await vi.waitFor(() => expect(create).toHaveBeenCalledWith("/project/docs/assets/photo.png", "AP8="));
expect(editor.state.doc.toString()).toBe("before ![](assets/photo.png)after");
});
it("inserts a paste as one isolated undo step and tracks edits during saving", async () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
onmessage?: (e: { data: { data: string } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
}
},
);
+7 -4
View File
@@ -65,8 +65,8 @@ export async function saveImage(
markdown: string,
folder: string,
name: string,
data: number[],
create = (path: string, bytes: number[]) => call(commands.fsCreateFileBytes(path, bytes)),
data: string,
create = (path: string, base64: string) => call(commands.fsCreateFileBytes(path, base64)),
): Promise<string> {
const dot = name.lastIndexOf(".");
const stem = dot > 0 ? name.slice(0, dot) : name;
@@ -82,12 +82,15 @@ export async function saveImage(
}
}
function imageBytes(blob: Blob | string): Promise<number[]> {
/** The image as base64, the form `fsCreateFileBytes` takes. */
function imageBytes(blob: Blob | string): Promise<string> {
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: number[]; error?: string }>) => {
worker.onmessage = (event: MessageEvent<{ data: string; error?: string }>) => {
worker.terminate();
if (event.data.error) reject(new Error(event.data.error));
else resolve(event.data.data);
+3 -2
View File
@@ -52,7 +52,8 @@ import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
@@ -1299,7 +1300,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 saveFileDialog({
const path = await chooseSavePath({
title: tx("Save As"),
defaultPath: this.saveAsSuggestion(model),
filters: await languageFilters(),
+39 -1
View File
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } 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";
@@ -57,6 +59,42 @@ 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();
+1
View File
@@ -11,6 +11,7 @@ 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 }));
+3 -2
View File
@@ -1,6 +1,7 @@
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";
@@ -26,8 +27,8 @@ async function retrieve(path: string, choose: boolean) {
try {
let sources: string | null = null;
if (choose) {
const { open } = await import("@/platform/dialog");
const selected = await open({
const selected = await choosePath({
directory: false,
title: tx("Choose Sources…"),
filters: [{ name: tx("Source archives"), extensions: ["jar", "zip"] }],
});
@@ -11,7 +11,7 @@
* of the file in batches; results are cached per document text, and markers
* follow their lines in between.
* The cache outlives the editor view (switching tabs remounts it) until other
* files change or a language server settles: on some servers (jdtls) every
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
* implementation search walks the whole workspace, so asking again is costly.
* Library sources ask no inheritors from the server (`isLibrarySource`).
*/
@@ -119,11 +119,15 @@ function watchChanges() {
// documents: re-render them instead of waiting for an edit or a settling server.
for (const plugin of live) plugin.refreshSoon();
});
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
onServerSettled(() => {
// Answers (outlines too) given while a server was starting or importing may be incomplete.
const refreshCaches = () => {
docMarkers.clear();
forgetInheritanceGraph();
for (const plugin of live) plugin.refreshSoon();
};
onServerSettled(refreshCaches);
onIdeEvent("lspRefresh", (e) => {
if (e.kind === "inheritance") refreshCaches();
});
// Go to Declaration and the like go first: in-flight marker requests are cancelled and
// asked again once the navigation is done.
+65
View File
@@ -9,13 +9,25 @@ import {
commands,
type ClassInheritance,
type HierarchyItem,
type IdeEvent,
type Location,
type OutlineItem,
type Pos,
type SymbolKind,
} from "@/platform/ipc";
import { setInvokeRoute } from "@/platform/tauriCore";
const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi.fn() }));
const ideListeners = vi.hoisted(() => new Map<string, Set<(event: IdeEvent) => void>>());
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
onIdeEvent: (type: string, listener: (event: IdeEvent) => void) => {
let listeners = ideListeners.get(type);
if (!listeners) ideListeners.set(type, (listeners = new Set()));
listeners.add(listener);
return () => listeners.delete(listener);
},
}));
vi.mock("@/editor/lsp/navigation", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
@@ -623,6 +635,59 @@ describe("clicking a marker", () => {
});
describe("inheritance gutter", () => {
it.each([
{ type: "interface", source: SHAPE, outline: SHAPE_OUTLINE },
{ type: "abstract class", source: BASE, outline: BASE_OUTLINE },
])(
"refreshes implementation and override markers when a Java project update finishes ($type)",
async ({ source, outline }) => {
vi.useFakeTimers();
let indexed = false;
const target = "/p/service/target/generated-sources/example/ServiceImpl.java";
const queries = vi.fn<MarkerDeps["implementations"]>(async (positions) =>
positions.map(({ line }) => (indexed ? [loc(target, line + 2)] : [])),
);
setInvokeRoute(async (command, args) => {
if (command === "doc_outline") return outline;
if (command === "lsp_type_hierarchy") {
throw { kind: "unavailable", message: "no type hierarchy", data: null };
}
if (command === "lsp_implementations") return queries((args as { positions: Pos[] }).positions);
return null;
});
const ctx = { doc: 12, path: `/p/api/${outline[0]!.name}.java`, language: "java", uiMode: null, readOnly: false };
const view = new EditorView({
doc: Text.of(source),
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
const kinds = () =>
[...view.dom.querySelectorAll<HTMLElement>('[class*="cm-openidea-lineMarker-"]')].map((el) => el.dataset.kind);
const emit = (event: IdeEvent) => {
for (const listener of ideListeners.get(event.type) ?? []) listener(event);
};
try {
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
expect(kinds()).toEqual([]);
indexed = true;
emit({ type: "lspRefresh", server: 1, kind: "semanticTokens" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
emit({ type: "lspRefresh", server: 1, kind: "inheritance" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(2);
expect(kinds()).toEqual(["implemented", "implemented", "overridden"]);
} finally {
view.destroy();
setInvokeRoute(null);
vi.useRealTimers();
}
},
);
it.each([
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
{ kind: "overridden", language: "java", declaration: "@Data" },
+1 -1
View File
@@ -679,7 +679,7 @@ function CustomAgentModal({
try {
const trimmed = name.trim();
const title = trimmed ? tx`Select ${trimmed}` : tx("Select executable");
const path = await backend.chooseExecutable(title, command);
const path = await backend.chooseExecutable(title, command, "desktop");
if (path) setCommand(path);
setError(null);
} catch (e) {
+6 -3
View File
@@ -1,5 +1,7 @@
/** 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,
@@ -31,7 +33,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): Promise<string | null>;
chooseExecutable(title: string, current?: string, location?: "desktop"): Promise<string | null>;
saveCustom(input: CustomAgentInput): Promise<void>;
removeCustom(id: string): Promise<void>;
importAcp(text: string): Promise<AcpImportOutcome[]>;
@@ -56,7 +58,8 @@ 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) => {
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
return typeof picked === "string" ? picked : null;
},
@@ -81,7 +84,7 @@ export const tauriCommands: CommandsBackend = {
filters: [{ name: tx("ACP config"), extensions: ["json"] }],
});
if (typeof picked !== "string") return null;
return call(commands.fsReadText(picked));
return readDesktopText(picked);
},
};
+2 -5
View File
@@ -4,7 +4,7 @@ import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { isTauri } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
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,10 +40,7 @@ export function AnalysisDialogHost() {
}
async function browseDirectory(initial: string): Promise<string | null> {
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;
return choosePath({ directory: true, defaultPath: initial });
}
const KINDS: ScopeKind[] = ["project", "directory", "file", "changed", "custom"];
+5 -13
View File
@@ -10,6 +10,7 @@ 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,
@@ -427,15 +428,12 @@ 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 { open } = await import("@/platform/dialog");
const picked = await open({
const paths = await choosePaths({
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);
@@ -470,14 +468,11 @@ export async function importModuleFromExistingSources() {
} catch {
/* Tests and hosts without the tool-window service still link the POM. */
}
const { open } = await import("@/platform/dialog");
const picked = await open({
const path = await choosePath({
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))) {
@@ -532,16 +527,13 @@ export async function linkGradleProjects() {
!isTauri()
)
return;
const { open } = await import("@/platform/dialog");
const picked = await open({
const paths = await choosePaths({
title: tx`Link Gradle Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "Gradle build files", extensions: ["gradle", "kts"] }],
});
const paths = typeof picked === "string" ? [picked] : picked;
if (!paths?.length || useProject.getState().project?.root !== root || gen !== generation) return;
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);
+2 -4
View File
@@ -5,6 +5,7 @@
*/
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";
@@ -28,9 +29,7 @@ import styles from "./Coverage.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
async function pickReport(): Promise<string | null> {
const { open } = await import("@/platform/dialog");
const file = await open({
multiple: false,
return choosePath({
directory: false,
title: "Import Coverage Report",
filters: [
@@ -41,7 +40,6 @@ 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. */
+2 -1
View File
@@ -1,6 +1,7 @@
/** 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";
@@ -157,7 +158,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 call(commands.fsReadText(f));
const content = await readDesktopText(f);
setFile(f);
setText(content);
setSep(guessSeparator(content));
+3 -4
View File
@@ -1,4 +1,5 @@
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";
@@ -85,14 +86,12 @@ export function JdbcDriverProfiles({
setBusy(true);
setError(null);
try {
const { open } = await import("@/platform/dialog");
const files = await open({
const files = await choosePaths({
title: tx("Choose JDBC Driver and Dependency JARs"),
multiple: true,
directory: false,
filters: [{ name: tx("Java archives"), extensions: ["jar"] }],
});
if (files && draft) {
if (files.length && draft) {
const jars = [...new Set([...draft.jars, ...files])];
set({ jars });
const names = await call(commands.dbJdbcDriverClasses(jars));
@@ -16,6 +16,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
(...args: unknown[]) => [name, ...args];
return {
...real,
isTauri: () => true,
call: backend.call,
commands: {
...real.commands,
+2 -3
View File
@@ -21,6 +21,7 @@ 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";
@@ -259,9 +260,7 @@ function blank(): DataSource {
}
async function pickFile(title: string): Promise<string | null> {
const { open } = await import("@/platform/dialog");
const file = await open({ multiple: false, directory: false, title });
return typeof file === "string" ? file : null;
return choosePath({ directory: false, title });
}
/** A path field with Browse…. */
+2 -1
View File
@@ -6,6 +6,7 @@
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";
@@ -200,7 +201,7 @@ async function runScriptFile(id: string) {
});
if (typeof file !== "string") return;
try {
const text = await call(commands.fsReadText(file));
const text = await readDesktopText(file);
const statements = await call(commands.dbStatements(id, text, 0, text.length));
useDatabase.setState({ activeResult: OUTPUT_TAB });
showServiceView(RESULTS_VIEW, false);
+2 -2
View File
@@ -1,4 +1,5 @@
/** 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";
@@ -32,8 +33,7 @@ const act = (
const sep: MenuItem = { kind: "separator" };
async function sqliteFromFile() {
const { open } = await import("@/platform/dialog");
const file = await open({ multiple: false, directory: false, title: "SQLite Database File" });
const file = await choosePath({ directory: false, title: "SQLite Database File" });
if (typeof file === "string") openSourceDialog(null, { driver: "sqlite", file, name: fileSourceName(file) });
}
+4 -1
View File
@@ -19,7 +19,9 @@ 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" } }) } }));
vi.mock("@/platform/project", () => ({
useProject: { getState: () => ({ project: { root: "/project" } }), subscribe: vi.fn() },
}));
vi.mock("@/workbench/contributions", () => ({
notifications: () => ({ notify: ipc.notify }),
projectViewSelection: () => ipc.selection(),
@@ -27,6 +29,7 @@ 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,
+2 -3
View File
@@ -1,5 +1,6 @@
/** 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";
@@ -183,10 +184,8 @@ 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 { open } = await import("@/platform/dialog");
const target = await open({
const target = await choosePath({
directory: true,
multiple: false,
title: tx("Download to"),
defaultPath: (await defaultDownloadFolder()) ?? undefined,
});
+3 -2
View File
@@ -6,6 +6,7 @@ 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";
@@ -254,7 +255,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, [...new TextEncoder().encode(CONFIG_TEMPLATE)]));
await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(CONFIG_TEMPLATE))));
} catch (e) {
notifications().notify({ level: "error", title: "Cannot create the GraphQL configuration", body: String(e) });
return;
@@ -441,7 +442,7 @@ export async function introspectEndpoint(path: string, name?: string): Promise<v
}
} else {
try {
await call(commands.fsCreateFileBytes(target, [...new TextEncoder().encode(sdl)]));
await call(commands.fsCreateFileBytes(target, toBase64(new TextEncoder().encode(sdl))));
} catch (e) {
notifications().notify({ level: "error", title: "Cannot write the GraphQL schema", body: String(e) });
return;
@@ -7,6 +7,7 @@ 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;
+3 -11
View File
@@ -39,6 +39,8 @@ 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";
@@ -197,12 +199,6 @@ 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);
@@ -227,11 +223,7 @@ export const tauriPluginsBackend: PluginsBackend = {
return chosen;
},
program: (id, program, scope) => call(commands.pluginProgram(id, program, scope)),
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;
},
pickProgram: () => choosePath({ directory: false, title: tx("Choose plugin executable") }),
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 -9
View File
@@ -5,6 +5,7 @@
* batches.
*/
import { readClipboardPlainText, readClipboardPng, writeClipboardText } from "@/platform/clipboard";
import { choosePath } from "@/platform/choosePath";
import { providePluginTestParser, providePluginTestSelector } from "@/workbench/contributions";
import {
contentTabData,
@@ -512,16 +513,11 @@ async function askUser(prompt: Prompt, signal: AbortSignal): Promise<string[] |
case "pickDirectory": {
if (signal.aborted) return null;
try {
const { open } = await import("@/platform/dialog");
const path = await choosePath(
{ directory: true, title: prompt.title, defaultPath: prompt.initial ?? undefined },
signal,
);
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)
+2 -1
View File
@@ -4,6 +4,7 @@
*/
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";
@@ -31,7 +32,7 @@ export const tauriFs: ProjectFs = {
notifyFileOperation({ kind: "created", paths: [path] });
},
createFileBytes: async (path, data) => {
await call(commands.fsCreateFileBytes(path, [...data]));
await call(commands.fsCreateFileBytes(path, toBase64(data)));
notifyFileOperation({ kind: "created", paths: [path] });
},
createDir: async (path) => void (await call(commands.fsCreateDir(path))),
@@ -1,6 +1,8 @@
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";
@@ -15,6 +17,7 @@ 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"> = {};
@@ -35,11 +38,14 @@ beforeEach(() => {
});
vi.spyOn(commands, "fsOpenWithSystem").mockResolvedValue(ok);
vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, data) => {
written.push({ path, text: new TextDecoder().decode(new Uint8Array(data)) });
written.push({ path, text: new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))) });
return ok;
});
});
afterEach(() => vi.restoreAllMocks());
afterEach(() => {
useRemote.setState({ session: null });
vi.restoreAllMocks();
});
function results() {
const r = new TestResults();
@@ -164,6 +170,59 @@ 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";
+19 -1
View File
@@ -4,8 +4,11 @@
*/
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";
@@ -96,7 +99,7 @@ export async function writeTestReport(path: string, text: string, confirmed: boo
return false;
await call(commands.fsDelete(path));
}
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(text))));
await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(text))));
return true;
} catch (e) {
notifications().notify({
@@ -158,6 +161,21 @@ 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,
+2 -1
View File
@@ -4,6 +4,7 @@
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
* it as a normal document.
*/
import { toBase64 } from "@/platform/base64";
import { call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { scratchesDir as hostScratchesDir } from "@/platform/scratchesDir";
import { editorService, notifications } from "@/workbench/contributions";
@@ -23,7 +24,7 @@ export const tauriScratchBackend: ScratchBackend = {
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
createFile: async (path, text) =>
void (await call(
text ? commands.fsCreateFileBytes(path, [...new TextEncoder().encode(text)]) : commands.fsCreateFile(path),
text ? commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(text))) : commands.fsCreateFile(path),
)),
languages: async () => scratchLanguages(await commands.languages()),
open: (path, caret) => editorService().openFile(path, { focus: true, ...(caret && { selection: caret }) }),
+3 -10
View File
@@ -12,10 +12,11 @@ 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, isTauri, onIdeEvent } from "@/platform/ipc";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectModules } from "@/platform/projectRoots";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
@@ -98,15 +99,7 @@ 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> {
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;
return choosePath({ directory: true, title: tx("Select Search Directory"), defaultPath: current });
}
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(Array));
expect(new TextDecoder().decode(new Uint8Array(mocks.write.mock.calls[0]![1]))).toContain(
'name="Forest &amp; Moss"',
);
expect(mocks.write).toHaveBeenCalledWith("/schemes/export.icls", expect.any(String));
expect(
new TextDecoder().decode(Uint8Array.from(atob(mocks.write.mock.calls[0]![1]), (c) => c.charCodeAt(0))),
).toContain('name="Forest &amp; Moss"');
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(Array));
expect(mocks.write).toHaveBeenCalledWith("/chosen/custom-export.icls", expect.any(String));
});
it("supports cancel, keep both and overwrite collisions", async () => {
@@ -2,10 +2,15 @@ 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 = {
@@ -15,6 +20,71 @@ 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();
@@ -52,6 +122,7 @@ 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 });
@@ -97,6 +168,7 @@ 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" }));
+3 -5
View File
@@ -10,7 +10,7 @@ import { useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { allActions, useActions, type Action } from "@/platform/actions";
import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS } from "@/platform/keymap";
import { call, commands } from "@/platform/ipc";
import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles";
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 call(commands.fsReadText(path)));
parsed = parseIdeaKeymap(await readDesktopText(path));
} catch (e) {
await showError(tx("Import Keymap"), e instanceof Error ? e.message : String(e));
return;
@@ -298,9 +298,7 @@ export function KeymapPage() {
draft,
);
try {
// 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))));
await writeDesktopText(path, json);
notifications().notify({
level: "info",
title: tx("Keymap exported"),
@@ -2,17 +2,21 @@
* 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: a click on its pad records the button and modifiers.
* Shortcut" dialog: the pad records mouse buttons and wheel gestures.
*/
import { useEffect, useMemo, useState, type MouseEvent } from "react";
import { useEffect, useMemo, useRef, 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";
@@ -30,7 +34,7 @@ export interface RecordShortcutDialogProps {
onCancel: () => void;
/** `removeConflicts`: also unbind the conflicting assignments. */
onSubmit: (binding: string, conflicts: Conflict[], removeConflicts: boolean) => void;
/** Record a mouse shortcut (modified left clicks, middle or side buttons) instead of keys. */
/** Record a mouse button or wheel shortcut. */
mouse?: boolean;
}
@@ -42,9 +46,11 @@ 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],
@@ -96,7 +102,12 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
</div>
</div>
{mouse ? (
<MouseRecorder value={first} onChange={setFirst} sideButtons={!rectangularSelection} />
<MouseRecorder
value={first}
onChange={setFirst}
sideButtons={!rectangularSelection}
wheel={supportsWheelShortcut(action.id)}
/>
) : (
<KeyStrokes
first={first}
@@ -119,7 +130,7 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
<T>The action already has this shortcut</T>
</span>
)}
{!already && binding && conflicts.length === 0 && (
{!already && binding && !zoomConflict && conflicts.length === 0 && (
<span className={styles.recordHint}>
<T>No conflicts</T>
</span>
@@ -135,6 +146,16 @@ 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>
@@ -208,17 +229,34 @@ function KeyStrokes({ first, second, useSecond, allowsSecond, setFirst, setSecon
);
}
/** Shortcuts stay off while the dialog records mouse buttons and modifiers. */
/** Shortcuts stay off while the dialog records mouse gestures. */
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;
@@ -230,6 +268,7 @@ function MouseRecorder({
};
return (
<div
ref={padRef}
role="textbox"
aria-readonly="true"
aria-label="Mouse shortcut"
@@ -242,7 +281,9 @@ function MouseRecorder({
<span className={styles.recorded}>{formatBinding(value)}</span>
) : (
<span className={styles.recorderPlaceholder}>
{sideButtons ? (
{wheel ? (
<T>Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button</T>
) : 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 { call, commands } from "@/platform/ipc";
import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles";
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 call(commands.fsReadText(path)), fallbackName);
const parsed = parseIcls(await readDesktopText(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,10 +1758,7 @@ export function ColorSchemePage({
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }],
}));
if (!path) return;
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));
await writeDesktopText(path, exportIcls(id, customs, mine));
setReport(tx("Scheme exported."));
},
delete: async () => {
@@ -10,6 +10,7 @@
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";
@@ -300,9 +301,8 @@ function JavaFormatter({
}) {
const id = useId();
const browse = async () => {
const { open } = await import("@/platform/dialog");
const path = await open({
multiple: false,
const path = await choosePath({
directory: false,
title: tx("Eclipse formatter XML"),
filters: [{ name: "XML", extensions: ["xml"] }],
});
+2 -3
View File
@@ -8,6 +8,7 @@ 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,
@@ -137,9 +138,7 @@ function ShellPathRow() {
void commands.termAvailableShells().then(setShells, () => undefined);
}, []);
const browse = async () => {
const { open: pick } = await import("@/platform/dialog");
const picked = await pick({ multiple: false, title: "Shell Path" });
const path = Array.isArray(picked) ? picked[0] : picked;
const path = await choosePath({ directory: false, title: "Shell Path" });
if (path) set(quotePath(path));
};
return (
+2 -2
View File
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTx } from "@/platform/i18n";
import { Checkbox, Dialog, Input } from "@/ui";
import { answerAskpass, askpassAnswer, useAskpass, type AskpassPrompt } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, 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(p.kind === "secret" ? "SSH Password" : "SSH")}
title={tx(askpassTitle(p))}
onClose={cancel}
width={440}
buttons={[
+9
View File
@@ -45,3 +45,12 @@ 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";
}
+13 -1
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SSH_CONFIG, type SshConfigValid } from "@/platform/remoteSettings";
import { answerAskpass, askpassAnswer, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
describe("askpass queue", () => {
@@ -40,6 +40,18 @@ 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: number[]) => {
fsCreateFileBytes: (path: string, data: string) => {
calls.bytes(path);
files.set(path, new TextDecoder().decode(new Uint8Array(data)));
files.set(path, new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))));
return Promise.resolve(null);
},
fsCreateFile: (path: string) => {
+2 -1
View File
@@ -1,4 +1,5 @@
/** 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";
@@ -191,7 +192,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, [...new TextEncoder().encode(text)]));
if (provided && text) await call(commands.fsCreateFileBytes(plan.path, toBase64(new TextEncoder().encode(text))));
else await call(commands.fsCreateFile(plan.path));
notifyFileOperation({ kind: "created", paths: [plan.path] });
onCreated?.();
+7 -7
View File
@@ -218,7 +218,7 @@ it("allows images at the size limit", async () => {
const remove = installTerminalPaste(host, paste, () => remoteTarget());
host.dispatchEvent(imageEvent(image(undefined, 20 * 1024 * 1024)));
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("'/remote/image.png'"));
expect(store).toHaveBeenCalledWith(42, [1, 2], "image/png");
expect(store).toHaveBeenCalledWith(42, "AQI=", "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, [1, 2], "image/png"));
await vi.waitFor(() => expect(store).toHaveBeenCalledWith(42, "AQI=", "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, [1, 2], "image/png");
expect(store).toHaveBeenCalledWith(42, "AQI=", "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, [1, 2], "image/png");
expect(store).toHaveBeenCalledWith(42, "AQI=", "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, [1, 2], "image/png");
expect(store).toHaveBeenCalledWith(42, "AQI=", "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, [1, 2], "image/png");
expect(store).toHaveBeenCalledWith(42, "AQI=", "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, [1, 2], type);
expect(store).toHaveBeenCalledWith(42, "AQI=", type);
remove();
});
+2 -1
View File
@@ -1,4 +1,5 @@
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";
@@ -67,7 +68,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 = Array.from(new Uint8Array(await media.arrayBuffer()));
const data = toBase64(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));
+2 -5
View File
@@ -5,6 +5,7 @@
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;
@@ -43,11 +44,7 @@ export const tauriToolsBackend: ToolsBackend = {
restartServers: async (name) => {
await call(commands.lspRestartNamed(name));
},
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;
},
chooseExecutable: (title, defaultPath) => choosePath({ directory: false, title, defaultPath }),
languages: async () =>
(await commands.languages())
.map((l) => ({ id: l.id, name: l.name, extensions: l.extensions, filenames: l.filenames }))
+4 -1
View File
@@ -1,5 +1,6 @@
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";
@@ -260,7 +261,9 @@ function WorktreeForm({
}
if (!file.exists) {
try {
await call(commands.fsCreateFileBytes(file.path, [...new TextEncoder().encode(worktreeIncludeTemplate())]));
await call(
commands.fsCreateFileBytes(file.path, toBase64(new TextEncoder().encode(worktreeIncludeTemplate()))),
);
} catch (e) {
if (!isErrorKind(e, "alreadyExists")) throw e;
}
+3 -6
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { Commit } from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { notifications, type EditorInput } from "@/workbench/contributions";
import {
@@ -26,15 +26,12 @@ import { currentRepoRoot } from "./store";
import { repositoryPath } from "./repositoryPaths";
import { firstLineOf, languageFor, viewerBase } from "./cm";
import styles from "./GitLog.module.css";
import { choosePath } from "@/platform/choosePath";
import { choosePaths } from "@/platform/choosePath";
import { openLogTab } from "./logStore";
import { openRevisionFile, type RevisionData } from "./revisionInput";
export async function openExternalLog() {
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] : [];
const paths = await choosePaths({ title: tx("Open Git Log"), directory: true });
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, bytes) => {
mocks.create.mockImplementation(async (_path, base64: string) => {
exists = true;
content = new TextDecoder().decode(Uint8Array.from(bytes));
content = new TextDecoder().decode(Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)));
return ok(null);
});
mocks.read.mockImplementation(async () => ok(content));
+5 -4
View File
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { Channel } from "@tauri-apps/api/core";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { callDesktop, 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,8 +183,9 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
};
const cancel = () => {
if (request.current !== null) void commands.cancelRequest(request.current);
else onClose();
const id = request.current;
if (id === null) onClose();
else void callDesktop("cancel_request", { id });
};
const clone = async (picked?: string) => {
@@ -201,7 +202,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
if (text) setProgress({ line: text, fraction: progressFraction(text) });
};
try {
await call(commands.vcsClone(id, cloneUrl.trim(), target, depth, channel));
await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel });
writeParent(parentOf(target));
rememberUrl(cloneUrl.trim());
onClose();
+4 -6
View File
@@ -4,6 +4,7 @@
*/
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";
@@ -97,16 +98,13 @@ 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;
const picked = await open({ multiple: false, directory: false, title: "Compare With", defaultPath: dir });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
return choosePath({ directory: false, title: tx("Compare With"), defaultPath: dir });
}
/**
* The file to compare `path` against: the OS file dialog on the desktop; a
* browser file picker's contents elsewhere (remote development / `pnpm dev`),
* The file to compare `path` against: a project-host path in the app; a
* browser file picker's contents in the browser build,
* compared as text since no absolute path is available to the backend.
*/
async function pickComparison(
+2 -2
View File
@@ -1,5 +1,5 @@
/** VCS › Create Git Repository…: `git init` in a folder chosen under the project. */
import { open } from "@/platform/dialog";
import { choosePath } from "@/platform/choosePath";
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 open({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root });
const dir = await choosePath({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root });
if (typeof dir !== "string") return;
try {
await call(commands.vcsInit(dir));
+3 -7
View File
@@ -35,7 +35,7 @@ import {
} from "@/ui";
import { executeAction } from "@/platform/actions";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { choosePath } from "@/platform/choosePath";
import { choosePath, chooseSavePath } from "@/platform/choosePath";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
@@ -165,8 +165,7 @@ export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string)
async function browseSave(current: string): Promise<string | null> {
try {
const { save } = await import("@/platform/dialog");
return (await save({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] })) ?? null;
return await chooseSavePath({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] });
} catch {
return null;
}
@@ -414,14 +413,11 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string)
} else {
let file = path ?? null;
if (!file) {
const { open } = await import("@/platform/dialog");
const picked = await open({
multiple: false,
file = await choosePath({
directory: false,
defaultPath: useVcs.getState().root ?? undefined,
filters: [{ name: "Patch", extensions: ["patch", "diff"] }],
});
file = typeof picked === "string" ? picked : null;
}
if (!file) return;
sourcePath = file;
+3 -6
View File
@@ -4,6 +4,7 @@
* 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";
@@ -581,12 +582,8 @@ export async function showShelfDiff(arg?: unknown, local = false, newTab = false
export async function importShelfPatches(paths?: string[]) {
const repo = currentRepo();
const 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) {
paths ?? (await choosePaths({ directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }));
for (const path of picked) {
await runOp(
tx("Import patches"),
async () => call(commands.vcsShelfImport(repo, baseName(path), await call(commands.fsReadText(path)))),
+20
View File
@@ -0,0 +1,20 @@
import { expect, it } from "vitest";
import { toBase64 } from "./base64";
const decode = (text: string) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
it("encodes every byte value and the empty input to standard padded base64", () => {
expect(toBase64(new Uint8Array())).toBe("");
expect(toBase64(new Uint8Array([0, 255]))).toBe("AP8=");
const all = Uint8Array.from({ length: 256 }, (_, i) => i);
expect([...decode(toBase64(all))]).toEqual([...all]);
});
it("is a string of at most ceil(4n/3) characters, across the chunk boundary", () => {
for (const n of [0x7fff, 0x8000, 0x8001, 5 * 0x8000 + 1]) {
const bytes = Uint8Array.from({ length: n }, (_, i) => (i * 31) % 256);
const text = toBase64(bytes);
expect(text).toHaveLength(4 * Math.ceil(n / 3));
expect(decode(text)).toEqual(bytes);
}
});
+11
View File
@@ -0,0 +1,11 @@
/**
* 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(""));
}
+31 -11
View File
@@ -1,13 +1,21 @@
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[];
}
type HostChooser = (opts: ChoosePathOptions) => Promise<string | null>;
export interface HostPathOptions extends ChoosePathOptions {
multiple?: boolean;
save?: boolean;
signal?: AbortSignal;
}
type HostChooser = (opts: HostPathOptions) => Promise<string[] | null>;
let hostChooser: HostChooser | null = null;
/**
@@ -25,16 +33,28 @@ 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): Promise<string | null> {
if (!isTauri()) return null;
if (isRemoteWindow() && hostChooser) return hostChooser(opts);
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;
// Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load.
const { open } = await import("@/platform/dialog");
const picked = await open({
directory: opts.directory,
multiple: false,
title: opts.title,
defaultPath: opts.defaultPath || undefined,
});
if (signal?.aborted) return null;
const picked = await open({ ...opts, multiple: false, defaultPath: opts.defaultPath || undefined });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
}
/** Pick multiple existing paths on the project host. */
export async function choosePaths(opts: ChoosePathOptions): Promise<string[]> {
if (!isTauri()) return [];
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, multiple: true })) ?? [];
const { open } = await import("@/platform/dialog");
const picked = await open({ ...opts, multiple: true });
return typeof picked === "string" ? [picked] : (picked ?? []);
}
/** Choose a destination on the project host and confirm replacement if it exists. */
export async function chooseSavePath(opts: SaveDialogOptions): Promise<string | null> {
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, directory: false, save: true }))?.[0] ?? null;
const { save } = await import("@/platform/dialog");
return save(opts);
}
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { readDesktopText, writeDesktopText } from "./desktopFiles";
import { useRemote } from "./remote";
import { setInvokeRoute } from "./tauriCore";
const invoke = vi.fn();
const remoteInvoke = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
useRemote.setState({ session: { root: "/srv/project", os: "linux" } as never });
setInvokeRoute(remoteInvoke);
});
afterEach(() => {
setInvokeRoute(null);
useRemote.setState({ session: null });
vi.unstubAllGlobals();
});
it("reads desktop settings or import files even when project IPC is remote", async () => {
const path = "C:\\Users\\me\\settings.xml";
invoke.mockResolvedValueOnce("<settings />");
await expect(readDesktopText(path)).resolves.toBe("<settings />");
expect(invoke.mock.calls[0]?.slice(0, 2)).toEqual(["fs_read_text", { path }]);
expect(remoteInvoke).not.toHaveBeenCalled();
});
it("checks and replaces an existing desktop file on the desktop", async () => {
const path = "C:\\Users\\me\\scheme.icls";
invoke.mockResolvedValueOnce("file").mockResolvedValueOnce(null).mockResolvedValueOnce(null);
await writeDesktopText(path, "é");
expect(invoke.mock.calls.map((args) => args.slice(0, 2))).toEqual([
["fs_entry_kind", { path }],
["fs_delete", { path }],
["fs_create_file_bytes", { path, data: "w6k=" }],
]);
expect(remoteInvoke).not.toHaveBeenCalled();
});
+24
View File
@@ -0,0 +1,24 @@
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 });
}
+3 -1
View File
@@ -23,6 +23,8 @@ 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" />
@@ -31,7 +33,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"].map(normalizeBinding),
["Meta+Shift+N", "Meta+K Meta+C", "Alt+Button1", "Ctrl+WheelUp", "Alt+Shift+WheelDown"].map(normalizeBinding),
);
expect(k.overrides["navigate.declaration"]).toEqual([]);
expect(k.applied).toBe(2);
+6 -5
View File
@@ -24,7 +24,7 @@ export interface ImportedIdeaKeymap {
applied: number;
/** IDEA action ids without an OpenIDEA counterpart. */
unknownActions: string[];
/** Shortcuts that cannot be expressed here (wheel, double click, unknown keys). */
/** Shortcuts that cannot be expressed here (double click, unknown keys). */
skippedShortcuts: number;
}
@@ -90,12 +90,13 @@ export function fromSwingStroke(stroke: string): string | null {
return name ? [...words.map((w) => SWING_MODS[w.toLowerCase()]), name].join("+") : null;
}
/** `"meta alt button1"` → `"Meta+Alt+Button1"`; wheel and multi-click gestures → null. */
/** Converts Swing mouse buttons and wheel directions. */
function fromMouseStroke(stroke: string): string | null {
const words = stroke.trim().split(/\s+/);
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("+");
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("+");
}
/** Parses an IDEA keymap XML; throws when the file is not a keymap. */
+12
View File
@@ -9,6 +9,8 @@ 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";
@@ -43,6 +45,16 @@ 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";
}
+84 -13
View File
@@ -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),
* optionally with modifiers (`Alt+Button4`); they are single strokes.
* or the wheel direction (`WheelUp`, `WheelDown`), optionally with modifiers.
*/
import { create } from "zustand";
import { executeAction, executeActionFrom, getAction, isActionKeyEnabled } from "./actions";
@@ -79,24 +79,45 @@ 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">;
/** A mouse shortcut (`Button4`, `Shift+Button5`) rather than a keystroke. */
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. */
export function isMouseBinding(binding: string): boolean {
const b = binding.trim();
return !/\s/.test(b) && MOUSE_KEY_RE.test(b.split("+").pop()!);
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("+");
}
/**
* 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" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
): string | null {
export function mouseStrokeOf(e: Pick<MouseEvent, "button"> & ModifierKeys): 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;
const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean);
return [...mods, `Button${e.button + 1}`].join("+");
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 STROKE_RE = /^(?:(?:Ctrl|Alt|Shift|Meta)\+)*[^\s+]+$|^(?:(?:Ctrl|Alt|Shift|Meta)\+)*\+$/i;
@@ -118,8 +139,9 @@ 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();
if (parseDoubleModifier(b)) return true;
const strokes = b.split(/\s+/);
if (strokes.some(isWheelBinding)) return strokes.length === 1 && STROKE_RE.test(b);
if (parseDoubleModifier(b)) return true;
if (strokes.some((s) => /swipe(left|right)$/i.test(s))) {
return strokes.length === 1 && /^swipe(left|right)$/i.test(b);
}
@@ -298,8 +320,10 @@ 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(" ");
@@ -366,8 +390,7 @@ export function strokeOf(
if (["Shift", "Meta", "Control", "Alt"].includes(e.key)) return null;
key = e.key.length === 1 ? e.key.toUpperCase() : e.key;
}
const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean);
return [...mods, key].join("+");
return modifiedStroke(e, key);
}
const SYMBOLS: Record<string, string> = {
@@ -404,8 +427,12 @@ export function formatBinding(binding: string, mac = isMacHost()): string {
if (isMouseBinding(binding)) {
const parts = normalizeBinding(binding).split("+");
const key = parts.pop();
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("+");
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("+");
}
if (!mac)
return normalizeBinding(binding)
@@ -444,6 +471,13 @@ 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" };
@@ -669,6 +703,7 @@ 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 = () => {
@@ -819,6 +854,39 @@ 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;
@@ -832,6 +900,7 @@ export function installKeyboardDispatcher(
const onBlur = () => {
reset();
doubleModifier.reset();
wheelGesture = null;
};
const onSwipe = (event: Event) => {
@@ -848,6 +917,7 @@ 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);
@@ -857,6 +927,7 @@ 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);
+72
View File
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
applyKeymapSettings,
bindingsFor,
formatBinding,
dispatchMouseShortcut,
installKeyboardDispatcher,
@@ -76,6 +78,37 @@ 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();
@@ -105,6 +138,45 @@ 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);
+4
View File
@@ -981,6 +981,10 @@
"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",
+4
View File
@@ -988,6 +988,10 @@
"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": "取消选择匹配项",
+86 -31
View File
@@ -9,11 +9,13 @@
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import { create } from "zustand";
import { registerHostPathChooser, type ChoosePathOptions } from "@/platform/choosePath";
import { registerHostPathChooser, type HostPathOptions } from "@/platform/choosePath";
import { t, tx, VerbatimTextContext } from "@/platform/i18n";
import { call, commands, type FileEntry } from "@/platform/ipc";
import { call, commands, isErrorKind, type FileEntry } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
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 {
@@ -63,7 +65,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: ChoosePathOptions; resolve: (v: string | null) => void };
| { kind: "path"; id: number; options: HostPathOptions; resolve: (v: string[] | null) => void };
const useInputDialogs = create<{ stack: Request[] }>(() => ({ stack: [] }));
let seq = 0;
@@ -102,8 +104,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). */
export function choosePathOnHost(options: ChoosePathOptions): Promise<string | null> {
return open<string>((id, resolve) => ({ kind: "path", id, options, resolve }));
function choosePathOnHost(options: HostPathOptions): Promise<string[] | null> {
return open<string[]>((id, resolve) => ({ kind: "path", id, options, resolve }), options.signal);
}
registerHostPathChooser(choosePathOnHost);
@@ -351,8 +353,10 @@ 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 trimmed = path.length > 1 ? path.replace(/[\\/]+$/, "") : path;
const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
const posix = path.startsWith("/") && !path.startsWith("//");
const trimmed = path.replace(posix ? /\/+$/ : /[\\/]+$/, "");
const slash = trimmed.lastIndexOf("/");
const cut = posix ? slash : Math.max(slash, trimmed.lastIndexOf("\\"));
if (cut < 0) return null;
const parent = trimmed.slice(0, cut);
// `/a` → `/`; `C:\a` → `C:\`.
@@ -360,30 +364,44 @@ export function parentPath(path: string): string | null {
return parent === trimmed ? null : parent;
}
function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: string | null) => void }) {
function PathDialog({ options, done }: { options: HostPathOptions; 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 visit = async (path: string) => {
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 id = ++request.current;
setLoading(true);
try {
const listed = await call(commands.fsReadDir(path));
if (id !== request.current) return true;
const shown = listed
.filter((e) => !options.directory || isDir(e))
.filter(accepts)
.sort((a, b) => Number(isDir(b)) - Number(isDir(a)) || a.name.localeCompare(b.name));
setDir(path);
setEntries(shown);
setActive(-1);
setValue(path);
setValue(filename ? inDir(path, filename) : path);
setError(null);
return true;
} catch (e) {
@@ -395,7 +413,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
};
useEffect(() => {
const start = options.defaultPath || root || "/";
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;
}
// A file path starts in its folder, with the file in the field.
void visit(start).then((ok) => {
const parent = parentPath(start);
@@ -404,23 +427,42 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
// 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 visit(entry.path);
else done(entry.path);
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]);
};
const submit = async () => {
const path = value.trim();
if (!path) return;
let kind: string;
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);
try {
kind = await call(commands.fsEntryKind(path));
} catch {
return setError(tx("No such file or folder"));
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);
}
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);
@@ -428,11 +470,16 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
<Dialog
open
blockWorkbenchShortcuts
title={options.title}
title={title}
onClose={() => done(null)}
width={520}
buttons={[
{ label: tx("OK"), role: "default", disabled: !value.trim(), onClick: () => void submit() },
{
label: tx("OK"),
role: "default",
disabled: loading || submitting || (!value.trim() && !selected.length),
onClick: () => void submit(),
},
{ label: t("common.cancel"), role: "cancel" },
]}
>
@@ -448,12 +495,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
icon="arrow-up"
title={tx("Parent Folder")}
disabled={!up || loading}
onClick={() => up && void visit(up)}
onClick={() => up && void move(up)}
/>
<Input
data-autofocus
className={styles.pathInput}
aria-label={options.title}
aria-label={title}
value={value}
invalid={!!error}
onChange={(e) => {
@@ -469,12 +516,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
onActiveChange={(i) => {
setActive(i);
const entry = entries[i];
if (entry) setValue(entry.path);
if (entry && (!options.save || !isDir(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 ?? options.title}
aria-label={dir ?? title}
empty={
<div className={styles.hint}>
<T>{loading ? "Loading…" : "Empty folder"}</T>
@@ -483,7 +530,15 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
renderItem={(entry, state) => (
<div className={`${state.active ? styles.activeRow : styles.row} ${styles.entry}`}>
<Icon name={isDir(entry) ? "folder" : "file"} />
<span className={styles.entryName}>{entry.name}</span>
{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>
)}
</div>
)}
/>
+61 -2
View File
@@ -6,6 +6,8 @@ const mocks = vi.hoisted(() => ({
readDir: vi.fn(),
entryKind: vi.fn(),
nativeOpen: vi.fn(),
nativeSave: vi.fn(),
confirm: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -16,9 +18,10 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
commands: { ...real.commands, fsReadDir: mocks.readDir, fsEntryKind: mocks.entryKind },
};
});
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: vi.fn() }));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: mocks.nativeSave }));
vi.mock("./messages", async (original) => ({ ...(await original<object>()), confirm: mocks.confirm }));
import { choosePath } from "@/platform/choosePath";
import { choosePath, choosePaths, chooseSavePath } from "@/platform/choosePath";
import { useRemote } from "@/platform/remote";
import { InputDialogsHost, parentPath } from "./inputDialogs";
@@ -26,6 +29,8 @@ const tree: Record<string, [string, "dir" | "file"][]> = {
"/srv/app": [
["runner", "dir"],
["pom.xml", "file"],
["build.xml", "file"],
["README.txt", "file"],
],
"/srv/app/runner": [
["plugins", "dir"],
@@ -119,6 +124,58 @@ describe("choosePath in a remote window", () => {
fireEvent.click(dialog().getByRole("button", { name: "Cancel" }));
await expect(result).resolves.toBeNull();
});
it("selects multiple matching files on the host", async () => {
let result!: Promise<string[]>;
act(() => {
result = choosePaths({
directory: false,
title: "Add Maven Projects",
defaultPath: "/srv/app",
filters: [{ name: "XML", extensions: ["xml"] }],
});
});
fireEvent.click(await dialog().findByRole("checkbox", { name: "pom.xml" }));
fireEvent.click(dialog().getByRole("checkbox", { name: "build.xml" }));
expect(dialog().queryByText("README.txt")).toBeNull();
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toEqual(["/srv/app/pom.xml", "/srv/app/build.xml"]);
expect(mocks.nativeOpen).not.toHaveBeenCalled();
});
it("keeps a proposed name while browsing to a new save destination", async () => {
let result!: Promise<string | null>;
act(() => {
result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/new.txt" });
});
await dialog().findByText("runner");
expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/new.txt");
fireEvent.click(dialog().getByText("runner"), { detail: 2 });
await dialog().findByText("plugins");
expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/runner/new.txt");
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toBe("/srv/app/runner/new.txt");
expect(mocks.nativeSave).not.toHaveBeenCalled();
expect(mocks.confirm).not.toHaveBeenCalled();
});
it("asks before accepting an existing save destination", async () => {
mocks.confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
let result!: Promise<string | null>;
act(() => {
result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/pom.xml" });
});
await dialog().findByText("runner");
const ok = dialog().getByRole("button", { name: "OK" });
fireEvent.click(ok);
await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
await waitFor(() => expect(ok).toBeEnabled());
fireEvent.click(ok);
await expect(result).resolves.toBe("/srv/app/pom.xml");
expect(mocks.confirm).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining("pom.xml") }),
);
});
});
describe("parentPath", () => {
@@ -127,8 +184,10 @@ describe("parentPath", () => {
expect(parentPath("/srv")).toBe("/");
expect(parentPath("/")).toBeNull();
expect(parentPath("C:\\Users\\me")).toBe("C:\\Users");
expect(parentPath("C:/Users\\me")).toBe("C:/Users");
expect(parentPath("C:\\Users")).toBe("C:\\");
expect(parentPath("C:\\")).toBeNull();
expect(parentPath("/srv/app/")).toBe("/srv");
expect(parentPath("/srv/app/file\\name")).toBe("/srv/app");
});
});