дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 13:52:36 +02:00
Порівняти коміти
16
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
04880ebb9f | ||
|
|
23f591289c | ||
|
|
8684e95778 | ||
|
|
9d9e3f1c4f | ||
|
|
5eff75cab5 | ||
|
|
aec1382e79 | ||
|
|
999d84b189 | ||
|
|
9fda9b92c2 | ||
|
|
261eb03009 | ||
|
|
db8b553364 | ||
|
|
2494b2efdf | ||
|
|
d78ce7ec66 | ||
|
|
9df9499bf5 | ||
|
|
d4b5581441 | ||
|
|
d96060f08b | ||
|
|
507258daec |
No files matched your search
Створено
@@ -4253,6 +4253,7 @@ dependencies = [
|
||||
name = "ide-core"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -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)");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
|
||||
/// (compile errors are added to `errors`). Other configurations are returned as they are.
|
||||
async fn resolve_jvm_application(
|
||||
call: &Call,
|
||||
config: RunConfig,
|
||||
mut config: RunConfig,
|
||||
errors: &mut BuildErrors,
|
||||
) -> IdeResult<Result<RunConfig, String>> {
|
||||
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
|
||||
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
|
||||
(Some(exec), "java") => exec.clone(),
|
||||
_ => config.command.clone(),
|
||||
};
|
||||
config.extras.module = Some(module);
|
||||
Ok(Ok(RunConfig { command, args, ..config }))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Maven / Gradle tool windows (the build model and its background sync) and
|
||||
//! Build › Build Project (compiling with the project's build system).
|
||||
mod workspace;
|
||||
pub(super) mod workspace;
|
||||
|
||||
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
|
||||
use crate::ops::Channel;
|
||||
@@ -181,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
|
||||
|
||||
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
|
||||
/// the tool window do.
|
||||
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
let profiles = ide_build::maven_profiles(cache);
|
||||
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
|
||||
for p in &mut m.projects {
|
||||
@@ -952,16 +952,18 @@ pub async fn build_run(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let mut launch_caches = Vec::new();
|
||||
let plan = if let Some(id) = cmake {
|
||||
launch_caches.push(cache.clone());
|
||||
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
|
||||
cmake_plan(&root, kind, &configs, &id)?
|
||||
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
let mut combined: Option<compile::BuildPlan> = None;
|
||||
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
|
||||
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
|
||||
let member_cache =
|
||||
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
|
||||
let member_cache = workspace::cache_at(&root, &cache, member);
|
||||
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
|
||||
launch_caches.push(member_cache);
|
||||
let plan = prepare_plan(
|
||||
compile::plan(
|
||||
member,
|
||||
@@ -985,6 +987,7 @@ pub async fn build_run(
|
||||
plan
|
||||
} else {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
launch_caches.push(cache.clone());
|
||||
match compile::plan(
|
||||
&root,
|
||||
&model,
|
||||
@@ -1007,7 +1010,9 @@ pub async fn build_run(
|
||||
});
|
||||
if kind == BuildKind::Rebuild {
|
||||
// The clean removed outputs that earlier launch snapshots still hold.
|
||||
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
|
||||
for cache in launch_caches {
|
||||
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
|
||||
}
|
||||
}
|
||||
let result = result?;
|
||||
if result.success && single && kind == BuildKind::Build {
|
||||
|
||||
@@ -1,12 +1,33 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) struct Scope {
|
||||
pub(in crate::ops) struct Scope {
|
||||
pub root: PathBuf,
|
||||
pub cache: PathBuf,
|
||||
pub settings: Settings,
|
||||
}
|
||||
|
||||
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
|
||||
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
|
||||
let root = workspace
|
||||
.as_ref()
|
||||
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
|
||||
.unwrap_or(&project.root);
|
||||
Ok(Scope {
|
||||
cache: cache_at(&project.root, &project.build_cache_dir(), root),
|
||||
settings: if root == &project.root {
|
||||
project.settings.effective()
|
||||
} else {
|
||||
project.settings.for_project(root).effective()
|
||||
},
|
||||
root: root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
|
||||
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
|
||||
}
|
||||
|
||||
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
|
||||
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
|
||||
}
|
||||
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
|
||||
.into_iter()
|
||||
.filter(|p| p.is_dir())
|
||||
.map(|root| Scope {
|
||||
cache: if root == window_root {
|
||||
cache.to_owned()
|
||||
} else {
|
||||
cache.join(crate::project::project_key(&root))
|
||||
},
|
||||
cache: cache_at(window_root, cache, &root),
|
||||
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
|
||||
root,
|
||||
})
|
||||
|
||||
@@ -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)?;
|
||||
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
|
||||
ide_vfs::create_dir(&path)
|
||||
}
|
||||
|
||||
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
/// keeps its scratches on the server, where its file commands run.
|
||||
#[command(trust = always)]
|
||||
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
let dir = host.data_dir.join("scratches");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
/// state). Returns whether the file is read-only now.
|
||||
#[command(trust = always)]
|
||||
@@ -383,6 +392,7 @@ ide_command::domain!(
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_scratches_dir,
|
||||
fs_set_writable,
|
||||
fs_synchronize_directories,
|
||||
fs_undo_delete,
|
||||
|
||||
@@ -4,7 +4,7 @@ pub(crate) mod cache;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::build::load;
|
||||
use super::build::{load, with_profiles, workspace};
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch(
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
let (project, module) = (project.clone(), module.clone());
|
||||
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
|
||||
}
|
||||
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
|
||||
let settings = project.settings.effective();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy);
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, prefer_maven, is_maven) = {
|
||||
let project = project.clone();
|
||||
let settings = settings.clone();
|
||||
let (model, external, mut delegated, is_maven) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let module = module.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
project.java_launch_snapshots.lock().initialize();
|
||||
let model = load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
|
||||
let is_maven =
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
let prefer_maven = settings.languages.java.maven.delegate_build;
|
||||
launches.snapshots.lock().initialize();
|
||||
let root = &scope.root;
|
||||
let model = load_launch_model(&scope);
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
policy,
|
||||
non_java,
|
||||
cache::has_record(&project.root, &project.build_cache_dir(), &module),
|
||||
cache::has_record(root, &scope.cache, &module),
|
||||
prefer_maven,
|
||||
);
|
||||
let external = non_java || delegated;
|
||||
(model, external, delegated, prefer_maven, is_maven)
|
||||
(model, external, delegated, is_maven)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
let model = std::sync::Arc::new(model);
|
||||
let members = if delegated {
|
||||
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
|
||||
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch(
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _external_build = external_build;
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
// Module outputs the launch runs from a snapshot of: the originals must not come back.
|
||||
let mut snapshotted = Vec::new();
|
||||
// The modules of the launches sharing this build also share its classpath probe.
|
||||
@@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch(
|
||||
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
|
||||
let built = if delegated {
|
||||
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
|
||||
let outputs = project.java_launch_snapshots.lock().build(
|
||||
&project.root,
|
||||
let outputs = launches.snapshots.lock().build(
|
||||
root,
|
||||
&model,
|
||||
&module,
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
|
||||
@@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch(
|
||||
snapshotted = outputs.originals;
|
||||
copies
|
||||
} else if external {
|
||||
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
|
||||
if let Some(failure) = built.failure {
|
||||
if policy != BuildPolicy::MakeAndContinueOnErrors {
|
||||
return Err(IdeError::internal(failure));
|
||||
@@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch(
|
||||
// m2e runs inside jdtls on the server JDK and can resolve a different
|
||||
// Maven profile/classifier than the module build. Ask the same Maven
|
||||
// process that built the module for its runtime/test dependencies.
|
||||
let maven_cp = compile::module_classpaths(
|
||||
&project.root,
|
||||
&model,
|
||||
&probed,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
);
|
||||
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
|
||||
} else {
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
if build && !delegated {
|
||||
let cache_dir = project.build_cache_dir();
|
||||
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
|
||||
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
|
||||
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
}
|
||||
let compile_ms = started.elapsed().as_millis() - lsp_ms;
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
|
||||
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
|
||||
}
|
||||
|
||||
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
module: PathBuf,
|
||||
scope: workspace::Scope,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let settings = project.settings.effective();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (root, cache, settings, module, cancel) =
|
||||
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
|
||||
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load(&root, &cache, &settings);
|
||||
let model = load_launch_model(&scope);
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
|
||||
};
|
||||
(model, built)
|
||||
})
|
||||
@@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls(
|
||||
let build_ms = started.elapsed().as_millis();
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let project = project.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
@@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls(
|
||||
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
|
||||
}
|
||||
None => {
|
||||
let is_maven = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
if !is_maven {
|
||||
if !is_maven_module(root, &model, &module) {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let classpath = compile::module_classpath(
|
||||
&project.root,
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
)?;
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
@@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls(
|
||||
}
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -445,10 +440,10 @@ fn apply_library_classpath(
|
||||
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
|
||||
async fn build_members(
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
scope: &std::sync::Arc<workspace::Scope>,
|
||||
model: &std::sync::Arc<BuildModel>,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
prefer_maven: bool,
|
||||
waiting: &cache::WaitingGuard,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<cache::Member>> {
|
||||
@@ -456,10 +451,11 @@ async fn build_members(
|
||||
if others.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
let joining = {
|
||||
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
|
||||
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
|
||||
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -500,8 +496,7 @@ fn joining_launches(
|
||||
others
|
||||
.into_iter()
|
||||
.filter(|o| {
|
||||
let is_maven =
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
|
||||
let is_maven = is_maven_module(root, model, &o.module);
|
||||
o.test == test
|
||||
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
|
||||
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
|
||||
|
||||
@@ -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(©.0)
|
||||
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +151,30 @@ pub(super) struct Member {
|
||||
pub rebuild_on_jdt_errors: bool,
|
||||
}
|
||||
|
||||
/// Launches share a build only within the same workspace project's cache.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
|
||||
|
||||
pub(in crate::ops) struct Launches {
|
||||
pub waiting: Waiting,
|
||||
pub snapshots: Mutex<Session>,
|
||||
}
|
||||
|
||||
impl Sessions {
|
||||
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
|
||||
self.0
|
||||
.lock()
|
||||
.entry(cache.to_owned())
|
||||
.or_insert_with(|| {
|
||||
Arc::new(Launches {
|
||||
waiting: Waiting::default(),
|
||||
snapshots: Mutex::new(Session::new(cache.to_owned())),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Java launches from their start until their build: one launch's Maven run also builds
|
||||
/// the modules of launches still waiting (configurations started together, #3971).
|
||||
#[derive(Default)]
|
||||
@@ -256,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())?;
|
||||
@@ -293,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());
|
||||
@@ -303,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);
|
||||
@@ -698,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,
|
||||
@@ -711,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"));
|
||||
@@ -732,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();
|
||||
@@ -869,6 +1025,7 @@ mod tests {
|
||||
fingerprint: None,
|
||||
snapshot: retained.clone(),
|
||||
originals: Vec::new(),
|
||||
output_stamps: None,
|
||||
failure: None,
|
||||
authoritative: false,
|
||||
};
|
||||
@@ -929,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();
|
||||
|
||||
@@ -242,7 +242,10 @@ fn settings_only(
|
||||
.cloned()
|
||||
});
|
||||
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
|
||||
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
|
||||
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
|
||||
if jvm && member.is_some() && config.cwd.is_none() {
|
||||
config.cwd = Some(owner.into());
|
||||
} else if config.extras.module.is_none() && !jvm {
|
||||
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
|
||||
}
|
||||
ide_run::scope::rebase(config, &project.root, None);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -51,10 +51,8 @@ pub struct Project {
|
||||
pub(crate) member_excludes: MemberExcludes,
|
||||
/// Per-project cache directory (build tool sync results…).
|
||||
pub cache_dir: PathBuf,
|
||||
/// Superseded launch snapshots retained until this project session ends.
|
||||
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
|
||||
/// Java launches waiting for their build, which can share one Maven run.
|
||||
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
|
||||
/// Pending launches and retained snapshots, scoped to each workspace project.
|
||||
pub(crate) java_launches: crate::ops::java::cache::Sessions,
|
||||
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
|
||||
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
@@ -641,10 +639,7 @@ impl Host {
|
||||
detected_roots,
|
||||
member_excludes,
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
java_launches_waiting: Default::default(),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
@@ -891,10 +886,7 @@ impl Host {
|
||||
detected_roots: Arc::default(),
|
||||
member_excludes: Arc::default(),
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
java_launches_waiting: Default::default(),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -74,6 +74,13 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
|
||||
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
|
||||
|
||||
let scratch_path = base.join("data/scratches");
|
||||
assert!(!scratch_path.exists());
|
||||
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
assert!(scratch_path.is_dir());
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
|
||||
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
|
||||
@@ -21,7 +21,7 @@ async fn storage_requires_a_registered_terminal() {
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1], "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,6 +6,107 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn java_launch_builds_the_owning_workspace_reactor() {
|
||||
use ide_run::BuildPolicy;
|
||||
use ide_workspace::{SettingsStore, settings::SettingsScope};
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let config_dir = base.join("config");
|
||||
let primary = base.join("primary");
|
||||
let sibling = base.join("spring");
|
||||
let nested = primary.join("nested");
|
||||
let roots = [&primary, &sibling, &nested];
|
||||
for (i, root) in roots.into_iter().enumerate() {
|
||||
fs::create_dir_all(root.join("app")).unwrap();
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
let wrapper = root.join("mvnw");
|
||||
fs::write(
|
||||
&wrapper,
|
||||
r#"#!/bin/sh
|
||||
set -eu
|
||||
printf '%s\n' "$*" >> calls
|
||||
mkdir -p app/target/classes
|
||||
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
|
||||
scope=runtime
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-Dmdep.includeScope=*) scope="${arg#*=}";;
|
||||
esac
|
||||
done
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-Dmdep.outputFile=*)
|
||||
touch "app/$scope.jar"
|
||||
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
|
||||
esac
|
||||
done
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
SettingsStore::load(&config_dir, Some(root))
|
||||
.set(
|
||||
SettingsScope::Project,
|
||||
"languages.java.maven.activeProfiles",
|
||||
serde_json::json!(format!("member-{i}")),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// Exercise the build-tool classpath fallback without starting an installed server.
|
||||
let global = SettingsStore::load(&config_dir, None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir,
|
||||
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: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
for root in roots {
|
||||
host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
host.open_project("main", &primary).unwrap();
|
||||
for root in [&sibling, &nested] {
|
||||
ops::project::attach_workspace(&host, "main", root).unwrap();
|
||||
}
|
||||
for (index, root) in roots.into_iter().enumerate() {
|
||||
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
|
||||
let test = index != 0;
|
||||
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
|
||||
.await
|
||||
.unwrap();
|
||||
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
|
||||
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains("dependency:build-classpath"), "{calls}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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` 与本地命令完全一样。
|
||||
|
||||
## 命令路由
|
||||
|
||||
|
||||
@@ -131,3 +131,60 @@ for (const home of [false, true]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
|
||||
await prepare(page, true, false);
|
||||
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
|
||||
const scroller = page.locator(".cm-scroller").filter({ has: box });
|
||||
const overflow = () =>
|
||||
scroller.evaluate((el) => ({
|
||||
x: el.scrollWidth - el.clientWidth,
|
||||
y: el.scrollHeight - el.clientHeight,
|
||||
}));
|
||||
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await box.fill("Reply with OK.");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await page.getByRole("button", { name: "Start", exact: true }).click();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
|
||||
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
|
||||
await page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const { useAgents } = await import(storePath);
|
||||
useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
id,
|
||||
[
|
||||
{ type: "user", text: "Reply with OK.", attachments: [] },
|
||||
{ type: "agent", text: "OK" },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
}, task.id);
|
||||
await expect(page.getByText("OK", { exact: true })).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect(scroller).toHaveCSS("overflow-x", "hidden");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await box.fill("Short draft");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await box.fill("word".repeat(2000));
|
||||
await expect(scroller).toHaveCSS("overflow-y", "auto");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { x, y } = await overflow();
|
||||
return x === 0 && y > 0;
|
||||
})
|
||||
.toBe(true);
|
||||
await box.fill("");
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
/** Opens the sample with the server's lenses `titles` above its first line, at editor font `fontSize`. */
|
||||
async function lensRow(page: Page, fontSize: number, titles: string[]): Promise<{ editor: Locator; row: Locator }> {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ fontSize, titles }) => {
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectPath);
|
||||
const settings = useProject.getState().settings;
|
||||
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize } } });
|
||||
const at = { line: 0, col: 0 };
|
||||
window.__ipc.handlers.lsp_code_lens = () =>
|
||||
titles.map((title) => ({ range: { start: at, end: at }, command: { title, command: "noop", arguments: [] } }));
|
||||
},
|
||||
{ fontSize, titles },
|
||||
);
|
||||
// An edit asks the server for its lenses again.
|
||||
await editor.locator(".cm-line").first().click();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.type(" ");
|
||||
const row = editor.locator(".cm-openidea-lens");
|
||||
await expect(row).toContainText(titles[0]!);
|
||||
return { editor, row };
|
||||
}
|
||||
|
||||
test("a Code Vision row fits CJK hints at a large editor font", async ({ workbench: page }) => {
|
||||
const { editor, row } = await lensRow(page, 20, ["10 个用法", "无用法"]);
|
||||
const overflow = await row.evaluate((el) => {
|
||||
const box = el.getBoundingClientRect();
|
||||
return [...el.querySelectorAll(".cm-openidea-lensItem")].map((item) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(item);
|
||||
const text = range.getBoundingClientRect();
|
||||
return Math.max(box.top - text.top, text.bottom - box.bottom);
|
||||
});
|
||||
});
|
||||
expect(overflow).toHaveLength(2);
|
||||
for (const px of overflow) expect(px).toBeLessThanOrEqual(0);
|
||||
// The editor measured the taller row: the lines below it still sit beside their numbers.
|
||||
const line = editor.locator(".cm-line", { hasText: "class OrderController" });
|
||||
const number = editor.locator(".cm-lineNumbers .cm-gutterElement", { hasText: /^8$/ });
|
||||
const [lineTop, numberTop] = [(await line.boundingBox())!.y, (await number.boundingBox())!.y];
|
||||
expect(Math.abs(lineTop - numberTop)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("a Code Vision row keeps its height at the default editor font", async ({ workbench: page }) => {
|
||||
const { row } = await lensRow(page, 13, ["3 usages"]);
|
||||
expect((await row.boundingBox())!.height).toBe(16);
|
||||
});
|
||||
@@ -487,6 +487,45 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
|
||||
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
|
||||
});
|
||||
|
||||
for (const mode of ["Preview Only", "Editor and Preview"]) {
|
||||
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
|
||||
const path = "/dev/acme-api/linked-heading.md";
|
||||
const heading = "5.2 状态机";
|
||||
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
|
||||
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
await page.evaluate(
|
||||
async ({ path, target }) => {
|
||||
const backendModule = "/src/editor/core/backend.ts";
|
||||
const routeModule = "/src/platform/tauriCore.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backendModule);
|
||||
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
|
||||
docBackend().files.set(path, target);
|
||||
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
|
||||
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
|
||||
);
|
||||
},
|
||||
{ path, target },
|
||||
);
|
||||
|
||||
await editor.locator(".cm-content").focus();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
|
||||
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
|
||||
|
||||
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(destinationTab).toHaveCount(0);
|
||||
await preview.getByRole("link", { name: "Linked heading" }).click();
|
||||
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
|
||||
if (mode === "Editor and Preview") {
|
||||
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
|
||||
@@ -37,6 +37,15 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
|
||||
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
|
||||
});
|
||||
|
||||
test("a single click shows the file in the preview tab, which the next one reuses", async ({ workbench: page }) => {
|
||||
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
|
||||
await expect(tabs.getByRole("tab", { name: "README.md" })).toBeVisible();
|
||||
await page.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).click();
|
||||
await expect(tabs.getByRole("tab", { name: "settings.gradle.kts" })).toBeVisible();
|
||||
await expect(tabs.getByRole("tab", { name: "README.md" })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("Rename targets a file or folder directly from its context menu", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 720, height: 480 });
|
||||
const menu = page.getByRole("menu", { name: "Context menu" });
|
||||
|
||||
@@ -12,9 +12,8 @@ test("the scratch language chooser fits short windows and keeps recents separate
|
||||
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
|
||||
const { rememberLanguage } = await import(/* @vite-ignore */ store);
|
||||
setScratchBackend({
|
||||
dataDir: async () => "/test-app-data",
|
||||
scratchesDir: async () => "/test-app-data/scratches",
|
||||
listNames: async () => [],
|
||||
createDir: async () => {},
|
||||
createFile: async () => {},
|
||||
languages: async () => [
|
||||
...Array.from({ length: 24 }, (_, i) => {
|
||||
|
||||
@@ -11,11 +11,11 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
|
||||
configurable: true,
|
||||
value: { transformCallback: () => 1 },
|
||||
});
|
||||
const stored: { id: number; data: 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'"]);
|
||||
});
|
||||
@@ -286,6 +286,7 @@ fs_read_range always project_host bin
|
||||
fs_read_text always project_host bindings async
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_scratches_dir always project_host bindings sync
|
||||
fs_set_writable always project_host bindings sync
|
||||
fs_synchronize_directories always project_host bindings async
|
||||
fs_undo_delete always project_host bindings async
|
||||
|
||||
+10
-2
@@ -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. */
|
||||
@@ -707,6 +707,11 @@ export const commands = {
|
||||
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
|
||||
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
|
||||
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
|
||||
/**
|
||||
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
* keeps its scratches on the server, where its file commands run.
|
||||
*/
|
||||
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
|
||||
/**
|
||||
* Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
* state). Returns whether the file is read-only now.
|
||||
@@ -1818,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
|
||||
@@ -8366,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;
|
||||
|
||||
|
||||
@@ -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==" } }));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -238,11 +238,13 @@ function buildDecorations(state: EditorState): DecorationSet {
|
||||
|
||||
const lensTheme = EditorView.theme({
|
||||
// IDEA paints code vision with the colour scheme's Inline hints attribute.
|
||||
// At least 16px, and taller when the hint font needs it: the row grows with its items, so a
|
||||
// large editor font or a fallback font that inks below the baseline (CJK) is never cut off.
|
||||
".cm-openidea-lens": {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "12px",
|
||||
height: "16px",
|
||||
minHeight: "16px",
|
||||
color: "var(--fg-inlay, var(--fg-muted))",
|
||||
WebkitUserSelect: "none",
|
||||
userSelect: "none",
|
||||
@@ -276,7 +278,10 @@ const lensTheme = EditorView.theme({
|
||||
// Pinned to the line, the hint may run past the editor's edge (IDEA clips it there); cap it so a
|
||||
// long one cannot stretch across the whole window first.
|
||||
maxWidth: "min(60ch, 50vw)",
|
||||
overflow: "hidden",
|
||||
// The box is 1em tall (the anchor's `lineHeight: 1`): clip only past the side, so a glyph that
|
||||
// inks above or below its em box (CJK fallback fonts) still shows whole.
|
||||
overflowX: "clip",
|
||||
overflowY: "visible",
|
||||
pointerEvents: "auto",
|
||||
},
|
||||
".cm-openidea-lensItem": {
|
||||
@@ -293,6 +298,9 @@ const lensTheme = EditorView.theme({
|
||||
fontFamily: "var(--font-ui)",
|
||||
fontSize: "calc(1em - 1px)",
|
||||
},
|
||||
// The row's items size to the fonts their text is drawn with (fallback fonts included), not to the
|
||||
// editor's line height, which `font: inherit` brings along.
|
||||
".cm-openidea-lens > .cm-openidea-lensItem": { lineHeight: "normal" },
|
||||
".cm-openidea-lensAction": { cursor: "pointer" },
|
||||
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
|
||||
".cm-openidea-lensIcon-run": { color: "var(--success)" },
|
||||
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView, runScopeHandlers } from "@codemirror/view";
|
||||
import { applySnippet, hasLinkedSnippetField } from "./linkedSnippet";
|
||||
|
||||
let view: EditorView;
|
||||
afterEach(() => view.destroy());
|
||||
|
||||
function expand(snippet: string) {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({ extensions: [EditorState.allowMultipleSelections.of(true)] }),
|
||||
parent: document.body,
|
||||
});
|
||||
applySnippet(view, [{ from: 0, to: 0, snippet }]);
|
||||
}
|
||||
|
||||
const selected = () => view.state.selection.ranges.map(({ from, to }) => view.state.sliceDoc(from, to));
|
||||
const doc = () => view.state.doc.toString();
|
||||
const type = (text: string) => view.dispatch(view.state.replaceSelection(text));
|
||||
const press = (key: string) => runScopeHandlers(view, new KeyboardEvent("keydown", { key }), "editor");
|
||||
|
||||
describe("linked snippets", () => {
|
||||
it("selects the first occurrence of each variable and mirrors edits within its group", () => {
|
||||
expand("${1:x}/${1:x} ${2:y}/${2:y}${0}");
|
||||
expect(selected()).toEqual(["x"]);
|
||||
expect(view.state.selection.main.from).toBe(0);
|
||||
type("name");
|
||||
expect(doc()).toBe("name/name y/y");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(selected()).toEqual(["y"]);
|
||||
expect(view.state.selection.main.from).toBe("name/name ".length);
|
||||
type("label");
|
||||
expect(doc()).toBe("name/name label/label");
|
||||
});
|
||||
|
||||
it("tracks adjacent empty occurrences and the next variable independently", () => {
|
||||
expand("${1}${1}${2:end}${0}");
|
||||
expect(selected()).toEqual([""]);
|
||||
type("x");
|
||||
type("y");
|
||||
expect(doc()).toBe("xyxyend");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(selected()).toEqual(["end"]);
|
||||
type("!");
|
||||
expect(doc()).toBe("xyxy!");
|
||||
});
|
||||
|
||||
it.each(["Escape", "Tab"])("ends mirroring on %s", (key) => {
|
||||
expand("${1:x}/${1:x}${0}");
|
||||
if (key === "Escape") {
|
||||
expect(press(key)).toBe(true);
|
||||
expect(hasLinkedSnippetField(view.state, 1)).toBe(true);
|
||||
}
|
||||
expect(press(key)).toBe(true);
|
||||
expect(hasLinkedSnippetField(view.state, 1)).toBe(false);
|
||||
const { head } = view.state.selection.main;
|
||||
expect(head).toBe(key === "Escape" ? 1 : doc().length);
|
||||
view.dispatch({ changes: { from: 0, to: 1, insert: "changed" } });
|
||||
expect(doc()).toBe("changed/x");
|
||||
});
|
||||
|
||||
it("keeps a repeated last placeholder active until the end of the snippet", () => {
|
||||
expand("${1:one} ${2:two}/${2:two}");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(selected()).toEqual(["two"]);
|
||||
type("new");
|
||||
expect(doc()).toBe("one new/new");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(view.state.selection.main.head).toBe(doc().length);
|
||||
});
|
||||
|
||||
it("keeps fields linked after a separate edit before the snippet", () => {
|
||||
expand("call(${1:arg}, ${1:arg})${0}");
|
||||
const prefix = "import call;\n";
|
||||
view.dispatch({ changes: { from: 0, insert: prefix }, userEvent: "input.complete" });
|
||||
expect(selected()).toEqual(["arg"]);
|
||||
type("value");
|
||||
expect(doc()).toBe(prefix + "call(value, value)");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(view.state.selection.main.head).toBe(doc().length);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,346 @@
|
||||
import {
|
||||
clearSnippet,
|
||||
closeCompletion,
|
||||
completionStatus,
|
||||
pickedCompletion,
|
||||
snippet,
|
||||
type Completion,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { indentUnit } from "@codemirror/language";
|
||||
import {
|
||||
ChangeSet,
|
||||
EditorSelection,
|
||||
EditorState,
|
||||
MapMode,
|
||||
Prec,
|
||||
StateEffect,
|
||||
StateField,
|
||||
Text,
|
||||
type ChangeSpec,
|
||||
type Transaction,
|
||||
} from "@codemirror/state";
|
||||
import { Decoration, EditorView, keymap, WidgetType, type Command } from "@codemirror/view";
|
||||
import { isExternalChange } from "@/editor/api";
|
||||
|
||||
interface SnippetSite {
|
||||
from: number;
|
||||
to: number;
|
||||
snippet: string;
|
||||
}
|
||||
|
||||
interface SnippetRange {
|
||||
from: number;
|
||||
to: number;
|
||||
field: number;
|
||||
}
|
||||
|
||||
interface Segment extends SnippetRange {
|
||||
site: number;
|
||||
primary: boolean;
|
||||
}
|
||||
|
||||
interface ActiveSnippet {
|
||||
segments: readonly Segment[];
|
||||
active: number;
|
||||
last: number;
|
||||
mainSite: number;
|
||||
completion: boolean;
|
||||
}
|
||||
|
||||
const setSnippet = StateEffect.define<ActiveSnippet | null>();
|
||||
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
|
||||
const fieldCursor = Decoration.widget({
|
||||
widget: new (class extends WidgetType {
|
||||
toDOM() {
|
||||
const span = document.createElement("span");
|
||||
span.className = "cm-snippetFieldPosition";
|
||||
return span;
|
||||
}
|
||||
ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
})(),
|
||||
});
|
||||
|
||||
function primarySegments(value: ActiveSnippet, field = value.active) {
|
||||
return value.segments.filter((segment) => segment.field === field && segment.primary);
|
||||
}
|
||||
|
||||
function contains(range: SnippetRange, from: number, to: number): boolean {
|
||||
return range.from <= from && to <= range.to;
|
||||
}
|
||||
|
||||
function selectionInField(value: ActiveSnippet, selection: EditorSelection): boolean {
|
||||
const primaries = primarySegments(value);
|
||||
return selection.ranges.every(({ from, to }) => primaries.some((segment) => contains(segment, from, to)));
|
||||
}
|
||||
|
||||
const fields = StateField.define<ActiveSnippet | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
const next = tr.effects.find((effect) => effect.is(setSnippet));
|
||||
if (next) return next.value;
|
||||
if (!value) return null;
|
||||
if (tr.docChanged) {
|
||||
const segments: Segment[] = [];
|
||||
for (const segment of value.segments) {
|
||||
const from = tr.changes.mapPos(segment.from, -1, MapMode.TrackDel);
|
||||
const to = tr.changes.mapPos(segment.to, 1, MapMode.TrackDel);
|
||||
if (from === null || to === null || from < (segments.at(-1)?.to ?? 0)) return null;
|
||||
segments.push({ ...segment, from, to });
|
||||
}
|
||||
value = { ...value, segments };
|
||||
}
|
||||
return tr.selection && !selectionInField(value, tr.selection) ? null : value;
|
||||
},
|
||||
provide: (field) =>
|
||||
EditorView.decorations.from(field, (value) =>
|
||||
value
|
||||
? Decoration.set(
|
||||
value.segments.map(({ from, to }) => (from === to ? fieldCursor : fieldMark).range(from, to)),
|
||||
true,
|
||||
)
|
||||
: Decoration.none,
|
||||
),
|
||||
});
|
||||
|
||||
// Keep the edit and its mirrors in one history entry.
|
||||
const mirrorEdits = EditorState.transactionFilter.of((tr) => {
|
||||
const value = tr.startState.field(fields, false);
|
||||
if (
|
||||
!value ||
|
||||
!tr.docChanged ||
|
||||
isExternalChange(tr) ||
|
||||
tr.isUserEvent("undo") ||
|
||||
tr.isUserEvent("redo") ||
|
||||
tr.effects.some((effect) => effect.is(setSnippet))
|
||||
)
|
||||
return tr;
|
||||
|
||||
const primaries = primarySegments(value);
|
||||
const edited = new Map<Segment, number>();
|
||||
let outside = false;
|
||||
let touchesOtherSegment = false;
|
||||
tr.changes.iterChangedRanges((from, to, newFrom, newTo) => {
|
||||
const segment = primaries.find((range) => contains(range, from, to));
|
||||
if (segment) edited.set(segment, (edited.get(segment) ?? 0) + (newTo - newFrom) - (to - from));
|
||||
else {
|
||||
outside = true;
|
||||
touchesOtherSegment ||= value.segments.some((range) => from <= range.to && to >= range.from);
|
||||
}
|
||||
}, true);
|
||||
if (outside) return edited.size || touchesOtherSegment ? [tr, { effects: setSnippet.of(null) }] : tr;
|
||||
|
||||
const changes: ChangeSpec[] = [];
|
||||
const replacements = new Map<number, Text>();
|
||||
let typedOffset = 0;
|
||||
let mirrorOffset = 0;
|
||||
// Map in source order so neighboring stops keep their own boundaries even when they touch.
|
||||
const segments = value.segments.map((segment) => {
|
||||
const start = segment.from + typedOffset;
|
||||
const from = start + mirrorOffset;
|
||||
let length = segment.to - segment.from;
|
||||
const delta = edited.get(segment);
|
||||
if (delta !== undefined) {
|
||||
length += delta;
|
||||
replacements.set(segment.site, tr.newDoc.slice(start, start + length));
|
||||
typedOffset += delta;
|
||||
} else if (segment.field === value.active && !segment.primary) {
|
||||
const insert = replacements.get(segment.site);
|
||||
if (insert && !insert.eq(tr.newDoc.slice(start, start + length))) {
|
||||
changes.push({ from: start, to: start + length, insert });
|
||||
mirrorOffset += insert.length - length;
|
||||
length = insert.length;
|
||||
}
|
||||
}
|
||||
return { ...segment, from, to: from + length };
|
||||
});
|
||||
const mirrors = ChangeSet.of(changes, tr.newDoc.length);
|
||||
const next = { ...value, segments };
|
||||
const staysInField = selectionInField(next, tr.newSelection.map(mirrors));
|
||||
return [tr, { changes: mirrors, effects: setSnippet.of(staysInField ? next : null), sequential: true }];
|
||||
});
|
||||
|
||||
function clearLinkedSnippet(view: EditorView): boolean {
|
||||
if (!view.state.field(fields, false)) return false;
|
||||
view.dispatch({ effects: setSnippet.of(null) });
|
||||
return true;
|
||||
}
|
||||
|
||||
export const escapeSnippet: Command = (view) => {
|
||||
const sel = view.state.selection;
|
||||
if (sel.ranges.some((r) => !r.empty)) {
|
||||
closeCompletion(view);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
|
||||
sel.mainIndex,
|
||||
),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (completionStatus(view.state) === "active") return closeCompletion(view);
|
||||
return clearLinkedSnippet(view) || clearSnippet(view);
|
||||
};
|
||||
|
||||
function fieldSelection(value: ActiveSnippet, field: number): EditorSelection {
|
||||
return EditorSelection.create(
|
||||
primarySegments(value, field).map(({ from, to }) => EditorSelection.range(from, to)),
|
||||
value.mainSite,
|
||||
);
|
||||
}
|
||||
|
||||
function selectField(view: EditorView, value: ActiveSnippet, active: number): boolean {
|
||||
if (active < 0 || active > value.last) return false;
|
||||
view.dispatch({
|
||||
selection: fieldSelection(value, active),
|
||||
effects: setSnippet.of(active === value.last ? null : { ...value, active }),
|
||||
scrollIntoView: true,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export function hasLinkedSnippetField(state: EditorState, direction: 1 | -1): boolean {
|
||||
const value = state.field(fields, false);
|
||||
return !!value && (direction === 1 ? value.active < value.last : value.active > 0);
|
||||
}
|
||||
|
||||
export const nextLiveSnippetField: Command = (view) => {
|
||||
const value = view.state.field(fields, false);
|
||||
return !!value && !value.completion && selectField(view, value, value.active + 1);
|
||||
};
|
||||
|
||||
const linkedSnippetExtension = [
|
||||
fields,
|
||||
mirrorEdits,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
{
|
||||
key: "Tab",
|
||||
run: (view) => {
|
||||
const value = view.state.field(fields);
|
||||
return (
|
||||
!!value &&
|
||||
!view.state.readOnly &&
|
||||
completionStatus(view.state) !== "active" &&
|
||||
selectField(view, value, value.active + 1)
|
||||
);
|
||||
},
|
||||
shift: (view) => {
|
||||
const value = view.state.field(fields);
|
||||
return !!value && selectField(view, value, value.active - 1);
|
||||
},
|
||||
},
|
||||
{ key: "Escape", run: (view) => !!view.state.field(fields) && escapeSnippet(view) },
|
||||
]),
|
||||
),
|
||||
EditorView.domEventHandlers({
|
||||
mousedown(event, view) {
|
||||
const value = view.state.field(fields);
|
||||
if (!value || event.button !== 0) return false;
|
||||
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
if (pos === null) return false;
|
||||
const segment = value.segments.find((range) => contains(range, pos, pos));
|
||||
return !!segment && segment.field !== value.active && selectField(view, value, segment.field);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
function codeMirrorSnippet(tr: Transaction): { active: number; ranges: SnippetRange[] } | undefined {
|
||||
// CodeMirror exposes the native snippet's unmerged ranges through its state effect.
|
||||
return tr.effects
|
||||
.map(({ value }) => value)
|
||||
.find((value) => {
|
||||
return value && typeof value.active === "number" && Array.isArray(value.ranges);
|
||||
});
|
||||
}
|
||||
|
||||
export function snippetFieldMoved(tr: Transaction): number | undefined {
|
||||
const linked = tr.effects.find((effect) => effect.is(setSnippet));
|
||||
if (linked) return linked.value?.completion ? undefined : linked.value?.active;
|
||||
return codeMirrorSnippet(tr)?.active;
|
||||
}
|
||||
|
||||
/** Render with CodeMirror to keep its snippet syntax and indentation. */
|
||||
function instantiate(source: EditorState, site: SnippetSite) {
|
||||
const line = source.doc.lineAt(site.from);
|
||||
const from = site.from - line.from;
|
||||
const to = site.to - line.from;
|
||||
const state = EditorState.create({
|
||||
doc: source.doc.slice(line.from, source.doc.lineAt(site.to).to),
|
||||
selection: EditorSelection.cursor(to),
|
||||
extensions: [indentUnit.of(source.facet(indentUnit))],
|
||||
});
|
||||
let insert = Text.empty;
|
||||
let ranges: SnippetRange[] = [];
|
||||
// An extra anonymous stop exposes the range effect even when a snippet has only one field.
|
||||
snippet(site.snippet + "#{}")(
|
||||
{
|
||||
state,
|
||||
dispatch(tr) {
|
||||
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
|
||||
insert = text;
|
||||
});
|
||||
ranges = codeMirrorSnippet(tr)?.ranges ?? [];
|
||||
},
|
||||
},
|
||||
null,
|
||||
from,
|
||||
to,
|
||||
);
|
||||
const end = ranges.at(-1);
|
||||
const seen = new Set<number>();
|
||||
const segments = ranges.slice(0, -1).map((range) => {
|
||||
const primary = !seen.has(range.field);
|
||||
seen.add(range.field);
|
||||
return { ...range, primary };
|
||||
});
|
||||
return { ...site, offset: from, insert, segments, end };
|
||||
}
|
||||
|
||||
export function applySnippet(view: EditorView, sites: readonly SnippetSite[], completion: Completion | null = null) {
|
||||
const { state } = view;
|
||||
const { main } = state.selection;
|
||||
const entries = sites.map((site) =>
|
||||
instantiate(state, { ...site, to: sites.length === 1 && site.to === main.from ? main.to : site.to }),
|
||||
);
|
||||
if (entries.length === 1 && entries[0]!.segments.every((segment) => segment.primary)) {
|
||||
const { snippet: source, from, to } = sites[0]!;
|
||||
clearLinkedSnippet(view);
|
||||
snippet(source)(view, completion, from, to);
|
||||
return;
|
||||
}
|
||||
|
||||
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
|
||||
let last = Math.max(...entries[0]!.segments.map(({ field }) => field));
|
||||
const needsEnd = entries.some(({ segments }) =>
|
||||
segments.some((segment) => segment.field === last && !segment.primary),
|
||||
);
|
||||
if (needsEnd) last++;
|
||||
const segments = entries.flatMap((entry, site) => {
|
||||
const offset = changes.mapPos(entry.from, -1) - entry.offset;
|
||||
const ranges = [...entry.segments];
|
||||
if (needsEnd && entry.end) ranges.push({ ...entry.end, primary: true });
|
||||
return ranges.map((segment) => ({ ...segment, site, from: segment.from + offset, to: segment.to + offset }));
|
||||
});
|
||||
const value = {
|
||||
segments,
|
||||
active: 0,
|
||||
last,
|
||||
mainSite: sites.length === 1 ? 0 : state.selection.mainIndex,
|
||||
completion: !!completion,
|
||||
};
|
||||
clearSnippet(view);
|
||||
view.dispatch({
|
||||
changes,
|
||||
selection: fieldSelection(value, 0),
|
||||
effects: [
|
||||
setSnippet.of(last > 0 ? value : null),
|
||||
...(state.field(fields, false) === undefined ? [StateEffect.appendConfig.of(linkedSnippetExtension)] : []),
|
||||
],
|
||||
annotations: completion ? pickedCompletion.of(completion) : isolateHistory.of("full"),
|
||||
userEvent: completion ? "input.complete" : undefined,
|
||||
scrollIntoView: true,
|
||||
});
|
||||
}
|
||||
@@ -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(
|
||||
"",
|
||||
);
|
||||
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", "AP8=", create)).toBe("");
|
||||
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 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==" } }));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
|
||||
import * as contributions from "@/workbench/contributions";
|
||||
import {
|
||||
registerEditorKind,
|
||||
registerMenuGroup,
|
||||
registerTextEditorWrapper,
|
||||
setProjectViewLead,
|
||||
useProjectViewLead,
|
||||
@@ -579,6 +580,46 @@ describe("EditorController", () => {
|
||||
useProject.setState({ project: null, settings: null });
|
||||
});
|
||||
|
||||
it("offers contributed Copy Path links in the tab menu like the other copy menus", async () => {
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
const dispose = registerActions(
|
||||
["project.copyAbsolutePath", "project.copyFileName", "project.copyRelativePath"].map((id) => ({
|
||||
id,
|
||||
title: id,
|
||||
run: () => undefined,
|
||||
})),
|
||||
);
|
||||
const links = registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: () => [{ id: "test.copyLink", label: "GitHub Link", verbatim: true, run: () => undefined }],
|
||||
});
|
||||
try {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const s = useTabs.getState();
|
||||
const pane = s.panes[s.activePane]!;
|
||||
const submenu = resolveMenuItems(ctrl.tabMenu(pane.id, pane.tabs[0]!)).find(
|
||||
(i) => i.label === "Copy Path/Reference…",
|
||||
)!.submenu!;
|
||||
expect(resolveMenuItems(submenu).map((i) => (i.kind === "separator" ? "-" : i.label))).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"Path From Content Root",
|
||||
"-",
|
||||
"GitHub Link",
|
||||
]);
|
||||
} finally {
|
||||
dispose();
|
||||
links();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["editor", "tab"])(
|
||||
"offers grouped Git actions in the %s menu and preserves action enablement",
|
||||
async (menu) => {
|
||||
|
||||
@@ -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(),
|
||||
@@ -2324,6 +2325,9 @@ export class EditorController implements SlotHost {
|
||||
},
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
// The links the project view and the editor chooser offer (features/vcs: GitHub Link).
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", { paths: [path] }),
|
||||
],
|
||||
},
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -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 }));
|
||||
|
||||
@@ -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"] }],
|
||||
});
|
||||
|
||||
@@ -297,6 +297,23 @@ describe("applying completions", () => {
|
||||
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
|
||||
});
|
||||
|
||||
it("edits repeated LSP placeholders from one selection", () => {
|
||||
const { view, req } = setup("lo|", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
const completion = makeCompletion(
|
||||
item({ kind: "snippet", insertText: "log(${1:value}, $1, ${2:label})$0", isSnippet: true }),
|
||||
req,
|
||||
);
|
||||
apply(view, completion, 0);
|
||||
expect(view.state.selection.ranges).toHaveLength(1);
|
||||
expect(view.state.doc.toString()).toBe("log(value, value, label)");
|
||||
view.dispatch(view.state.replaceSelection("name"));
|
||||
expect(view.state.doc.toString()).toBe("log(name, name, label)");
|
||||
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Enter" }), "editor")).toBe(false);
|
||||
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
|
||||
const { from, to } = view.state.selection.main;
|
||||
expect(view.state.sliceDoc(from, to)).toBe("label");
|
||||
});
|
||||
|
||||
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
|
||||
const executed: string[] = [];
|
||||
setInvokeRoute((cmd) => {
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
moveCompletionSelection,
|
||||
pickedCompletion,
|
||||
selectedCompletion,
|
||||
snippet,
|
||||
startCompletion,
|
||||
type Completion,
|
||||
type CompletionContext,
|
||||
@@ -53,6 +52,7 @@ import {
|
||||
typeColumnText,
|
||||
withoutDuplicates,
|
||||
} from "./completionItems";
|
||||
import { applySnippet } from "@/editor/core/cm/linkedSnippet";
|
||||
import { lspSnippetToCm, lspSnippetToPlainWithCaret, snippetVariables } from "./snippet";
|
||||
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
|
||||
import { offsetToPos, posToOffset, textEditsToChanges } from "./positions";
|
||||
@@ -296,7 +296,8 @@ export function applyLspCompletion(
|
||||
start = tr.changes.mapPos(start, 1);
|
||||
end = tr.changes.mapPos(end, 1);
|
||||
}
|
||||
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
|
||||
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
|
||||
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
|
||||
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
|
||||
// signature help says there is nothing to pass.
|
||||
const head = view.state.selection.main.head;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* it follows the caret and closes when the server reports no signature;
|
||||
* ⇥ / ⇧⇥ move to the next / previous argument.
|
||||
*/
|
||||
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
|
||||
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
|
||||
import {
|
||||
@@ -289,7 +290,8 @@ function moveToArgument(view: EditorView, dir: 1 | -1): boolean {
|
||||
if (!state.field(signatureField, false) || state.readOnly) return false;
|
||||
if (state.selection.ranges.length > 1 || completionStatus(state) === "active") return false;
|
||||
// Snippet / template fields and the in-place rename own ⇥.
|
||||
if (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)) return false;
|
||||
if (hasLinkedSnippetField(state, dir) || (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)))
|
||||
return false;
|
||||
if (inplaceRenameActive(state)) return false;
|
||||
const head = state.selection.main.head;
|
||||
const to = argumentStop(state.doc.toString(), head, dir);
|
||||
|
||||
@@ -193,11 +193,17 @@ export function lspSnippetToCm(snippet: string, vars: SnippetVariables = {}): st
|
||||
const hasField = nodes.some(
|
||||
(n) => n.t === "tab" || n.t === "choice" || (n.t === "var" && vars[n.name] === undefined && !n.children),
|
||||
);
|
||||
const defaults = new Map<number, string>();
|
||||
for (const node of nodes) {
|
||||
if (node.t === "text" || node.t === "var" || node.n === 0 || defaults.has(node.n)) continue;
|
||||
if (node.t === "choice") defaults.set(node.n, node.options[0] ?? "");
|
||||
else if (node.children) defaults.set(node.n, flatten(node.children, vars));
|
||||
}
|
||||
let out = "";
|
||||
for (const n of nodes) {
|
||||
if (n.t === "text") out += escapeText(n.v);
|
||||
else if (n.t === "tab") out += field(n.n, n.children ? flatten(n.children, vars) : "");
|
||||
else if (n.t === "choice") out += field(n.n, n.options[0] ?? "");
|
||||
else if (n.t === "tab") out += field(n.n, defaults.get(n.n) ?? (n.children ? flatten(n.children, vars) : ""));
|
||||
else if (n.t === "choice") out += field(n.n, defaults.get(n.n) ?? n.options[0] ?? "");
|
||||
else {
|
||||
const v = vars[n.name];
|
||||
if (v !== undefined) out += escapeText(v);
|
||||
|
||||
@@ -25,6 +25,7 @@ import { isNavigating, onNavigation } from "@/editor/lsp/foreground";
|
||||
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
|
||||
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
|
||||
import {
|
||||
commands,
|
||||
isCancelled,
|
||||
@@ -542,13 +543,32 @@ async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Loc
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the single target, or the chooser over several. */
|
||||
/** Resolves each declaration's targets before opening the shared chooser. */
|
||||
export async function openMarkerTargets(
|
||||
marker: LineMarker,
|
||||
markers: readonly [LineMarker, ...LineMarker[]],
|
||||
anchor: { x: number; y: number },
|
||||
doc: DocId | null = null,
|
||||
) {
|
||||
const targets = await markerTargets(marker, doc);
|
||||
const [first] = markers;
|
||||
const merged = markers.length > 1;
|
||||
let targets: DeclarationTarget[] = (
|
||||
await Promise.all(
|
||||
markers.map(async (marker) => {
|
||||
const locations = await markerTargets(marker, doc);
|
||||
// Generated methods can share a source location. Keep their names visible in the chooser.
|
||||
return merged && marker.method ? locations.map((target) => ({ ...target, name: marker.name })) : locations;
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
if (merged) {
|
||||
const seen = new Set<string>();
|
||||
targets = targets.filter(({ path, range, name }) => {
|
||||
const key = JSON.stringify([path, range.start.line, range.start.col, name]);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
if (targets.length === 1) {
|
||||
await navigateTo(targets[0]!);
|
||||
return;
|
||||
@@ -556,9 +576,9 @@ export async function openMarkerTargets(
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor,
|
||||
title: marker.chooserTitle,
|
||||
title: merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle,
|
||||
items: await locationItems(targets),
|
||||
pin: pinToFind(marker.name, targets),
|
||||
pin: pinToFind([...new Set(markers.map((m) => m.name))].join(", "), targets),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -587,41 +607,50 @@ function place(doc: Text, markers: readonly LineMarker[]): PlacedMarker[] {
|
||||
}
|
||||
|
||||
const sameMarkers = (a: readonly PlacedMarker[], b: readonly PlacedMarker[]) =>
|
||||
a.length === b.length &&
|
||||
a.every(
|
||||
(m, i) => m.pos === b[i]!.pos && m.marker.kind === b[i]!.marker.kind && m.marker.tooltip === b[i]!.marker.tooltip,
|
||||
);
|
||||
a.length === b.length && a.every((m, i) => m.pos === b[i]!.pos && m.marker === b[i]!.marker);
|
||||
|
||||
class InheritanceMarker extends GutterMarker {
|
||||
constructor(readonly marker: LineMarker) {
|
||||
readonly kind: LineMarker["kind"];
|
||||
readonly tooltip: string;
|
||||
|
||||
constructor(readonly markers: readonly [LineMarker, ...LineMarker[]]) {
|
||||
super();
|
||||
const [first] = markers;
|
||||
this.kind = first.kind;
|
||||
this.tooltip =
|
||||
markers.length === 1 ? first.tooltip : [...new Set(markers.map((m) => `${m.name} — ${m.tooltip}`))].join("\n");
|
||||
}
|
||||
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return (
|
||||
other instanceof InheritanceMarker &&
|
||||
other.marker.kind === this.marker.kind &&
|
||||
other.marker.tooltip === this.marker.tooltip
|
||||
);
|
||||
return other instanceof InheritanceMarker && other.kind === this.kind && other.tooltip === this.tooltip;
|
||||
}
|
||||
|
||||
override toDOM(): Node {
|
||||
const el = document.createElement("div");
|
||||
el.className = `${styles.marker} cm-openidea-lineMarker-${this.marker.kind}`;
|
||||
el.dataset.kind = this.marker.kind;
|
||||
el.title = this.marker.tooltip;
|
||||
el.className = `${styles.marker} cm-openidea-lineMarker-${this.kind}`;
|
||||
el.dataset.kind = this.kind;
|
||||
el.title = this.tooltip;
|
||||
el.setAttribute("role", "button");
|
||||
el.setAttribute("aria-label", this.marker.tooltip);
|
||||
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.marker.kind]) ?? "";
|
||||
el.setAttribute("aria-label", this.tooltip);
|
||||
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.kind]) ?? "";
|
||||
return el;
|
||||
}
|
||||
}
|
||||
|
||||
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<GutterMarker>>();
|
||||
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<InheritanceMarker>>();
|
||||
|
||||
function markerSet(placed: readonly PlacedMarker[]): RangeSet<GutterMarker> {
|
||||
function markerSet(placed: readonly PlacedMarker[]): RangeSet<InheritanceMarker> {
|
||||
let set = gutterMarkers.get(placed);
|
||||
if (!set) {
|
||||
const groups = new Map<string, { pos: number; markers: [LineMarker, ...LineMarker[]] }>();
|
||||
for (const { pos, marker } of placed) {
|
||||
const key = `${pos}:${marker.kind}`;
|
||||
const group = groups.get(key);
|
||||
if (group) group.markers.push(marker);
|
||||
else groups.set(key, { pos, markers: [marker] });
|
||||
}
|
||||
set = RangeSet.of(
|
||||
placed.map((m) => new InheritanceMarker(m.marker).range(m.pos)),
|
||||
[...groups.values()].map(({ pos, markers }) => new InheritanceMarker(markers).range(pos)),
|
||||
true,
|
||||
);
|
||||
gutterMarkers.set(placed, set);
|
||||
@@ -829,10 +858,14 @@ export function markerDeps(
|
||||
};
|
||||
}
|
||||
|
||||
function markerAt(view: EditorView, lineFrom: number, el: Element | null): LineMarker | null {
|
||||
const onLine = view.state.field(markersField).filter((m) => m.pos === lineFrom);
|
||||
const kind = (el?.closest(`.${styles.marker}`) as HTMLElement | null)?.dataset.kind;
|
||||
return (onLine.find((m) => m.marker.kind === kind) ?? (onLine.length === 1 ? onLine[0] : null))?.marker ?? null;
|
||||
function markerAt(view: EditorView, lineFrom: number, kind: string | undefined): InheritanceMarker | undefined {
|
||||
let match: InheritanceMarker | undefined;
|
||||
markerSet(view.state.field(markersField)).between(lineFrom, lineFrom, (pos, _to, marker) => {
|
||||
if (pos !== lineFrom || marker.kind !== kind) return;
|
||||
match = marker;
|
||||
return false;
|
||||
});
|
||||
return match;
|
||||
}
|
||||
|
||||
export function implementationGutter(ctx: EditorDocContext): Extension {
|
||||
@@ -846,13 +879,13 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
|
||||
markers: (view) => markerSet(view.state.field(markersField)),
|
||||
mousedown: (view, block, e) => {
|
||||
if (e.button !== 0) return false;
|
||||
const target = e.target instanceof Element ? e.target : null;
|
||||
if (!target?.closest(`.${styles.marker}`)) return false;
|
||||
const marker = markerAt(view, block.from, target);
|
||||
const target = e.target instanceof Element ? e.target.closest<HTMLElement>(`.${styles.marker}`) : null;
|
||||
if (!target) return false;
|
||||
const marker = markerAt(view, block.from, target.dataset.kind);
|
||||
if (!marker) return false;
|
||||
e.preventDefault();
|
||||
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
|
||||
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
|
||||
const rect = target.getBoundingClientRect();
|
||||
void openMarkerTargets(marker.markers, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
|
||||
import { lspDoc } from "@/editor/lsp/lsp";
|
||||
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
|
||||
import {
|
||||
IpcError,
|
||||
commands,
|
||||
@@ -14,14 +19,15 @@ const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi
|
||||
vi.mock("@/editor/lsp/navigation", async (orig) => ({
|
||||
...(await orig<typeof import("@/editor/lsp/navigation")>()),
|
||||
navigateTo: nav.navigateTo,
|
||||
locationItems: async (locs: Location[]) => locs.map((l, i) => ({ id: `${i}`, label: l.path, run: () => {} })),
|
||||
locationItems: async (locs: DeclarationTarget[]) =>
|
||||
locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path, run: () => {} })),
|
||||
}));
|
||||
vi.mock("@/editor/lsp/popupStore", async (orig) => ({
|
||||
...(await orig<typeof import("@/editor/lsp/popupStore")>()),
|
||||
openPopup: nav.openPopup,
|
||||
}));
|
||||
|
||||
import { candidateKey, markerCandidates, type MarkerCandidate } from "./lineMarkers";
|
||||
import { candidateKey, markerCandidates, type LineMarker, type MarkerCandidate } from "./lineMarkers";
|
||||
import { Text } from "@codemirror/state";
|
||||
import {
|
||||
affectsMarkers,
|
||||
@@ -29,6 +35,7 @@ import {
|
||||
emptyCache,
|
||||
enabledGroups,
|
||||
fillMarkers,
|
||||
implementationGutter,
|
||||
libraryCandidates,
|
||||
markerBatches,
|
||||
markerDeps,
|
||||
@@ -539,16 +546,18 @@ describe("clicking a marker", () => {
|
||||
it("navigates to a single target", async () => {
|
||||
const target = loc("/p/Circle.java", 0, 13);
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets: [target],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
[
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets: [target],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
],
|
||||
{ x: 1, y: 2 },
|
||||
);
|
||||
expect(nav.navigateTo).toHaveBeenCalledWith(target);
|
||||
@@ -562,16 +571,18 @@ describe("clicking a marker", () => {
|
||||
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
|
||||
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 1,
|
||||
col: 9,
|
||||
method: true,
|
||||
name: "save",
|
||||
targets: [zero],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
[
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 1,
|
||||
col: 9,
|
||||
method: true,
|
||||
name: "save",
|
||||
targets: [zero],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
],
|
||||
{ x: 1, y: 2 },
|
||||
7,
|
||||
);
|
||||
@@ -585,16 +596,18 @@ describe("clicking a marker", () => {
|
||||
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
|
||||
expect(candidateKey(candidate())).toBe("0:17:Shape");
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets,
|
||||
tooltip: "",
|
||||
chooserTitle: "Choose Implementation of Shape (2 found)",
|
||||
},
|
||||
[
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets,
|
||||
tooltip: "",
|
||||
chooserTitle: "Choose Implementation of Shape (2 found)",
|
||||
},
|
||||
],
|
||||
{ x: 1, y: 2 },
|
||||
);
|
||||
expect(nav.navigateTo).not.toHaveBeenCalled();
|
||||
@@ -609,6 +622,98 @@ describe("clicking a marker", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("inheritance gutter", () => {
|
||||
it.each([
|
||||
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
|
||||
{ kind: "overridden", language: "java", declaration: "@Data" },
|
||||
{ kind: "implementing", language: "go", declaration: "type Square struct{}" },
|
||||
{ kind: "implemented", language: "rust", declaration: "trait Shape { fn area(); fn label(); }" },
|
||||
] as const)("merges $language $kind markers by line and kind", async ({ kind, language, declaration }) => {
|
||||
vi.useFakeTimers();
|
||||
nav.navigateTo.mockClear();
|
||||
nav.openPopup.mockClear();
|
||||
const ctx = { doc: 1, path: `/p/gutter-${kind}`, language, uiMode: null, readOnly: false };
|
||||
const doc = Text.of([declaration, "another declaration"]);
|
||||
const markers = markersOf(ctx.path, doc);
|
||||
const otherKind = kind === "overridden" ? "overriding" : "overridden";
|
||||
const inputs = [
|
||||
{ kind, name: "build", line: 0 },
|
||||
{ kind: otherKind, name: "other", line: 0 },
|
||||
{ kind, name: "self", line: 0 },
|
||||
{ kind, name: "build", line: 0 },
|
||||
{ kind, name: "later", line: 1 },
|
||||
] as const;
|
||||
const candidates = inputs.map(({ name, line }, i): MarkerCandidate => ({
|
||||
name,
|
||||
line,
|
||||
symbol: `${name}(${i})`,
|
||||
col: 0,
|
||||
method: true,
|
||||
abstract: false,
|
||||
inheritable: false,
|
||||
overriding: false,
|
||||
owner: null,
|
||||
}));
|
||||
markers.outline = { items: [], candidates };
|
||||
inputs.forEach((input, i) => {
|
||||
const marker: LineMarker = {
|
||||
...input,
|
||||
col: 0,
|
||||
method: true,
|
||||
targets: [
|
||||
loc(
|
||||
language === "java" && input.kind === kind && input.line === 0 ? "/p/BaseOrder.java" : `/p/${input.name}`,
|
||||
2,
|
||||
),
|
||||
],
|
||||
tooltip: `Target for ${input.name}`,
|
||||
chooserTitle: input.name,
|
||||
};
|
||||
const group = marker.kind === "implemented" || marker.kind === "overridden" ? "inheritors" : "supers";
|
||||
markers.cache.entries.set(candidateKey(candidates[i]!), { [group]: marker });
|
||||
});
|
||||
const view = new EditorView({
|
||||
doc,
|
||||
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
|
||||
parent: document.body,
|
||||
});
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
const icons = [...view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`)];
|
||||
expect(icons).toHaveLength(2);
|
||||
expect(icons[0]!.title).toContain("Target for build");
|
||||
expect(icons[0]!.title).toContain("Target for self");
|
||||
expect(icons[0]!.title).not.toContain("Target for later");
|
||||
expect(icons[0]!.parentElement!.querySelector(`.cm-openidea-lineMarker-${otherKind}`)).not.toBeNull();
|
||||
|
||||
fireEvent.mouseDown(icons[0]!, { button: 0 });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(nav.navigateTo).not.toHaveBeenCalled();
|
||||
expect(nav.openPopup.mock.calls[0]![0].items.map((item: { label: string }) => item.label)).toEqual([
|
||||
"build",
|
||||
"self",
|
||||
]);
|
||||
|
||||
// CodeMirror finds the clicked line by the gutter row's screen position.
|
||||
const block = view.lineBlockAt(doc.line(2).from);
|
||||
vi.spyOn(icons[1]!.parentElement!, "getBoundingClientRect").mockReturnValue(
|
||||
new DOMRect(0, view.documentTop + block.top, 10, block.height),
|
||||
);
|
||||
fireEvent.mouseDown(icons[1]!, { button: 0 });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(nav.navigateTo).toHaveBeenCalledWith(loc("/p/later", 2));
|
||||
|
||||
view.dispatch({ changes: { from: doc.line(1).to, to: doc.line(2).from, insert: " " } });
|
||||
const joined = view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`);
|
||||
expect(joined).toHaveLength(1);
|
||||
expect(joined[0]!.title).toContain("Target for later");
|
||||
} finally {
|
||||
view.destroy();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("overriders of a type's methods from its subtypes", () => {
|
||||
// Shapes and names as jdtls answers them (outline names carry the signature).
|
||||
const REPO = [
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -36,7 +36,9 @@
|
||||
outline: none;
|
||||
}
|
||||
.field :global(.cm-scroller) {
|
||||
height: auto;
|
||||
max-height: 280px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
font-family: inherit;
|
||||
line-height: 1.5;
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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"];
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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…. */
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,6 @@ export async function javaLaunchConfig(
|
||||
root: string,
|
||||
preparation?: JavaPreparation,
|
||||
): Promise<LaunchConfig> {
|
||||
const cwd = rc.cwd ? join(root, rc.cwd) : root;
|
||||
rc = await withEnvFiles(rc, root);
|
||||
const parsed = parseJavaArgs(rc.args);
|
||||
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
|
||||
@@ -155,6 +154,7 @@ export async function javaLaunchConfig(
|
||||
},
|
||||
},
|
||||
);
|
||||
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
|
||||
if (info.errorCount > 0 && !preparation?.report)
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2,22 +2,17 @@ import { EditorView } from "@codemirror/view";
|
||||
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { scratchesDir } from "@/platform/scratchesDir";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { appendRequests } from "./spring/request";
|
||||
|
||||
export const GENERATED_REQUESTS = "generated-requests.http";
|
||||
|
||||
async function scratchFile(): Promise<{ path: string; created: boolean }> {
|
||||
const dir = `${await appDataDir()}/scratches`;
|
||||
const ignoreExisting = (e: unknown) => {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
};
|
||||
await call(commands.fsCreateDir(dir)).catch(ignoreExisting);
|
||||
const path = `${dir}/${GENERATED_REQUESTS}`;
|
||||
const path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
|
||||
let created = true;
|
||||
await call(commands.fsCreateFile(path)).catch((e) => {
|
||||
ignoreExisting(e);
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
created = false;
|
||||
});
|
||||
return { path, created };
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
|
||||
import { executeAction, getAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { scratchesDir } from "@/platform/scratchesDir";
|
||||
import {
|
||||
editorService,
|
||||
notifications,
|
||||
@@ -116,11 +116,13 @@ function directoryArg(arg: unknown): string | null {
|
||||
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
|
||||
async function newRequest(directory?: string) {
|
||||
try {
|
||||
const dir = directory ?? `${await appDataDir()}/scratches`;
|
||||
try {
|
||||
await call(commands.fsCreateDir(dir));
|
||||
} catch (e) {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
const dir = directory ?? (await scratchesDir());
|
||||
if (directory) {
|
||||
try {
|
||||
await call(commands.fsCreateDir(dir));
|
||||
} catch (e) {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
}
|
||||
}
|
||||
const names = new Set((await call(commands.fsReadDir(dir))).map((e) => e.name.toLowerCase()));
|
||||
let name = "requests.http";
|
||||
|
||||
@@ -4,12 +4,6 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co
|
||||
import { springControllers } from "./endpoints";
|
||||
import { generateRequests } from "./editor";
|
||||
|
||||
// The backend reports the user data directory `/`-separated on every OS.
|
||||
vi.mock("@/platform/platformInfo", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/platformInfo")>()),
|
||||
appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea",
|
||||
}));
|
||||
|
||||
// No backend here: the file commands answer like a project without Spring
|
||||
// configuration files (empty configs, the files the body lookup probes missing).
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
@@ -19,7 +13,8 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
call: async (p: Promise<unknown>) => await p,
|
||||
commands: {
|
||||
...m.commands,
|
||||
fsCreateDir: async () => null,
|
||||
// The backend reports the scratches folder `/`-separated on every OS.
|
||||
fsScratchesDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches",
|
||||
fsCreateFile: async () => null,
|
||||
fsReadText: async () => "",
|
||||
},
|
||||
|
||||
@@ -17,14 +17,40 @@ import {
|
||||
isLibraryPath,
|
||||
registerEditorContribution,
|
||||
setLibraryRoots,
|
||||
useEditorRegistry,
|
||||
} from "@/editor/api";
|
||||
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { libraryArchiveRoot } from "@/platform/virtualDocs";
|
||||
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
|
||||
import { goModNavigationExtension } from "./goModNavigation";
|
||||
|
||||
export const EXTERNAL_LIBRARIES_LABEL = "External Libraries";
|
||||
|
||||
/** A jdtls URI's `maven.*` attributes, as the group label used by build dependencies. */
|
||||
function archiveGroupName(uri: string, fallback: string): string {
|
||||
let query = uri.split("?")[1] ?? "";
|
||||
try {
|
||||
query = decodeURIComponent(query);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
const field = (name: string) => new RegExp(`maven\\.${name}=/([^=]+)=`).exec(query)?.[1];
|
||||
const [group, artifact, version] = [field("groupId"), field("artifactId"), field("version")];
|
||||
if (!group || !artifact || !version) return fallback;
|
||||
const classifier = field("classifier");
|
||||
return `Maven: ${group}:${artifact}:${version}${classifier ? `:${classifier}` : ""}`;
|
||||
}
|
||||
|
||||
/** A class opened from a jar the build model has not listed yet; show its exact archive. */
|
||||
export function openedLibraryGroup(uri: string, groups: readonly LibraryGroup[]): LibraryGroup | null {
|
||||
const archive = libraryArchiveRoot(uri);
|
||||
if (!archive || groups.some((group) => group.roots.some((root) => root.path === archive))) return null;
|
||||
const separator = Math.max(archive.lastIndexOf("/"), archive.lastIndexOf("\\"));
|
||||
const name = archive.slice(separator + 1, -1) || archive;
|
||||
return { name: archiveGroupName(uri, name), kind: "classpath", roots: [{ name, path: archive }] };
|
||||
}
|
||||
|
||||
const GROUP_ICONS: Record<string, string> = {
|
||||
python: "file-python",
|
||||
jdk: "file-java",
|
||||
@@ -174,6 +200,10 @@ export function activate(): () => void {
|
||||
let shown = "";
|
||||
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
|
||||
let settled: LibraryGroup[] = [];
|
||||
/** The last build/SDK result, before archives opened from the editor are added. */
|
||||
let backendGroups: LibraryGroup[] = [];
|
||||
/** One group per opened archive, so the build model can replace each archive independently. */
|
||||
let openedGroups: LibraryGroup[] = [];
|
||||
let request: RequestId | undefined;
|
||||
/** The project whose libraries are shown (and `settled`). */
|
||||
let shownFor: string | null = null;
|
||||
@@ -184,8 +214,36 @@ export function activate(): () => void {
|
||||
shown = "";
|
||||
shownGroups = [];
|
||||
settled = [];
|
||||
backendGroups = [];
|
||||
openedGroups = [];
|
||||
shownFor = null;
|
||||
};
|
||||
const render = (groups: LibraryGroup[]) => {
|
||||
backendGroups = groups;
|
||||
const covered = new Set(groups.flatMap((g) => g.roots.map((r) => r.path)));
|
||||
openedGroups = openedGroups.filter((g) => !g.roots.some((r) => covered.has(r.path)));
|
||||
const all = mergeLibraryGroups([...groups, ...openedGroups]);
|
||||
const key = JSON.stringify(all);
|
||||
if (key === shown) return;
|
||||
// The new node replaces the old one in place: removing it first would drop it from the tree
|
||||
// until the new one renders, and collapse it.
|
||||
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
|
||||
disposeRoot = disposeReadOnly = () => {};
|
||||
shown = key;
|
||||
// ⌘-hover may have probed a go.mod entry before its module was listed.
|
||||
if (goModules(all) !== goModules(shownGroups)) invalidateNavigationProviders();
|
||||
shownGroups = all;
|
||||
const root = librariesRoot(all);
|
||||
if (root) {
|
||||
disposeReadOnly = setLibraryRoots(
|
||||
"externalLibraries",
|
||||
all.flatMap((g) => g.roots.map((r) => r.path)),
|
||||
);
|
||||
disposeRoot = registerProjectViewRoot(root);
|
||||
}
|
||||
oldRoot();
|
||||
oldReadOnly();
|
||||
};
|
||||
const refresh = () => {
|
||||
const id = ++seq;
|
||||
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
|
||||
@@ -200,26 +258,7 @@ export function activate(): () => void {
|
||||
let collected: LibraryGroup[] = [];
|
||||
const show = (groups: LibraryGroup[]) => {
|
||||
if (id !== seq) return;
|
||||
const key = JSON.stringify(groups);
|
||||
if (key === shown) return;
|
||||
// The new node replaces the old one in place: removing it first would drop it from the tree
|
||||
// until the new one renders, and collapse it.
|
||||
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
|
||||
disposeRoot = disposeReadOnly = () => {};
|
||||
shown = key;
|
||||
// ⌘-hover may have probed a go.mod entry before its module was listed.
|
||||
if (goModules(groups) !== goModules(shownGroups)) invalidateNavigationProviders();
|
||||
shownGroups = groups;
|
||||
const root = librariesRoot(groups);
|
||||
if (root) {
|
||||
disposeReadOnly = setLibraryRoots(
|
||||
"externalLibraries",
|
||||
groups.flatMap((g) => g.roots.map((r) => r.path)),
|
||||
);
|
||||
disposeRoot = registerProjectViewRoot(root);
|
||||
}
|
||||
oldRoot();
|
||||
oldReadOnly();
|
||||
render(groups);
|
||||
};
|
||||
const channel = new Channel<LibraryGroup[]>();
|
||||
channel.onmessage = (groups) => {
|
||||
@@ -242,6 +281,13 @@ export function activate(): () => void {
|
||||
});
|
||||
};
|
||||
refresh();
|
||||
const showOpenedLibrary = (path: string | null) => {
|
||||
if (!path || !shownFor) return;
|
||||
const group = openedLibraryGroup(path, shownGroups);
|
||||
if (!group) return;
|
||||
openedGroups.push(group);
|
||||
render(backendGroups);
|
||||
};
|
||||
const disposeGoMod = registerEditorContribution({
|
||||
id: "libraries.goModNavigation",
|
||||
extensions: goModNavigationExtension((path, version) => goModuleRoot(shownGroups, path, version), isLibraryPath),
|
||||
@@ -252,6 +298,11 @@ export function activate(): () => void {
|
||||
const unsub = useProject.subscribe((s, prev) => {
|
||||
if (sdkKey(s) !== sdkKey(prev)) refresh();
|
||||
});
|
||||
const unsubEditor = useEditorRegistry.subscribe((s, prev) => {
|
||||
const path = s.active?.ctx.path ?? null;
|
||||
if (path !== (prev.active?.ctx.path ?? null)) showOpenedLibrary(path);
|
||||
});
|
||||
showOpenedLibrary(useEditorRegistry.getState().active?.ctx.path ?? null);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const unsubFs = onIdeEvent("fsChanged", (e) => {
|
||||
if (!touchesManifest([...e.created, ...e.modified, ...e.removed])) return;
|
||||
@@ -268,6 +319,7 @@ export function activate(): () => void {
|
||||
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
|
||||
clearTimeout(timer);
|
||||
unsub();
|
||||
unsubEditor();
|
||||
unsubFs();
|
||||
unsubRoots();
|
||||
disposeActions();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { isLibraryPath, setLibraryRoots } from "@/editor/api";
|
||||
import { librariesRoot, touchesManifest } from "./index";
|
||||
import { librariesRoot, openedLibraryGroup, touchesManifest } from "./index";
|
||||
import { mergeLibraryGroups } from "@/platform/libraries";
|
||||
|
||||
describe("External Libraries", () => {
|
||||
@@ -116,6 +116,27 @@ describe("External Libraries", () => {
|
||||
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
|
||||
});
|
||||
|
||||
it("adds the classifier jar opened from a library class when the build model omits it", () => {
|
||||
const uri =
|
||||
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.groupId=/com.example=/=/maven.artifactId=/demo-lib=/=/maven.version=/1.0=/=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
|
||||
expect(openedLibraryGroup(uri, [])).toEqual({
|
||||
name: "Maven: com.example:demo-lib:1.0:jdk21",
|
||||
kind: "classpath",
|
||||
roots: [
|
||||
{
|
||||
name: "demo-lib-1.0-jdk21.jar",
|
||||
path: "/m2/com/example/demo-lib/1.0/demo-lib-1.0-jdk21.jar!",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not duplicate an archive the build model already lists", () => {
|
||||
const uri = "jdt://contents/a.jar/p/C.class?=demo/%5C/m2%5C/a.jar%3Cp%28C.class";
|
||||
const group = { name: "a.jar", kind: "maven", roots: [{ name: "a.jar", path: "/m2/a.jar!" }] };
|
||||
expect(openedLibraryGroup(uri, [group])).toBeNull();
|
||||
});
|
||||
|
||||
it("refreshes on manifest changes outside node_modules", () => {
|
||||
expect(touchesManifest(["/p/src/main.rs", "/p/Cargo.toml"])).toBe(true);
|
||||
expect(touchesManifest(["C:\\p\\go.mod"])).toBe(true);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LibraryGroup } from "@/bindings";
|
||||
|
||||
const results: LibraryGroup[][] = [];
|
||||
@@ -31,6 +31,7 @@ vi.mock("@/platform/ipc", () => ({
|
||||
}));
|
||||
|
||||
const { activate } = await import("./index");
|
||||
const { useEditorRegistry } = await import("@/editor/api");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { useProjectViewRoots } = await import("@/workbench/contributions");
|
||||
const { executeAction } = await import("@/platform/actions");
|
||||
@@ -42,6 +43,13 @@ const rust = (version: string): LibraryGroup => ({
|
||||
});
|
||||
|
||||
describe("External Libraries refresh", () => {
|
||||
afterEach(() => {
|
||||
results.length = 0;
|
||||
streamed.length = 0;
|
||||
hang = false;
|
||||
useEditorRegistry.setState({ active: null });
|
||||
});
|
||||
|
||||
it("replaces the node in place when the libraries change", async () => {
|
||||
useProject.setState({
|
||||
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
|
||||
@@ -86,4 +94,54 @@ describe("External Libraries refresh", () => {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps other opened archives with the same name when the build lists one of them", async () => {
|
||||
const first = "/first/library.jar!";
|
||||
const second = "/second/library.jar!";
|
||||
useProject.setState({
|
||||
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
|
||||
});
|
||||
const dispose = activate();
|
||||
const paths = () =>
|
||||
useProjectViewRoots
|
||||
.getState()
|
||||
.roots.get("externalLibraries")
|
||||
?.children?.flatMap((group) => group.children?.map((root) => root.path) ?? [])
|
||||
.sort();
|
||||
try {
|
||||
for (const archive of [first, second]) {
|
||||
useEditorRegistry.setState({ active: { ctx: { path: `jar:file://${archive}/p/Example.class` } } as never });
|
||||
}
|
||||
await vi.waitFor(() => expect(paths()).toEqual([first, second]));
|
||||
|
||||
results.push([{ name: "Build dependency", kind: "gradle", roots: [{ name: "library.jar", path: first }] }]);
|
||||
await executeAction("libraries.reload");
|
||||
await vi.waitFor(() =>
|
||||
expect(useProjectViewRoots.getState().roots.get("externalLibraries")?.children?.[0]?.label).toBe(
|
||||
"Build dependency",
|
||||
),
|
||||
);
|
||||
expect(paths()).toEqual([first, second]);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the exact classifier jar of the library class opened in the editor", async () => {
|
||||
const uri =
|
||||
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
|
||||
useProject.setState({
|
||||
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
|
||||
});
|
||||
useEditorRegistry.setState({ active: { ctx: { path: uri } } as never });
|
||||
results.push([]);
|
||||
const dispose = activate();
|
||||
const labels = () =>
|
||||
useProjectViewRoots
|
||||
.getState()
|
||||
.roots.get("externalLibraries")
|
||||
?.children?.[0]?.children?.map((g) => g.label);
|
||||
await vi.waitFor(() => expect(labels()).toContain("demo-lib-1.0-jdk21.jar"));
|
||||
dispose();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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,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,7 +2,17 @@ import { shortcutLabel } from "@/platform/keymap";
|
||||
import { IconButton, type MenuItem } from "@/ui";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { userScopes } from "@/platform/scopes";
|
||||
import { VIEW_MODES, setScopeView, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
|
||||
import { useEditorPrefs } from "@/platform/editorSettings";
|
||||
import {
|
||||
VIEW_MODES,
|
||||
previewTabEnabled,
|
||||
setPreviewTabEnabled,
|
||||
setScopeView,
|
||||
setViewMode,
|
||||
setViewOption,
|
||||
useProjectTree,
|
||||
type ViewOptions,
|
||||
} from "./store";
|
||||
import type { SortKey } from "./model";
|
||||
|
||||
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
|
||||
@@ -35,9 +45,22 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
|
||||
}
|
||||
|
||||
/** The on / off view options. */
|
||||
export type ToggleOption = {
|
||||
type ViewToggle = {
|
||||
[K in keyof ViewOptions]-?: ViewOptions[K] extends boolean ? K : never;
|
||||
}[keyof ViewOptions];
|
||||
/** The view's switches, plus the editor's preview tab setting it shares (as in IDEA). */
|
||||
export type ToggleOption = ViewToggle | "previewTab";
|
||||
|
||||
const toggleState = (key: ToggleOption, options: ViewOptions, preview: boolean) =>
|
||||
key === "previewTab" ? preview : options[key];
|
||||
|
||||
export const isToggled = (key: ToggleOption) =>
|
||||
toggleState(key, useProjectTree.getState().options, previewTabEnabled());
|
||||
|
||||
export function flipToggle(key: ToggleOption) {
|
||||
if (key === "previewTab") void setPreviewTabEnabled(!previewTabEnabled());
|
||||
else setViewOption(key, !useProjectTree.getState().options[key]);
|
||||
}
|
||||
|
||||
const APPEARANCE_OPTIONS: Array<[ToggleOption, string]> = [
|
||||
["showHidden", "Show Hidden Files"],
|
||||
@@ -90,22 +113,26 @@ export const SORT_LABELS: Array<[key: SortKey, actionLabel: string, menuLabel: s
|
||||
/** Project view options in the header's "⋮" menu. */
|
||||
export function useProjectHeaderMenu(): MenuItem[] {
|
||||
const options = useProjectTree((s) => s.options);
|
||||
const preview = useEditorPrefs().tabs.previewTab;
|
||||
const option = (key: ToggleOption, label: string): MenuItem => ({
|
||||
id: key,
|
||||
label,
|
||||
checked: toggleState(key, options, preview),
|
||||
run: () => flipToggle(key),
|
||||
});
|
||||
const unity = useProjectTree((s) => s.mode === "unity");
|
||||
return [
|
||||
{
|
||||
label: "Behavior",
|
||||
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label, options)),
|
||||
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label)),
|
||||
},
|
||||
{
|
||||
label: "Appearance",
|
||||
submenu: [
|
||||
...(unity
|
||||
? [
|
||||
option("showUnityMeta", "Show Meta Files", options),
|
||||
option("showUnityGenerated", "Show Generated Files", options),
|
||||
]
|
||||
? [option("showUnityMeta", "Show Meta Files"), option("showUnityGenerated", "Show Generated Files")]
|
||||
: []),
|
||||
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label, options)),
|
||||
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label)),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -118,12 +145,8 @@ export function useProjectHeaderMenu(): MenuItem[] {
|
||||
run: () => setViewOption("sortBy", sortBy),
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
option(...FOLDERS_FIRST, options),
|
||||
option(...FOLDERS_FIRST),
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function option(key: ToggleOption, label: string, options: ViewOptions): MenuItem {
|
||||
return { id: key, label, checked: options[key], run: () => setViewOption(key, !options[key]) };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { installRepeatedDoubleClick } from "@/platform/doubleClick";
|
||||
import { getContext, setContext } from "@/platform/context";
|
||||
@@ -22,13 +22,17 @@ import { beginNew, canPaste } from "./operations";
|
||||
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
|
||||
import type { OutlineItem } from "@/bindings";
|
||||
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
|
||||
import { ProjectHeaderActions } from "./HeaderActions";
|
||||
import { ProjectHeaderActions, useProjectHeaderMenu } from "./HeaderActions";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { loadOutline } from "./store";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
docOpen: vi.fn(),
|
||||
docClose: vi.fn(),
|
||||
docOutline: vi.fn(),
|
||||
settingsSet: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/bindings", async (orig) => {
|
||||
const real = await orig<typeof import("@/bindings")>();
|
||||
@@ -58,6 +62,11 @@ const deferred = <T,>() => {
|
||||
};
|
||||
|
||||
const ROOT = "/w/acme";
|
||||
const initialSettings = useProject.getState().settings;
|
||||
|
||||
/** Settings › Editor › General › Editor Tabs › Enable preview tab. */
|
||||
const previewTabSettings = (on: boolean) => ({ editor: { tabs: { previewTab: on } } });
|
||||
const setPreviewTabSetting = (on: boolean) => act(() => useProject.setState({ settings: previewTabSettings(on) }));
|
||||
let fs: MemoryFs;
|
||||
let openFile: ReturnType<typeof vi.fn>;
|
||||
let dispose: () => void;
|
||||
@@ -98,6 +107,7 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
useProject.setState({ settings: initialSettings });
|
||||
setProjectFsForTests(null);
|
||||
uninstallDispatcher?.();
|
||||
uninstallDispatcher = null;
|
||||
@@ -222,6 +232,42 @@ describe("ProjectView", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("pastes a copied keyword into the tree's speed search instead of pasting files", async () => {
|
||||
dispatchViaKeymap();
|
||||
// Explorer holds a file, and the user wants to paste a word they copied from somewhere else
|
||||
// into the search they just opened with ⌘F.
|
||||
fs.nodes.set("/elsewhere/Photo.png", { kind: "file", size: 3 });
|
||||
setOsClipboardForTests({
|
||||
files: async () => ["/elsewhere/Photo.png"],
|
||||
hasFiles: async () => true,
|
||||
setFiles: async () => false,
|
||||
});
|
||||
try {
|
||||
const { tree, row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
fireEvent.mouseDown(row("src"));
|
||||
tree.focus();
|
||||
fireEvent.keyDown(tree, { key: "f", code: "KeyF", metaKey: true });
|
||||
fireEvent.paste(tree, {
|
||||
clipboardData: { getData: () => "Read" },
|
||||
} as unknown as ClipboardEventInit);
|
||||
expect(within(tree.parentElement!).getByRole("status")).toHaveTextContent("Read");
|
||||
// The file Paste never ran: give a wrong one the time to land, then check the project.
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toEqual([]);
|
||||
// Closed, ⌘V is the view's file Paste again.
|
||||
fireEvent.keyDown(tree, { key: "Escape", code: "Escape" });
|
||||
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
|
||||
await waitFor(() =>
|
||||
expect([...fs.nodes.keys()].some((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toBe(true),
|
||||
);
|
||||
} finally {
|
||||
setOsClipboardForTests(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("clears cut dimming and disables Paste on focus after the OS clipboard becomes text", async () => {
|
||||
dispatchViaKeymap();
|
||||
let files: string[] = [];
|
||||
@@ -257,21 +303,48 @@ describe("ProjectView", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens files on double click and previews on single click only when enabled", async () => {
|
||||
it("opens files on double click and previews on single click while the editor's preview tab is on", async () => {
|
||||
const { row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
const content = row("README.md").querySelector("[data-project-path]")!;
|
||||
fireEvent.click(content, { detail: 1 });
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
fireEvent.doubleClick(row("README.md"));
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
|
||||
act(() => setViewOption("previewTab", true));
|
||||
// Settings › Editor › General › Editor Tabs › Enable preview tab is on by default.
|
||||
fireEvent.click(content, { detail: 1 });
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
|
||||
openFile.mockClear();
|
||||
fireEvent.click(content, { detail: 3 });
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
act(() => setViewOption("previewTab", false));
|
||||
setPreviewTabSetting(false);
|
||||
fireEvent.click(content, { detail: 1 });
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
fireEvent.doubleClick(row("README.md"));
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
|
||||
});
|
||||
|
||||
it("toggles the editor's preview tab setting from the Behavior menu and its action", async () => {
|
||||
ipc.settingsSet.mockImplementation(async (_scope: string, _key: string, value: string) =>
|
||||
ok(previewTabSettings(JSON.parse(value) as boolean)),
|
||||
);
|
||||
const { result } = renderHook(() => useProjectHeaderMenu());
|
||||
type Item = Extract<MenuItem, { id?: string }>;
|
||||
const behavior = () => (result.current[0] as Item).submenu as Item[];
|
||||
const item = () => behavior().find((i) => i.id === "previewTab")!;
|
||||
expect(item().checked).toBe(true);
|
||||
act(() => item().run!());
|
||||
await waitFor(() => expect(item().checked).toBe(false));
|
||||
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.tabs.previewTab", "false");
|
||||
const action = getAction("project.option.previewTab")!;
|
||||
expect(action.toggled!()).toBe(false);
|
||||
act(() => void executeAction(action.id));
|
||||
await waitFor(() => expect(item().checked).toBe(true));
|
||||
});
|
||||
|
||||
it("drops the former view-only preview tab option from saved view options", () => {
|
||||
localStorage.setItem("openidea.projectTree.options", JSON.stringify({ previewTab: true, singleClickOpen: true }));
|
||||
vi.resetModules();
|
||||
return import("./store").then(({ useProjectTree: fresh }) => {
|
||||
expect(fresh.getState().options).not.toHaveProperty("previewTab");
|
||||
expect(fresh.getState().options.singleClickOpen).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("follows tab switches with Always Select Opened File, hiding Select Opened File", async () => {
|
||||
@@ -701,17 +774,17 @@ describe("Show Members", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("autoscrolls to source without handing files to another application", async () => {
|
||||
it.each([true, false])("autoscrolls to source with preview tabs set to %s", async (preview) => {
|
||||
const { rows, row } = setup();
|
||||
setPreviewTabSetting(preview);
|
||||
act(() => {
|
||||
setViewOption("autoscrollToSource", true);
|
||||
setViewOption("singleClickOpen", false);
|
||||
setViewOption("previewTab", false);
|
||||
});
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
fireEvent.mouseDown(row("README.md"));
|
||||
await waitFor(() =>
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", expect.objectContaining({ external: false })),
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview, focus: false, external: false }),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -724,14 +797,14 @@ describe("Show Members", () => {
|
||||
setViewOption("showMembers", true);
|
||||
setViewOption("autoscrollToSource", false);
|
||||
setViewOption("singleClickOpen", false);
|
||||
setViewOption("previewTab", false);
|
||||
useProject.setState({ settings: previewTabSettings(false) });
|
||||
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
|
||||
});
|
||||
await waitFor(() => expect(rows()).toContain("main"));
|
||||
const content = () => row("main").querySelector("[data-project-key]")!;
|
||||
fireEvent.click(content(), { detail: 1 });
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
act(() => setViewOption("previewTab", true));
|
||||
setPreviewTabSetting(true);
|
||||
fireEvent.click(content(), { detail: 1 });
|
||||
expect(openFile).toHaveBeenLastCalledWith(
|
||||
APP,
|
||||
|
||||
@@ -91,6 +91,7 @@ import {
|
||||
explainHiddenPath,
|
||||
loadDir,
|
||||
loadOutline,
|
||||
previewTabEnabled,
|
||||
revealPath,
|
||||
selectModel,
|
||||
setDropTarget,
|
||||
@@ -584,13 +585,10 @@ export function ProjectView() {
|
||||
setSelection(next, lead?.key ?? null);
|
||||
const { options: o } = useProjectTree.getState();
|
||||
if (revealing.current || !o.autoscrollToSource || !lead || lead.dir || lead.placeholder || next.size !== 1) return;
|
||||
const opts = { preview: previewTabEnabled(), focus: false, external: false };
|
||||
if (lead.member) {
|
||||
void revealRange(
|
||||
lead.path,
|
||||
{ start: lead.member.selection_range.start },
|
||||
{ preview: o.previewTab, focus: false, external: false },
|
||||
);
|
||||
} else void openFile(lead.path, { preview: o.previewTab, focus: false, external: false });
|
||||
void revealRange(lead.path, { start: lead.member.selection_range.start }, opts);
|
||||
} else void openFile(lead.path, opts);
|
||||
}, []);
|
||||
|
||||
const onActivate = useCallback((node: ProjectNode) => {
|
||||
@@ -633,7 +631,7 @@ export function ProjectView() {
|
||||
if (o.singleClickExpand) toggleExpanded(node);
|
||||
return;
|
||||
}
|
||||
if (!o.singleClickOpen && !o.previewTab) return;
|
||||
if (!o.singleClickOpen && !previewTabEnabled()) return;
|
||||
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
|
||||
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
|
||||
else void openFile(node.path, opts);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fil
|
||||
import { dirname, useProject } from "@/platform/project";
|
||||
import { showContextMenu, type MenuItem } from "@/ui";
|
||||
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
|
||||
import { OPTION_LABELS, SORT_LABELS } from "./HeaderActions";
|
||||
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
|
||||
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
|
||||
import { openNewPopup } from "./newPopupModel";
|
||||
import type { ProjectNode } from "./model";
|
||||
@@ -191,8 +191,8 @@ export function registerProjectActions(): () => void {
|
||||
category: "View",
|
||||
// IDEA's former name of Always Select Opened File.
|
||||
keywords: ["project", "tree", "toggle", ...(key === "autoscrollFromSource" ? ["autoscroll from source"] : [])],
|
||||
toggled: () => useProjectTree.getState().options[key],
|
||||
run: () => setViewOption(key, !useProjectTree.getState().options[key]),
|
||||
toggled: () => isToggled(key),
|
||||
run: () => flipToggle(key),
|
||||
}));
|
||||
|
||||
const modes: Action[] = VIEW_MODES.map(([mode, label]) => ({
|
||||
|
||||
@@ -145,6 +145,22 @@ describe("project view context menu", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists contributed links in Copy Path/Reference… of library files too", () => {
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
|
||||
}),
|
||||
);
|
||||
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"-",
|
||||
"Link /root/.m2/lib.jar",
|
||||
]);
|
||||
});
|
||||
|
||||
it("groups clipboard, search, file changes, formatting and history actions for a file", () => {
|
||||
const items = contextMenuItems([node(`${ROOT}/src/a.py`)]);
|
||||
expect(labels(items)).toEqual([
|
||||
|
||||
@@ -512,6 +512,8 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
run: () => void copyPaths("absolute", nodes),
|
||||
},
|
||||
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", menuGroupContext(nodes)),
|
||||
],
|
||||
},
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -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))),
|
||||
|
||||
@@ -13,6 +13,8 @@ import { libraryEntryPaths } from "@/platform/virtualDocs";
|
||||
import { isIgnoredName } from "@/platform/ignoredNames";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import {
|
||||
DEFAULT_TREE_OPTIONS,
|
||||
@@ -57,8 +59,6 @@ export interface ViewOptions extends TreeOptions {
|
||||
singleClickOpen: boolean;
|
||||
/** Single click on a folder row expands / collapses it. */
|
||||
singleClickExpand: boolean;
|
||||
/** Single click shows files in the preview tab (IDEA's "Enable Preview Tab"). */
|
||||
previewTab: boolean;
|
||||
/** Show a file's declarations as expandable rows below it. */
|
||||
showMembers: boolean;
|
||||
/** Show the location of each project root beside its name. */
|
||||
@@ -73,8 +73,6 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
|
||||
autoscrollToSource: false,
|
||||
singleClickOpen: false,
|
||||
singleClickExpand: false,
|
||||
// IDEA's "Enable Preview Tab" is off by default.
|
||||
previewTab: false,
|
||||
showMembers: false,
|
||||
showRootPaths: true,
|
||||
horizontalScroll: true,
|
||||
@@ -82,6 +80,8 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
|
||||
|
||||
function storedOptions(): ViewOptions {
|
||||
const options = { ...DEFAULT_VIEW_OPTIONS, ...readJson<Partial<ViewOptions>>(OPTIONS_KEY) };
|
||||
// Former view-only switch, now the editor's preview tab setting (`previewTabEnabled`).
|
||||
delete (options as { previewTab?: unknown }).previewTab;
|
||||
if (!["name", "type", "modified"].includes(options.sortBy)) options.sortBy = "name";
|
||||
return options;
|
||||
}
|
||||
@@ -502,6 +502,22 @@ export function setViewOption<K extends keyof ViewOptions>(key: K, value: ViewOp
|
||||
writeJson(OPTIONS_KEY, options);
|
||||
}
|
||||
|
||||
/** Single click shows files in the preview tab: IDEA's "Enable Preview Tab" is the editor's own setting. */
|
||||
export const previewTabEnabled = () => editorPrefs().tabs.previewTab;
|
||||
|
||||
export async function setPreviewTabEnabled(on: boolean): Promise<void> {
|
||||
try {
|
||||
const settings = await call(commands.settingsSet("global", "editor.tabs.previewTab", JSON.stringify(on)));
|
||||
useProject.setState({ settings });
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot change the setting",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Loading
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun";
|
||||
import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers";
|
||||
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems, projectContext } from "./contextRun";
|
||||
import { OPTIMISTIC, produceContext, produceContextChoices, type ToolEnv } from "./producers";
|
||||
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
|
||||
import { useRun } from "./store";
|
||||
import type { RunTarget } from "./targets";
|
||||
@@ -115,6 +115,53 @@ describe("run context menu group", () => {
|
||||
expect(contextMenuItems("projectView", { paths: [`${ROOT}/src/components`], dirs: [true] })).toEqual([]);
|
||||
});
|
||||
|
||||
it("routes an attached Spring Boot main and its tests through the member's Maven build", () => {
|
||||
const member = "/work/spring";
|
||||
const project = useProject.getState().project!;
|
||||
useProject.setState({ project: { ...project, workspace: { version: 1, name: "app", projects: [ROOT, member] } } });
|
||||
const maven: RunConfig = { ...npmTest, kind: "maven", command: "mvn", args: ["test"], debugAdapter: null };
|
||||
useRun.setState({
|
||||
configs: [
|
||||
{ ...maven, id: "maven:test" },
|
||||
{ ...maven, id: "member:test", cwd: member },
|
||||
],
|
||||
});
|
||||
const content = [
|
||||
"package demo;",
|
||||
"import org.springframework.boot.SpringApplication;",
|
||||
"import org.springframework.boot.autoconfigure.SpringBootApplication;",
|
||||
"@SpringBootApplication",
|
||||
"public class App {",
|
||||
" public static void main(String[] args) { SpringApplication.run(App.class, args); }",
|
||||
"}",
|
||||
].join("\n");
|
||||
const main = { ...projectContext(), path: `${member}/src/main/java/demo/App.java`, content, line: 5 };
|
||||
expect(produceContext(main, OPTIMISTIC)?.config).toMatchObject({
|
||||
kind: "spring-boot",
|
||||
module: member,
|
||||
args: ["-cp", "${classpath}", "demo.App"],
|
||||
});
|
||||
expect(
|
||||
produceContext(
|
||||
{
|
||||
...main,
|
||||
path: `${member}/src/test/java/demo/AppTest.java`,
|
||||
content: "package demo;\nclass AppTest {\n @Test\n void starts() {}\n}",
|
||||
line: 3,
|
||||
},
|
||||
OPTIMISTIC,
|
||||
)?.config,
|
||||
).toMatchObject({
|
||||
kind: "maven",
|
||||
cwd: member,
|
||||
args: ["test", "-Dtest=demo.AppTest#starts", "-Dsurefire.failIfNoSpecifiedTests=false"],
|
||||
});
|
||||
expect(produceContext({ ...main, path: `${ROOT}/src/main/java/demo/App.java` }, OPTIMISTIC)?.config).toMatchObject({
|
||||
kind: "spring-boot",
|
||||
module: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows nothing when no producer matches or for several paths", () => {
|
||||
expect(contextMenuItems("editor", { paths: [`${ROOT}/README.md`], text: "# hi", line: 0 })).toEqual([]);
|
||||
expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual(
|
||||
|
||||
@@ -50,15 +50,16 @@ async function ensureConfigs() {
|
||||
}
|
||||
|
||||
/** The focused editor's file, text and caret line. */
|
||||
/** Project folders outside its root: Project Structure content roots and Gradle modules (as of the last sync). */
|
||||
/** Attached projects, Project Structure content roots and external Gradle modules. */
|
||||
export function projectContentRoots(): string[] {
|
||||
const own = effectiveContentRoots(validateProjectStructure(useProject.getState().settings?.projectStructure));
|
||||
const { project, settings } = useProject.getState();
|
||||
const own = effectiveContentRoots(validateProjectStructure(settings?.projectStructure));
|
||||
// The build model keeps the folders of modules outside the project absolute.
|
||||
const gradle = (useBuildModel.getState().model?.gradle ?? [])
|
||||
.flatMap((g) => g.projects)
|
||||
.map((p) => p.dir)
|
||||
.filter((d) => isAbsolute(d));
|
||||
return [...new Set([...own, ...gradle])];
|
||||
return [...new Set([...(project?.workspace?.projects ?? []), ...own, ...gradle])];
|
||||
}
|
||||
|
||||
const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p);
|
||||
|
||||
@@ -68,6 +68,7 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
resetRuns();
|
||||
_resetI18nForTests();
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
|
||||
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
|
||||
@@ -142,6 +143,27 @@ it("finds the source module for an old saved configuration without a module", as
|
||||
);
|
||||
});
|
||||
|
||||
it.each([null, "/elsewhere"])("recovers an attached module from its indexed path with cwd %s", async (cwd) => {
|
||||
const root = "/p";
|
||||
const member = "/other/spring";
|
||||
const module = `${member}/web`;
|
||||
useProject.setState({
|
||||
project: { root, workspace: { version: 1, name: "demo", projects: [root, member] } } as never,
|
||||
});
|
||||
ipc.findFiles.mockResolvedValueOnce({
|
||||
status: "ok",
|
||||
data: [{ path: `${module}/src/main/java/a/Main.java`, relPath: "spring/web/src/main/java/a/Main.java" }],
|
||||
});
|
||||
const session = await startRun({ ...config, cwd });
|
||||
expect(session?.status).toBe("running");
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number));
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: cwd ?? module, module }),
|
||||
expect.anything(),
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath resolution (%j)", async (...classpath) => {
|
||||
const args = ["-Xmx256m", ...classpath, "a.Main", "--spring.profiles.active=dev"];
|
||||
const boot = { ...config, kind: "spring-boot", args };
|
||||
|
||||
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { useProjectViewRoots } from "@/workbench/contributions";
|
||||
import {
|
||||
chooserRows,
|
||||
@@ -102,9 +103,8 @@ describe("creating scratch files", () => {
|
||||
opened = [];
|
||||
carets = [];
|
||||
backend = {
|
||||
dataDir: async () => "/data/",
|
||||
scratchesDir: async () => "/data/scratches/",
|
||||
listNames: async (dir) => [...files].filter((f) => f.startsWith(dir + "/")).map((f) => f.slice(dir.length + 1)),
|
||||
createDir: async () => {},
|
||||
createFile: async (p, text) => {
|
||||
files.add(p);
|
||||
contents.set(p, text);
|
||||
@@ -177,14 +177,43 @@ describe("creating scratch files", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("scratches of a remote window", () => {
|
||||
afterEach(() => {
|
||||
useRemote.setState({ session: null });
|
||||
setScratchBackend(tauriScratchBackend);
|
||||
});
|
||||
|
||||
it("moves the Scratches root to the server's folder when the window attaches to it in place", async () => {
|
||||
const remote = () => useRemote.getState().session !== null;
|
||||
setScratchBackend({
|
||||
scratchesDir: async () => (remote() ? "/home/me/.openidea/data/scratches" : "C:/Users/me/AppData/scratches"),
|
||||
listNames: async () => [],
|
||||
createFile: async () => {},
|
||||
languages: async () => [],
|
||||
open: async () => {},
|
||||
});
|
||||
const root = () => useProjectViewRoots.getState().roots.get("scratches")?.path;
|
||||
const dispose = activate();
|
||||
try {
|
||||
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
|
||||
useRemote.setState({ session: { root: "/home/me/project" } as never });
|
||||
await vi.waitFor(() => expect(root()).toBe("/home/me/.openidea/data/scratches"));
|
||||
useRemote.setState({ session: null });
|
||||
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
expect(root()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleting scratch files", () => {
|
||||
afterEach(() => setScratchBackend(tauriScratchBackend));
|
||||
|
||||
it("reports deletions inside the scratches folder as file system changes", async () => {
|
||||
setScratchBackend({
|
||||
dataDir: async () => "/data",
|
||||
scratchesDir: async () => "/data/scratches",
|
||||
listNames: async () => [],
|
||||
createDir: async () => {},
|
||||
createFile: async () => {},
|
||||
languages: async () => [],
|
||||
open: async () => {},
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { onFileOperation } from "@/platform/fileOps";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { registerMenuGroup, registerOverlay, registerProjectViewRoot } from "@/workbench/contributions";
|
||||
import { ScratchChooserHost } from "./ScratchChooser";
|
||||
import { openChooser } from "./store";
|
||||
@@ -20,10 +21,15 @@ export function activate(): () => void {
|
||||
let disposed = false;
|
||||
let unregisterRoot = () => {};
|
||||
let dir: string | null = null;
|
||||
if (scratchesAvailable())
|
||||
let generation = 0;
|
||||
const registerRoot = () => {
|
||||
const current = ++generation;
|
||||
unregisterRoot();
|
||||
unregisterRoot = () => {};
|
||||
dir = null;
|
||||
void scratchesDir()
|
||||
.then((path) => {
|
||||
if (disposed) return;
|
||||
if (disposed || current !== generation) return;
|
||||
dir = path;
|
||||
unregisterRoot = registerProjectViewRoot({
|
||||
id: "scratches",
|
||||
@@ -35,7 +41,13 @@ export function activate(): () => void {
|
||||
});
|
||||
})
|
||||
.catch((e: unknown) => console.warn("scratch files: no scratches folder", e));
|
||||
};
|
||||
if (scratchesAvailable()) registerRoot();
|
||||
const disposers = [
|
||||
// Attaching to (or leaving) a remote server moves the scratches to that host.
|
||||
useRemote.subscribe((state, previous) => {
|
||||
if (state.session !== previous.session && scratchesAvailable()) registerRoot();
|
||||
}),
|
||||
// The file watcher covers the project only: deleted scratches close their editors like watched files.
|
||||
onFileOperation((op) => {
|
||||
const removed = dir && op.kind === "deleted" ? op.paths.filter((p) => p === dir || p.startsWith(`${dir}/`)) : [];
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
/**
|
||||
* Scratch files live in the app data dir (`<appData>/scratches`), not in the
|
||||
* project, like IDEA's config-dir scratches. Creating one picks the next free
|
||||
* `scratch[_n].<ext>` name and opens it as a normal document.
|
||||
* Scratch files live in the user data dir (`<data>/scratches`) of the host that runs the
|
||||
* window's file commands (the server in a remote window), not in the project, like IDEA's
|
||||
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
|
||||
* it as a normal document.
|
||||
*/
|
||||
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
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";
|
||||
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
|
||||
|
||||
export interface ScratchBackend {
|
||||
/** Absolute app data dir. */
|
||||
dataDir(): Promise<string>;
|
||||
/** Absolute scratches folder, created. */
|
||||
scratchesDir(): Promise<string>;
|
||||
listNames(dir: string): Promise<string[]>;
|
||||
createDir(dir: string): Promise<void>;
|
||||
createFile(path: string, text: string): Promise<void>;
|
||||
languages(): Promise<ScratchLanguage[]>;
|
||||
open(path: string, caret: { line: number; col: number } | null): Promise<void>;
|
||||
}
|
||||
|
||||
export const tauriScratchBackend: ScratchBackend = {
|
||||
dataDir: appDataDir,
|
||||
scratchesDir: hostScratchesDir,
|
||||
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
|
||||
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
|
||||
createFile: async (path, text) =>
|
||||
void (await call(
|
||||
text ? commands.fsCreateFileBytes(path, [...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 }) }),
|
||||
@@ -35,30 +35,13 @@ let backend: ScratchBackend = tauriScratchBackend;
|
||||
/** Tests swap the backend. */
|
||||
export function setScratchBackend(b: ScratchBackend) {
|
||||
backend = b;
|
||||
dirPromise = null;
|
||||
}
|
||||
|
||||
export const scratchBackend = () => backend;
|
||||
|
||||
let dirPromise: Promise<string> | null = null;
|
||||
|
||||
/** `<appData>/scratches`, created on first use. */
|
||||
export function scratchesDir(): Promise<string> {
|
||||
if (!dirPromise) {
|
||||
dirPromise = (async () => {
|
||||
const dir = `${(await backend.dataDir()).replace(/\/+$/, "")}/scratches`;
|
||||
try {
|
||||
await backend.createDir(dir);
|
||||
} catch (e) {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
}
|
||||
return dir;
|
||||
})();
|
||||
dirPromise.catch(() => {
|
||||
dirPromise = null;
|
||||
});
|
||||
}
|
||||
return dirPromise;
|
||||
/** The scratches folder, created if needed. */
|
||||
export async function scratchesDir(): Promise<string> {
|
||||
return (await backend.scratchesDir()).replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export const scratchesAvailable = () => isTauri() || backend !== tauriScratchBackend;
|
||||
|
||||
@@ -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 & 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 & 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 () => {
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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"] }],
|
||||
});
|
||||
|
||||
@@ -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,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={[
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView, runScopeHandlers } from "@codemirror/view";
|
||||
import { cursorCharRight, history, undo } from "@codemirror/commands";
|
||||
import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
|
||||
import { cursorCharRight, history, redo, standardKeymap, undo } from "@codemirror/commands";
|
||||
import { nextOccurrence, occurrenceSearch } from "@/editor/core/cm/editing";
|
||||
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
|
||||
import { completedSyntaxState } from "@/test/syntax";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
import {
|
||||
@@ -284,14 +285,55 @@ describe("surround with", () => {
|
||||
describe("template fields", () => {
|
||||
const selected = (v: EditorView) => v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to);
|
||||
|
||||
it("edits the Java fori index from a single caret and lets the initializer be edited separately", async () => {
|
||||
const doc = "class Main {\n void f() {\n fori\n }\n}";
|
||||
const v = await editor("java", doc, doc.indexOf("fori") + 4, [history(), keymap.of(standardKeymap)]);
|
||||
expect(tab(v)).toBe(true);
|
||||
expect(v.state.selection.ranges).toHaveLength(1);
|
||||
expect(selected(v)).toBe("i");
|
||||
expect(v.state.selection.main.from).toBe(v.state.doc.toString().indexOf("int i") + "int ".length);
|
||||
|
||||
const expanded = v.state.doc.toString();
|
||||
v.dispatch(v.state.replaceSelection("index"));
|
||||
const renamed = expanded.replace(/\bi\b/g, "index");
|
||||
expect(v.state.doc.toString()).toBe(renamed);
|
||||
expect(undo(v)).toBe(true);
|
||||
expect(v.state.doc.toString()).toBe(expanded);
|
||||
expect(redo(v)).toBe(true);
|
||||
expect(v.state.doc.toString()).toBe(renamed);
|
||||
|
||||
const afterZero = renamed.indexOf(" = 0") + " = 0".length;
|
||||
while (v.state.selection.main.head < afterZero) expect(press(v, "ArrowRight")).toBe(true);
|
||||
expect(v.state.selection.main.head).toBe(afterZero);
|
||||
expect(v.state.selection.ranges).toHaveLength(1);
|
||||
expect(press(v, "Backspace")).toBe(true);
|
||||
v.dispatch(v.state.replaceSelection("1"));
|
||||
expect(v.state.doc.toString()).toBe(renamed.replace(" = 0", " = 1"));
|
||||
});
|
||||
|
||||
it("keeps one index caret per Java fori expansion", async () => {
|
||||
const doc = "class Main {\n void f() {\n fori\n fori\n }\n}";
|
||||
const v = await editor("java", doc);
|
||||
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
|
||||
expect(tab(v)).toBe(true);
|
||||
expect(v.state.selection.ranges).toHaveLength(2);
|
||||
expect(v.state.selection.mainIndex).toBe(1);
|
||||
v.dispatch(v.state.replaceSelection("index"));
|
||||
expect(v.state.doc.toString().match(/\bindex\b/g)).toHaveLength(6);
|
||||
expect(press(v, "Enter")).toBe(true);
|
||||
expect(v.state.selection.ranges.every((range) => range.empty)).toBe(true);
|
||||
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
|
||||
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["index", "index"]);
|
||||
});
|
||||
|
||||
it("links fields and advances all carets through separately indented expansions", async () => {
|
||||
const doc = "function first() {\n fori\n}\nfunction second() {\n fori\n}";
|
||||
const v = await editor("typescript", doc, undefined, [history()]);
|
||||
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
|
||||
const before = v.state.selection;
|
||||
expect(tab(v)).toBe(true);
|
||||
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(Array(6).fill("i"));
|
||||
expect(v.state.selection.mainIndex).toBe(3);
|
||||
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["i", "i"]);
|
||||
expect(v.state.selection.mainIndex).toBe(1);
|
||||
expect(v.state.doc.line(3).text).toBe(" ");
|
||||
expect(v.state.doc.line(8).text).toBe(" ");
|
||||
|
||||
@@ -301,7 +343,7 @@ describe("template fields", () => {
|
||||
expect(v.state.selection.ranges).toHaveLength(2);
|
||||
expect(v.state.selection.ranges.every((r) => v.state.sliceDoc(r.head, r.head + 7) === ".length")).toBe(true);
|
||||
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
|
||||
expect(v.state.selection.ranges).toHaveLength(6);
|
||||
expect(v.state.selection.ranges).toHaveLength(2);
|
||||
expect(tab(v)).toBe(true);
|
||||
expect(tab(v)).toBe(true);
|
||||
expect(v.state.selection.ranges.map((r) => r.head)).toEqual([v.state.doc.line(3).to, v.state.doc.line(8).to]);
|
||||
@@ -365,15 +407,36 @@ describe("template fields", () => {
|
||||
await tick();
|
||||
expect(press(v, "Escape")).toBe(true);
|
||||
expect(v.state.selection.main.empty).toBe(true);
|
||||
expect(hasNextSnippetField(v.state)).toBe(true);
|
||||
expect(hasLinkedSnippetField(v.state, 1)).toBe(true);
|
||||
expect(press(v, "Escape")).toBe(true);
|
||||
expect(hasNextSnippetField(v.state)).toBe(false);
|
||||
expect(hasLinkedSnippetField(v.state, 1)).toBe(false);
|
||||
// Outside a template Enter and Esc are left to the editor.
|
||||
expect(press(v, "Escape")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("⌘J Insert Live Template", () => {
|
||||
it.each([
|
||||
{ label: "sout", insert: "System.out.println();" },
|
||||
{ label: "fori", insert: "for (int i = 0; i < ; i++) {" },
|
||||
])("replaces a backward selection when picking $label", async ({ label, insert }) => {
|
||||
const text = "class Main {\n void f() {\n payload\n leftover\n return;\n }\n}";
|
||||
const from = text.indexOf("payload");
|
||||
const to = text.indexOf("leftover") + "leftover".length;
|
||||
const v = await editor("java", text, from, [autocompletion()]);
|
||||
v.dispatch({ selection: { anchor: to, head: from } });
|
||||
insertLiveTemplate(v);
|
||||
const result = await templateCompletionSource(new CompletionContext(v.state, from, true));
|
||||
const option = result?.options.find((candidate) => candidate.label === label);
|
||||
if (typeof option?.apply !== "function") throw new Error("Expected a live template completion");
|
||||
option.apply(v, option, result!.from, from);
|
||||
|
||||
expect(v.state.doc.line(3).text.trim()).toBe(insert);
|
||||
expect(v.state.doc.toString()).not.toMatch(/payload|leftover/);
|
||||
expect(v.state.doc.toString()).toContain("return;");
|
||||
expect(v.state.selection.ranges).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("opens a lookup restricted to live templates and ends with it", async () => {
|
||||
const v = await editor("typescript", "function f() {\n ", undefined, [autocompletion()]);
|
||||
const exclusive = () =>
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -4,13 +4,11 @@
|
||||
* application / field navigation.
|
||||
*/
|
||||
import {
|
||||
clearSnippet,
|
||||
closeCompletion,
|
||||
completionStatus,
|
||||
nextSnippetField,
|
||||
pickedCompletion,
|
||||
prevSnippetField,
|
||||
snippet,
|
||||
snippetKeymap,
|
||||
startCompletion,
|
||||
type Completion,
|
||||
@@ -18,16 +16,7 @@ import {
|
||||
type CompletionResult,
|
||||
type CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import {
|
||||
EditorSelection,
|
||||
EditorState,
|
||||
Facet,
|
||||
Prec,
|
||||
StateEffect,
|
||||
StateField,
|
||||
type Extension,
|
||||
type Transaction,
|
||||
} from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, Facet, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { EditorView, keymap, type Command } from "@codemirror/view";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -50,14 +39,7 @@ import { showChooser, type ChooserItem } from "./popup/store";
|
||||
import { expandEmmetAtCaret } from "./emmet/editor";
|
||||
import { hasEmmet, loadEmmet } from "./emmet/model";
|
||||
import { readClipboardPlainText } from "@/platform/clipboard";
|
||||
import {
|
||||
applyMulticaretSnippet,
|
||||
clearMulticaretSnippet,
|
||||
hasMulticaretSnippet,
|
||||
moveMulticaretField,
|
||||
multicaretFieldMoved,
|
||||
multicaretSnippetExtension,
|
||||
} from "./multicaretSnippet";
|
||||
import { applySnippet, escapeSnippet, nextLiveSnippetField, snippetFieldMoved } from "@/editor/core/cm/linkedSnippet";
|
||||
|
||||
export interface TemplateDocInfo {
|
||||
path: string;
|
||||
@@ -149,23 +131,19 @@ async function expandAtSites(
|
||||
const clipboard = needsClipboard(t) ? await readClipboard() : "";
|
||||
if (view.state.doc !== state.doc || !view.state.selection.eq(state.selection) || view.state.readOnly) return;
|
||||
let expansions = sites.map(({ from }) => expansionAt(state, t, from, clipboard, opts));
|
||||
if (sites.length === 1) {
|
||||
const { from, to } = sites[0]!;
|
||||
clearMulticaretSnippet(view);
|
||||
snippet(expansions[0]!.snippet)(view, null, from, to);
|
||||
} else {
|
||||
if (sites.length > 1) {
|
||||
// A variable stays editable everywhere if any caret needs it as a tab stop.
|
||||
const editable = new Set(expansions.flatMap((e) => e.fields));
|
||||
if (expansions.some((e) => e.fields.length !== editable.size)) {
|
||||
const variables = t.variables?.map((v) => (editable.has(v.name) ? { ...v, skipIfDefined: false } : v));
|
||||
expansions = sites.map(({ from }) => expansionAt(state, { ...t, variables }, from, clipboard, opts));
|
||||
}
|
||||
applyMulticaretSnippet(
|
||||
view,
|
||||
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
|
||||
);
|
||||
}
|
||||
const exp = expansions[0]!;
|
||||
applySnippet(
|
||||
view,
|
||||
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
|
||||
);
|
||||
if (view.state.field(fieldCompletion, false) !== undefined)
|
||||
view.dispatch({ effects: setFieldCompletion.of(exp.completing) });
|
||||
if (exp.completeFirst) setTimeout(() => startCompletion(view), 0);
|
||||
@@ -189,63 +167,29 @@ const fieldCompletion = StateField.define<readonly boolean[]>({
|
||||
update: (value, tr) => tr.effects.find((e) => e.is(setFieldCompletion))?.value ?? value,
|
||||
});
|
||||
|
||||
/**
|
||||
* The snippet field a transaction moves to. CodeMirror doesn't expose it; its
|
||||
* snippet-state effect carries the active snippet (`{ ranges, active }`).
|
||||
*/
|
||||
function movedToField(tr: Transaction): number | null {
|
||||
for (const e of tr.effects) {
|
||||
const v = e.value as { active?: unknown; ranges?: unknown } | null;
|
||||
if (v && typeof v === "object" && typeof v.active === "number" && Array.isArray(v.ranges)) return v.active;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Moving to a field that asks for completion opens it, as IDEA does. */
|
||||
const completeOnFieldMove = EditorView.updateListener.of((u) => {
|
||||
if (u.docChanged) return;
|
||||
const flags = u.state.field(fieldCompletion);
|
||||
const field = u.transactions.map((tr) => multicaretFieldMoved(tr) ?? movedToField(tr)).findLast((i) => i !== null);
|
||||
const field = u.transactions.map((tr) => snippetFieldMoved(tr)).findLast((i) => i !== undefined);
|
||||
if (field == null || !flags[field]) return;
|
||||
setTimeout(() => {
|
||||
if (u.view.state.selection === u.state.selection) startCompletion(u.view);
|
||||
}, 0);
|
||||
});
|
||||
|
||||
/**
|
||||
* Esc in a template, as in IDEA: first drops the selection (closing the lookup)
|
||||
* or closes the lookup; only with neither does it leave the template.
|
||||
*/
|
||||
export const escapeTemplate: Command = (view) => {
|
||||
const sel = view.state.selection;
|
||||
if (sel.ranges.some((r) => !r.empty)) {
|
||||
closeCompletion(view);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
|
||||
sel.mainIndex,
|
||||
),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (completionStatus(view.state) === "active") return closeCompletion(view);
|
||||
return clearMulticaretSnippet(view) || clearSnippet(view);
|
||||
};
|
||||
|
||||
const unlessLookup =
|
||||
(cmd: Command): Command =>
|
||||
(view) =>
|
||||
completionStatus(view.state) === "active" ? false : cmd(view);
|
||||
|
||||
const nextMulticaretField = moveMulticaretField(1);
|
||||
|
||||
/**
|
||||
* Whether the active snippet came from a live template or Emmet, where Enter moves to the
|
||||
* next field. A completion's snippet (an LSP `<tag>$1</tag>$0`) keeps Enter for new lines.
|
||||
*/
|
||||
const templateSnippet = StateField.define<boolean>({
|
||||
create: () => false,
|
||||
update: (value, tr) => (movedToField(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
|
||||
update: (value, tr) => (snippetFieldMoved(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
|
||||
});
|
||||
|
||||
/** Tab moves to the next field; Enter too in templates (the lookup's while it is open). */
|
||||
@@ -255,7 +199,7 @@ const templateFieldKeys = snippetKeymap.of([
|
||||
key: "Enter",
|
||||
run: unlessLookup((view) => view.state.field(templateSnippet, false) === true && nextSnippetField(view)),
|
||||
},
|
||||
{ key: "Escape", run: escapeTemplate },
|
||||
{ key: "Escape", run: escapeSnippet },
|
||||
]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -672,7 +616,6 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
|
||||
fieldCompletion,
|
||||
templateSnippet,
|
||||
completeOnFieldMove,
|
||||
multicaretSnippetExtension,
|
||||
templateFieldKeys,
|
||||
templateLookup,
|
||||
endTemplateLookup,
|
||||
@@ -685,14 +628,11 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
|
||||
]),
|
||||
Prec.high(
|
||||
keymap.of([
|
||||
{ key: "Enter", run: unlessLookup(nextMulticaretField) },
|
||||
{ key: "Escape", run: (view) => hasMulticaretSnippet(view.state) && escapeTemplate(view) },
|
||||
{ key: "Enter", run: unlessLookup(nextLiveSnippetField) },
|
||||
{
|
||||
key: "Tab",
|
||||
shift: moveMulticaretField(-1),
|
||||
run: (view) => {
|
||||
if (view.state.readOnly || completionStatus(view.state) === "active") return false;
|
||||
if (nextMulticaretField(view)) return true;
|
||||
if (expandPostfixAtCaret(view)) return true;
|
||||
if (useLiveTemplateOptions.getState().expandWithTab && expandLiveTemplateAtCaret(view)) return true;
|
||||
return expandEmmetAtCaret(view, ctx.language);
|
||||
|
||||
@@ -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?.();
|
||||
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача