mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 19:49:35 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2aa46f21bf | ||
|
|
7310d0ab01 |
No files matched your search
@@ -82,23 +82,11 @@ pub fn load_linked(
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
gradle_settings: &ide_core::settings::GradleSettings,
|
||||
) -> BuildModel {
|
||||
load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None)
|
||||
}
|
||||
|
||||
/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles.
|
||||
pub fn load_linked_with_jdk(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
gradle_settings: &ide_core::settings::GradleSettings,
|
||||
maven_jdk_version: Option<u32>,
|
||||
) -> BuildModel {
|
||||
let maven = maven::has_projects(root, settings).then(|| {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
let repo = maven_repo.or_else(maven::default_local_repo);
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
|
||||
+67
-888
File diff suppressed because it is too large.
Load diff
@@ -92,12 +92,6 @@ pub enum IdeEvent {
|
||||
/// Text version when this transition occurred, including when it was saved.
|
||||
version: u32,
|
||||
},
|
||||
/// An open document's file changed on disk while the buffer had unsaved changes. The buffer
|
||||
/// keeps them (autosave leaves the file alone); the UI offers to load the disk version.
|
||||
DocDiskConflict {
|
||||
doc: DocId,
|
||||
path: String,
|
||||
},
|
||||
/// A complete workspace edit can be undone as one operation.
|
||||
WorkspaceEditApplied {
|
||||
id: u32,
|
||||
|
||||
@@ -8,79 +8,30 @@ use crate::{Host, Project};
|
||||
use ide_command::command;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::maven::PomGoto;
|
||||
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
|
||||
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
|
||||
use ide_build::pom_edit::{ArtifactKey, Exclusion};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn join_err(e: tokio::task::JoinError) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// POM gutters in several editors refresh together. A very short cache lets those
|
||||
/// requests share one reactor scan without serving a stale module list after edits settle.
|
||||
const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250);
|
||||
type MavenModuleCache = HashMap<String, (Instant, Vec<ide_build::maven::ModulePom>)>;
|
||||
static MAVEN_MODULES: OnceLock<Mutex<MavenModuleCache>> = OnceLock::new();
|
||||
|
||||
fn maven_modules(
|
||||
project: &Project,
|
||||
settings: &Settings,
|
||||
options: &PomNavigationOptions,
|
||||
) -> Vec<ide_build::maven::ModulePom> {
|
||||
let key = format!(
|
||||
"{}\0{:?}\0{:?}\0{:?}\0{:?}",
|
||||
project.root.display(),
|
||||
project.build_cache_dir(),
|
||||
settings.languages.java.maven.linked_projects,
|
||||
options.profiles,
|
||||
options.jdk_version
|
||||
);
|
||||
let cache = MAVEN_MODULES.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Some((_at, modules)) = cache.lock().ok().and_then(|mut cache| {
|
||||
let fresh = cache.get(&key).filter(|(at, _)| at.elapsed() < MAVEN_MODULE_CACHE_TTL).cloned();
|
||||
if fresh.is_none() {
|
||||
cache.remove(&key);
|
||||
}
|
||||
fresh
|
||||
}) {
|
||||
return modules;
|
||||
}
|
||||
let model = load(&project.root, &project.build_cache_dir(), settings).maven.unwrap_or_default();
|
||||
let modules = model
|
||||
.projects
|
||||
.into_iter()
|
||||
.map(|p| ide_build::maven::ModulePom {
|
||||
group_id: p.group_id,
|
||||
artifact_id: p.artifact_id,
|
||||
version: p.version,
|
||||
pom: project.root.join(&p.pom),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if let Ok(mut cache) = cache.lock() {
|
||||
cache.insert(key, (Instant::now(), modules.clone()));
|
||||
}
|
||||
modules
|
||||
}
|
||||
|
||||
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
|
||||
/// the Maven home and options from Settings › Maven.
|
||||
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
let jdk = ide_sdk::apply::project_jdk(root, settings);
|
||||
let mut model = ide_build::load_linked_with_jdk(
|
||||
let mut model = ide_build::load_linked(
|
||||
root,
|
||||
cache,
|
||||
ide_sdk::apply::maven_local_repository(root, settings),
|
||||
&settings.languages.java.maven,
|
||||
&settings.languages.java.gradle,
|
||||
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major),
|
||||
);
|
||||
let jdk = ide_sdk::apply::project_jdk(root, settings);
|
||||
if let Some(m) = &mut model.maven {
|
||||
let mvn = ide_sdk::apply::maven_command(root, settings);
|
||||
let options = ide_sdk::apply::maven_options(root, settings);
|
||||
@@ -126,23 +77,6 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
model
|
||||
}
|
||||
|
||||
/// POM navigation follows the same profile choices as the last Maven sync and
|
||||
/// resolves JDK-activated profiles with the project's selected Maven runtime.
|
||||
fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions {
|
||||
let mut profiles = settings.languages.java.maven.profiles(&[]);
|
||||
for profile in ide_build::maven_profiles(&project.build_cache_dir()) {
|
||||
if !profiles.contains(&profile) {
|
||||
profiles.push(profile);
|
||||
}
|
||||
}
|
||||
PomNavigationOptions {
|
||||
local_repo: ide_sdk::apply::maven_local_repository(&project.root, settings)
|
||||
.or_else(ide_build::maven::default_local_repo),
|
||||
profiles,
|
||||
jdk_version: ide_sdk::apply::maven_jdk(&project.root, settings, None).map(|jdk| jdk.major),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build and Run use the same selected toolchain and module-local runtime discovery.
|
||||
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan {
|
||||
let kind = match plan.system {
|
||||
@@ -613,9 +547,8 @@ pub async fn maven_dependency_declaration(
|
||||
}
|
||||
|
||||
/// The go-to-declaration target at `pos` of a Maven POM: the definition of the
|
||||
/// `${property}` at the caret, the parent POM, or the dependency / plugin's own POM
|
||||
/// (a project module first, then the local repository). A dependency without a
|
||||
/// resolvable artifact POM falls back to its management entry.
|
||||
/// `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
|
||||
/// entry providing the dependency's / plugin's version, along the parent chain.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: Pos) -> IdeResult<Option<PomGoto>> {
|
||||
// `pom` is project-relative, or absolute for a parent POM opened from the local repository.
|
||||
@@ -628,55 +561,26 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
|
||||
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
|
||||
let text = project.text_of(&path)?;
|
||||
let settings = project.settings.effective();
|
||||
let options = pom_navigation_options(&project, &settings);
|
||||
let module_options = options.clone();
|
||||
let modules = || maven_modules(&project, &settings, &module_options);
|
||||
Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules))
|
||||
let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings)
|
||||
.or_else(ide_build::maven::default_local_repo);
|
||||
let modules = || {
|
||||
let model = load(&project.root, &project.build_cache_dir(), &settings).maven.unwrap_or_default();
|
||||
model
|
||||
.projects
|
||||
.into_iter()
|
||||
.map(|p| ide_build::maven::ModulePom {
|
||||
group_id: p.group_id,
|
||||
artifact_id: p.artifact_id,
|
||||
pom: project.root.join(&p.pom),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok(ide_build::maven::goto_declaration_in(&text, &path, pos, repo, modules))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// Gutter targets of the unversioned dependencies and plugins in a Maven POM:
|
||||
/// the management declarations that actually supply their versions, including
|
||||
/// parent POMs and imported BOMs. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn maven_managed_declarations(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
pom: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<PomManagedDeclaration>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let given = Path::new(&pom);
|
||||
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
|
||||
let text = project.text_of(&path)?;
|
||||
let settings = project.settings.effective();
|
||||
let options = pom_navigation_options(&project, &settings);
|
||||
let cancelled = cancel.clone();
|
||||
let module_options = options.clone();
|
||||
let modules = || {
|
||||
if cancelled.is_cancelled() {
|
||||
return Vec::new();
|
||||
}
|
||||
maven_modules(&project, &settings, &module_options)
|
||||
};
|
||||
let declarations = ide_build::maven::managed_declarations_with(&text, &path, options, modules);
|
||||
if cancel.is_cancelled() { Err(IdeError::cancelled()) } else { Ok(declarations) }
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(error) => Err(join_err(error)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How long completion waits for Maven Central before answering from the local repository.
|
||||
const CENTRAL_WAIT: std::time::Duration = std::time::Duration::from_secs(1);
|
||||
|
||||
@@ -1429,5 +1333,4 @@ ide_command::domain!(
|
||||
maven_dependency_declaration,
|
||||
maven_exclude_dependency,
|
||||
maven_goto_declaration,
|
||||
maven_managed_declarations,
|
||||
);
|
||||
@@ -70,13 +70,6 @@ pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
/// Load Changes from Disk: discards the buffer's unsaved changes and reads its file again.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.discard_and_reload(doc)).await
|
||||
}
|
||||
|
||||
/// An automatic save: `false` (nothing written) when the file changed on disk after the
|
||||
/// buffer was edited, which only an explicit save overwrites.
|
||||
#[command(trust = always)]
|
||||
@@ -127,7 +120,6 @@ ide_command::domain!(
|
||||
doc_edit,
|
||||
doc_open,
|
||||
doc_open_untitled,
|
||||
doc_reload_from_disk,
|
||||
doc_save,
|
||||
doc_autosave,
|
||||
doc_save_all,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
use crate::{HostConfig, Project};
|
||||
use ide_core::{IdeEvent, TextChange};
|
||||
use ide_core::{IdeEvent, TextChange, event::NotifyLevel};
|
||||
use parking_lot::Mutex;
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
@@ -57,9 +57,7 @@ impl Fixture {
|
||||
self.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
matches!(e, IdeEvent::DocPatched { .. } | IdeEvent::DocDirty { .. } | IdeEvent::DocDiskConflict { .. })
|
||||
})
|
||||
.filter(|e| matches!(e, IdeEvent::DocPatched { .. } | IdeEvent::DocDirty { .. } | IdeEvent::Notify { .. }))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
@@ -112,7 +110,7 @@ async fn dirty_document_keeps_edits_and_warns_once() {
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(loaded.text, "local original\n");
|
||||
assert!(loaded.dirty);
|
||||
assert!(matches!(f.document_events().as_slice(), [IdeEvent::DocDiskConflict { .. }]));
|
||||
assert!(matches!(f.document_events().as_slice(), [IdeEvent::Notify { level: NotifyLevel::Warning, .. }]));
|
||||
f.events.lock().clear();
|
||||
f.sync().await;
|
||||
assert!(f.document_events().is_empty());
|
||||
|
||||
@@ -191,7 +191,6 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
|
||||
| IdeEvent::ExcludedDirsChanged { .. }
|
||||
| IdeEvent::DocPatched { .. }
|
||||
| IdeEvent::DocDirty { .. }
|
||||
| IdeEvent::DocDiskConflict { .. }
|
||||
| IdeEvent::WorkspaceEditApplied { .. }
|
||||
| IdeEvent::DocLanguage { .. }
|
||||
| IdeEvent::Diagnostics { .. }
|
||||
|
||||
@@ -1112,12 +1112,8 @@ fn module_count(root: &Path) -> usize {
|
||||
/// named after its `artifactId` (usually its folder), a Gradle one `<project>.<path>.<source set>`.
|
||||
fn module_dir(root: &Path, name: &str) -> Option<String> {
|
||||
let folder = |dir: &Path| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
// A Maven module is named after its artifactId, so that match wins over a folder of the same
|
||||
// name anywhere above it (a checkout folder named like a child module's artifactId).
|
||||
if let Some(dir) = find_module(root, &|dir: &Path| pom_artifact(dir).is_some_and(|a| a == name)) {
|
||||
return Some(dir);
|
||||
}
|
||||
if let Some(dir) = find_module(root, &|dir: &Path| folder(dir) == name) {
|
||||
let exact = |dir: &Path| folder(dir) == name || pom_artifact(dir).is_some_and(|a| a == name);
|
||||
if let Some(dir) = find_module(root, &exact) {
|
||||
return Some(dir);
|
||||
}
|
||||
let gradle = name.strip_suffix(".main").or_else(|| name.strip_suffix(".test")).unwrap_or(name);
|
||||
|
||||
@@ -860,38 +860,6 @@ fn java_applications_and_spring_boot_keep_their_module() {
|
||||
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
|
||||
}
|
||||
|
||||
/// A checkout folder named like a child module's artifactId: IDEA's module is the child.
|
||||
#[test]
|
||||
fn maven_module_artifact_wins_over_a_folder_of_the_same_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap().join("demo-service");
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
"<project><artifactId>demo-service-parent</artifactId><packaging>pom</packaging></project>",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app-web/pom.xml",
|
||||
"<project><parent><artifactId>demo-service-parent</artifactId></parent><artifactId>demo-service</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
".run/Demo.run.xml",
|
||||
&run_file(
|
||||
"Demo",
|
||||
r#"<configuration name="Demo" type="Application" factoryName="Application">
|
||||
<module name="demo-service" />
|
||||
<option name="MAIN_CLASS_NAME" value="com.example.Demo" />
|
||||
</configuration>"#,
|
||||
),
|
||||
);
|
||||
|
||||
let r = import_from(&root, &[]);
|
||||
|
||||
assert_eq!(get(&r, "Demo").extras.module.as_deref(), Some("app-web"));
|
||||
}
|
||||
|
||||
/// IDEA writes the working directory as a URL. On Windows `file://$PROJECT_DIR$`
|
||||
/// expands to `file://C:/project`, where the drive letter sits where the authority
|
||||
/// belongs; read as a path that is `C:project`, which resolves against the project
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::editorconfig::{EditorConfig, EditorConfigProps};
|
||||
use crate::file_defaults::FileDefaults;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
|
||||
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
|
||||
use parking_lot::{Mutex, ReentrantMutex, RwLock};
|
||||
@@ -1137,24 +1138,6 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
|
||||
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
|
||||
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
|
||||
self.with_doc(doc, |st| {
|
||||
if st.uri.is_some() || st.binary {
|
||||
return Err(IdeError::invalid("only a file's text can be reloaded from disk"));
|
||||
}
|
||||
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.disk_mtime = loaded.mtime_ms;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
st.disk_conflict = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
self.set_dirty(doc, st, false);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// The URI of a virtual document, or `None` for a file-backed one.
|
||||
pub fn virtual_uri(&self, doc: DocId) -> IdeResult<Option<String>> {
|
||||
self.with_doc(doc, |st| Ok(st.uri.clone()))
|
||||
@@ -1267,7 +1250,7 @@ impl Documents {
|
||||
}
|
||||
|
||||
/// Re-reads from disk after an external change. Clean documents reload
|
||||
/// silently; dirty ones are left alone and reported via `IdeEvent::DocDiskConflict`.
|
||||
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
|
||||
/// Changes matching our own last save are ignored.
|
||||
pub fn on_disk_changed(&self, paths: &[PathBuf]) {
|
||||
self.reload_from_disk(paths, false, false);
|
||||
@@ -1306,7 +1289,16 @@ impl Documents {
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
|
||||
let name = st.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
self.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: format!("{name} changed on disk"),
|
||||
body: Some(format!(
|
||||
"{} was modified externally but has unsaved changes in the editor. \
|
||||
Saving explicitly will overwrite the external changes; autosave leaves the file alone.",
|
||||
st.path.display()
|
||||
)),
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = if force_clean {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{ChangeSet, DocId, IdeEvent, LanguageId, Pos, Range, SharedSink, TextChange, TextEdit};
|
||||
use ide_text::{AppliedChange, LineEnding};
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -564,31 +565,15 @@ fn external_changes() {
|
||||
fs::write(&path, "something else\n").unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, "// alpha\nBETA\ngamma\n");
|
||||
let warnings = f
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path.to_string_lossy()))
|
||||
.count();
|
||||
let warnings =
|
||||
f.events.lock().iter().filter(|e| matches!(e, IdeEvent::Notify { level: NotifyLevel::Warning, .. })).count();
|
||||
assert_eq!(warnings, 1);
|
||||
// The same disk state is reported only once.
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let warnings = f
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path.to_string_lossy()))
|
||||
.count();
|
||||
let warnings =
|
||||
f.events.lock().iter().filter(|e| matches!(e, IdeEvent::Notify { level: NotifyLevel::Warning, .. })).count();
|
||||
assert_eq!(warnings, 1);
|
||||
|
||||
// Load Changes from Disk drops the buffer's changes; autosave writes again afterwards.
|
||||
f.docs.discard_and_reload(id).unwrap();
|
||||
let reloaded = f.docs.snapshot(id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.dirty), ("something else\n", false));
|
||||
f.docs.edit(id, reloaded.version, change(0, 0, "# ")).unwrap();
|
||||
assert!(f.docs.autosave(id).unwrap());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "# something else\n");
|
||||
|
||||
// Unknown paths are ignored.
|
||||
f.docs.on_disk_changed(&[f.root.join("other.txt")]);
|
||||
}
|
||||
|
||||
@@ -215,7 +215,6 @@ doc_open_untitled always project_host bin
|
||||
doc_open_virtual always project_host bindings async
|
||||
doc_outline always project_host bindings async
|
||||
doc_python_facts always project_host bindings async
|
||||
doc_reload_from_disk always project_host bindings async
|
||||
doc_save always project_host bindings async
|
||||
doc_save_all always project_host bindings async
|
||||
doc_save_as always project_host bindings async
|
||||
@@ -376,7 +375,6 @@ maven_dependency_completion trusted project_host bin
|
||||
maven_dependency_declaration trusted project_host bindings async
|
||||
maven_exclude_dependency trusted project_host bindings async
|
||||
maven_goto_declaration trusted project_host bindings async
|
||||
maven_managed_declarations trusted project_host bindings async
|
||||
mcp_agent_run_closed trusted project_host bindings sync
|
||||
mcp_background_projects always project_host bindings sync
|
||||
mcp_regenerate_token outside_restricted project_host bindings sync
|
||||
|
||||
+2
-26
@@ -533,8 +533,6 @@ export const commands = {
|
||||
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
|
||||
/** Python class facts for the inheritance inspections: tree-sitter, no language server. */
|
||||
docPythonFacts: (doc: DocId) => typedError<PythonFacts, IdeError>(__TAURI_INVOKE("doc_python_facts", { doc })),
|
||||
/** Load Changes from Disk: discards the buffer's unsaved changes and reads its file again. */
|
||||
docReloadFromDisk: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_reload_from_disk", { doc })),
|
||||
docSave: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_save", { doc })),
|
||||
docSaveAll: () => typedError<null, IdeError>(__TAURI_INVOKE("doc_save_all")),
|
||||
/**
|
||||
@@ -962,9 +960,8 @@ export const commands = {
|
||||
mavenExcludeDependency: (pom: string, dependency: ArtifactKey, exclusion: ArtifactKey) => typedError<Location, IdeError>(__TAURI_INVOKE("maven_exclude_dependency", { pom, dependency, exclusion })),
|
||||
/**
|
||||
* The go-to-declaration target at `pos` of a Maven POM: the definition of the
|
||||
* `${property}` at the caret, the parent POM, or the dependency / plugin's own POM
|
||||
* (a project module first, then the local repository). A dependency without a
|
||||
* resolvable artifact POM falls back to its management entry.
|
||||
* `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
|
||||
* entry providing the dependency's / plugin's version, along the parent chain.
|
||||
*/
|
||||
mavenGotoDeclaration: (pom: string, pos: Pos) => typedError<{
|
||||
/**
|
||||
@@ -978,12 +975,6 @@ export const commands = {
|
||||
/** The declaration as named for the user (`example.version`, `com.example:example-lib`). */
|
||||
label: string,
|
||||
} | null, IdeError>(__TAURI_INVOKE("maven_goto_declaration", { pom, pos })),
|
||||
/**
|
||||
* Gutter targets of the unversioned dependencies and plugins in a Maven POM:
|
||||
* the management declarations that actually supply their versions, including
|
||||
* parent POMs and imported BOMs. Cancel with `cancel_request(request)`.
|
||||
*/
|
||||
mavenManagedDeclarations: (pom: string, request: RequestId) => typedError<PomManagedDeclaration[], IdeError>(__TAURI_INVOKE("maven_managed_declarations", { pom, request })),
|
||||
/** The user closed the Run tool window tab of an agent command (`run_command`). */
|
||||
mcpAgentRunClosed: (name: string) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_agent_run_closed", { name })),
|
||||
/**
|
||||
@@ -7035,11 +7026,6 @@ workspaceEdit?: boolean } |
|
||||
{ type: "docDirty"; doc: DocId; dirty: boolean;
|
||||
/** Text version when this transition occurred, including when it was saved. */
|
||||
version: number } |
|
||||
/**
|
||||
* An open document's file changed on disk while the buffer had unsaved changes. The buffer
|
||||
* keeps them (autosave leaves the file alone); the UI offers to load the disk version.
|
||||
*/
|
||||
{ type: "docDiskConflict"; doc: DocId; path: string } |
|
||||
/** A complete workspace edit can be undone as one operation. */
|
||||
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
|
||||
/**
|
||||
@@ -9767,16 +9753,6 @@ export type PomGotoKind =
|
||||
/** The POM of the artifact itself: a project module's, else the local repository's. */
|
||||
"artifactPom";
|
||||
|
||||
/** A dependency or plugin whose version comes from a management declaration. */
|
||||
export type PomManagedDeclaration = {
|
||||
/** 0-based line of the `<dependency>` or `<plugin>` declaration. */
|
||||
line: number,
|
||||
/** The interpolated version the management entry provides, when it has one. */
|
||||
version: string | null,
|
||||
/** The management entry, possibly in a parent POM or an imported BOM. */
|
||||
target: PomGoto,
|
||||
};
|
||||
|
||||
/** A 0-based line / UTF-16 column position. */
|
||||
export type Pos = {
|
||||
line: number,
|
||||
|
||||
+1
-15
@@ -490,11 +490,7 @@ export type ContributedFormatter = (
|
||||
range: { from: number; to: number } | null,
|
||||
) => Array<{ from: number; to: number; insert: string }>;
|
||||
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
|
||||
export interface ContributedDefinition {
|
||||
(view: EditorView, pos: number): boolean;
|
||||
/** Cheap, side-effect-free eligibility for hover underline and navigation probing. */
|
||||
canHandle?(state: EditorState, pos: number): boolean;
|
||||
}
|
||||
export type ContributedDefinition = (view: EditorView, pos: number) => boolean;
|
||||
/** Hover and Quick Documentation: Markdown about the symbol at `pos`. */
|
||||
export type ContributedHover = (
|
||||
state: EditorState,
|
||||
@@ -505,16 +501,6 @@ export function contributedAt<T>(state: EditorState, key: string, pos: number):
|
||||
return state.languageDataAt<T>(key, pos)[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Every provider registered for a contributed language-data key at `pos`. A provider may
|
||||
* be present for the document but decline this particular position (the MyBatis SQL
|
||||
* provider on a Maven POM, for example), so callers that dispatch a request must not stop
|
||||
* at the first entry when it returns "not handled".
|
||||
*/
|
||||
export function contributedAtAll<T>(state: EditorState, key: string, pos: number): readonly T[] {
|
||||
return state.languageDataAt<T>(key, pos);
|
||||
}
|
||||
|
||||
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */
|
||||
export interface ContributedIntention {
|
||||
id: string;
|
||||
|
||||
@@ -77,10 +77,6 @@ export interface DocBackend {
|
||||
onDirty(handler: (e: DocDirtyEvent) => void): () => void;
|
||||
/** Files changed on disk (used to refresh nothing but closed-file state). */
|
||||
onFsChanged?(handler: (e: { removed: string[] }) => void): () => void;
|
||||
/** A file changed on disk while its buffer had unsaved changes, which the buffer kept. */
|
||||
onDiskConflict?(handler: (e: { doc: DocId; path: string }) => void): () => void;
|
||||
/** Load Changes from Disk: drops the buffer's unsaved changes and reads its file again. */
|
||||
reloadDiscarding?(doc: DocId): Promise<void>;
|
||||
/**
|
||||
* Every OpenIDEA window lost focus to another application. Also seen while focus is in a frame
|
||||
* (a plugin's web view), which hides the window's own `blur`.
|
||||
@@ -116,8 +112,6 @@ export const ipcBackend: DocBackend = {
|
||||
onPatched: (h) => onIdeEvent("docPatched", (e) => h(e)),
|
||||
onDirty: (h) => onIdeEvent("docDirty", (e) => h(e)),
|
||||
onFsChanged: (h) => onIdeEvent("fsChanged", (e) => h(e)),
|
||||
onDiskConflict: (h) => onIdeEvent("docDiskConflict", (e) => h(e)),
|
||||
reloadDiscarding: async (doc) => void (await call(commands.docReloadFromDisk(doc))),
|
||||
onApplicationDeactivated: (h) => {
|
||||
if (!isTauri()) return () => {};
|
||||
const listener = getCurrentWebviewWindow().listen("ide://application-deactivated", () => h());
|
||||
|
||||
@@ -171,40 +171,6 @@ describe("find in selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("plain-text queries", () => {
|
||||
it("match regex syntax and line breaks literally, case-insensitively", () => {
|
||||
const v = make("a.b(c)[d]$ x A.B(C)[D]$ axb\nend\n1 + 1 = 2", { search: "a.b(c)[d]$" });
|
||||
expect(countMatches(v.state).total).toBe(2);
|
||||
expect(countMatches(make("one\ntwo\none two", { search: "one\ntwo" }).state).total).toBe(1);
|
||||
expect(countMatches(make("1+1 11", { search: "1+1" }).state).total).toBe(1);
|
||||
expect(countMatches(make("a/b a\\b", { search: "a\\b" }).state).total).toBe(1);
|
||||
});
|
||||
|
||||
it("replace with `$` and backslashes as written", () => {
|
||||
const v = make("cost: x; cost: y", { search: "cost", replace: "$& $1 $$ \\n" });
|
||||
replaceAll(v);
|
||||
expect(v.state.doc.toString()).toBe("$& $1 $$ \\n: x; $& $1 $$ \\n: y");
|
||||
const w = make("cost", { search: "cost", replace: "$" });
|
||||
replaceNext(w, true);
|
||||
replaceNext(w, true);
|
||||
expect(w.state.doc.toString()).toBe("$");
|
||||
});
|
||||
|
||||
it("previous wraps from the start to the last match, skipping the selected one", () => {
|
||||
const v = make("ab ab ab", { search: "ab" });
|
||||
v.dispatch({ selection: { anchor: 0, head: 2 } });
|
||||
findPrevious(v);
|
||||
expect(sel(v)).toEqual([6, 8]);
|
||||
findPrevious(v);
|
||||
expect(sel(v)).toEqual([3, 5]);
|
||||
const only = make("x ab", { search: "ab" });
|
||||
only.dispatch({ selection: { anchor: 2, head: 4 } });
|
||||
expect(findPrevious(only)).toBe(false);
|
||||
expect(sel(only)).toEqual([2, 4]);
|
||||
expect(findPrevious(make("x", { search: "ab" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("search context, exclude and preserve case", () => {
|
||||
const lang = StreamLanguage.define<null>({
|
||||
token(stream) {
|
||||
|
||||
@@ -17,12 +17,12 @@ import {
|
||||
type ChangeDesc,
|
||||
type EditorState,
|
||||
type Extension,
|
||||
type SelectionRange,
|
||||
} from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
SearchQuery,
|
||||
findNext as cmFindNext,
|
||||
findPrevious as cmFindPrevious,
|
||||
getSearchQuery,
|
||||
replaceAll as cmReplaceAll,
|
||||
replaceNext as cmReplaceNext,
|
||||
@@ -240,21 +240,15 @@ export interface FindQueryOptions extends FindOptions {
|
||||
inChanges?: boolean;
|
||||
}
|
||||
|
||||
/** The characters a regular expression treats as syntax (`-` only inside a class, which never opens here). */
|
||||
const REGEX_SYNTAX = /[\\^$.*+?()[\]{}|/]/g;
|
||||
|
||||
export function makeQuery(o: FindQueryOptions) {
|
||||
// CodeMirror compares a plain-text query one character at a time; the same text as an escaped
|
||||
// regular expression runs on the engine's matcher, over 20× faster in a large file, so every
|
||||
// keystroke in the bar stays responsive. Its replacement escapes `$` to stay literal too.
|
||||
return new SearchQuery({
|
||||
search: o.regexp ? o.search : o.search.replace(REGEX_SYNTAX, "\\$&"),
|
||||
search: o.search,
|
||||
// Plain-text search and replace are literal (`\n` is not a newline), as in IDEA.
|
||||
literal: !o.regexp,
|
||||
caseSensitive: o.caseSensitive,
|
||||
wholeWord: o.wholeWord,
|
||||
regexp: true,
|
||||
replace: o.regexp ? o.replace : o.replace.replaceAll("$", "$$$$"),
|
||||
regexp: o.regexp,
|
||||
replace: o.replace,
|
||||
test: testFor(o.context ?? "any", !!o.inChanges),
|
||||
});
|
||||
}
|
||||
@@ -351,28 +345,8 @@ export function findNext(view: EditorView): boolean {
|
||||
return view.state.field(findScope, false) ? step(view, true) : cmFindNext(view);
|
||||
}
|
||||
|
||||
/** The last match in `from`–`to` other than `skip`. */
|
||||
function lastMatch(state: EditorState, from: number, to: number, skip?: SelectionRange): Match | null {
|
||||
const cursor = getSearchQuery(state).getCursor(state, from, to);
|
||||
let last: Match | null = null;
|
||||
for (let r = cursor.next(); !r.done; r = cursor.next())
|
||||
if (!skip || r.value.from !== skip.from || r.value.to !== skip.to) last = r.value as Match;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* The match before the selection, wrapping to the end. CodeMirror finds it by scanning ever larger
|
||||
* chunks backwards, quadratic in the distance to the match; one forward pass is linear.
|
||||
*/
|
||||
export function findPrevious(view: EditorView): boolean {
|
||||
const { state } = view;
|
||||
if (state.field(findScope, false)) return step(view, false);
|
||||
if (!getSearchQuery(state).valid) return false;
|
||||
const main = state.selection.main;
|
||||
const m = lastMatch(state, 0, main.from) ?? lastMatch(state, main.from, state.doc.length, main);
|
||||
if (!m) return false;
|
||||
selectMatch(view, m);
|
||||
return true;
|
||||
return view.state.field(findScope, false) ? step(view, false) : cmFindPrevious(view);
|
||||
}
|
||||
|
||||
/** The text replacing `m`, keeping its case when `preserve` is set. */
|
||||
|
||||
@@ -466,8 +466,6 @@ export class EditorController implements SlotHost {
|
||||
if (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
|
||||
if (this.manager.backend.onFsChanged)
|
||||
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
|
||||
if (this.manager.backend.onDiskConflict)
|
||||
this.disposers.push(this.manager.backend.onDiskConflict((e) => this.onDiskConflict(e.path)));
|
||||
const onWindowBlur = () => {
|
||||
if (this.autoSave() && !this.closeSession) {
|
||||
void this.manager.saveAll("auto");
|
||||
@@ -1767,39 +1765,6 @@ export class EditorController implements SlotHost {
|
||||
});
|
||||
}
|
||||
/** Reload from Disk: re-reads the open, unmodified documents of `paths`. */
|
||||
/**
|
||||
* A file changed on disk while its buffer had unsaved changes: the buffer keeps them (autosave
|
||||
* leaves the file alone) until the user loads the disk version or saves over it.
|
||||
*/
|
||||
private onDiskConflict(path: string) {
|
||||
const key = `disk-conflict:${path}`;
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
key,
|
||||
sticky: true,
|
||||
title: tx`${basename(path)} changed on disk`,
|
||||
body: tx(
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
|
||||
),
|
||||
actions: [
|
||||
{
|
||||
label: tx("Load Changes from Disk"),
|
||||
run: () => {
|
||||
const doc = this.manager.get(path)?.getMeta().doc;
|
||||
if (doc === undefined || !this.manager.backend.reloadDiscarding) return;
|
||||
this.manager.backend.reloadDiscarding(doc).catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot reload from disk"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
}),
|
||||
);
|
||||
},
|
||||
},
|
||||
{ label: tx("Keep Editor Changes"), run: () => {} },
|
||||
],
|
||||
});
|
||||
}
|
||||
async reloadFromDisk(paths: string[]) {
|
||||
for (const path of paths) {
|
||||
const model = this.manager.get(path);
|
||||
|
||||
@@ -21,36 +21,20 @@ const target: Location = {
|
||||
range: { start: { line: 3, col: 4 }, end: { line: 3, col: 9 } },
|
||||
};
|
||||
const views: EditorView[] = [];
|
||||
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n", path = `/p/${doc}.${language}`) {
|
||||
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n") {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text,
|
||||
extensions: [lspDoc.of({ doc, path, language, uiMode: language, readOnly: false }), navigationExtension()],
|
||||
extensions: [
|
||||
lspDoc.of({ doc, path: `/p/${doc}.${language}`, language, uiMode: language, readOnly: false }),
|
||||
navigationExtension(),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
it("uses the whole Maven element value for the navigation underline", () => {
|
||||
const text = " <artifactId>cdf-parent</artifactId>\n <version>${revision}</version>";
|
||||
const view = editor(1, "xml", text, "/p/pom.xml");
|
||||
const parent = text.indexOf("cdf-parent");
|
||||
for (const offset of [parent, parent + 3, parent + 4, parent + "cdf-parent".length]) {
|
||||
const range = navigationWord(view, offset)!;
|
||||
expect(view.state.sliceDoc(range.from, range.to)).toBe("cdf-parent");
|
||||
}
|
||||
const revision = text.indexOf("${revision}");
|
||||
const range = navigationWord(view, revision + 4)!;
|
||||
expect(view.state.sliceDoc(range.from, range.to)).toBe("${revision}");
|
||||
|
||||
const multiline = "<artifactId>\n cdf-parent\n </artifactId>";
|
||||
const multilineView = editor(2, "xml", multiline, "/p/multiline/pom.xml");
|
||||
const multilineRange = navigationWord(multilineView, multiline.indexOf("parent"))!;
|
||||
expect(multilineView.state.sliceDoc(multilineRange.from, multilineRange.to)).toBe("cdf-parent");
|
||||
});
|
||||
|
||||
let off: () => void;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
import type { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { onEditorEvent } from "@/editor/api";
|
||||
import { isMavenPom } from "@/platform/buildFiles";
|
||||
import { commands, IpcError, onIdeEvent, type GotoKind, type Location } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { onServerSettled } from "./availability";
|
||||
@@ -55,60 +54,9 @@ export function isConfigurationDocument(view: EditorView): boolean {
|
||||
return language === "yaml" || language === "properties";
|
||||
}
|
||||
|
||||
const XML_VALUE_SCAN_LINES = 256;
|
||||
|
||||
/** The text of the XML element, trimmed to the value itself. */
|
||||
function pomElementValueAt(view: EditorView, offset: number): { from: number; to: number } | null {
|
||||
const doc = view.state.doc;
|
||||
const line = doc.lineAt(offset);
|
||||
let open = -1;
|
||||
const onLine = line.text.lastIndexOf(">", offset - line.from);
|
||||
if (onLine >= 0) open = line.from + onLine;
|
||||
else {
|
||||
for (let number = line.number - 1; number >= 1 && line.number - number <= XML_VALUE_SCAN_LINES; number--) {
|
||||
const previous = doc.line(number);
|
||||
const col = previous.text.lastIndexOf(">");
|
||||
if (col >= 0) {
|
||||
open = previous.from + col;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (open < 0 || offset <= open) return null;
|
||||
|
||||
const afterOpen = doc.lineAt(Math.min(open + 1, doc.length));
|
||||
let close = -1;
|
||||
for (
|
||||
let number = afterOpen.number;
|
||||
number <= doc.lines && number - afterOpen.number <= XML_VALUE_SCAN_LINES;
|
||||
number++
|
||||
) {
|
||||
const current = doc.line(number);
|
||||
const col = current.text.indexOf("<", number === afterOpen.number ? open + 1 - current.from : 0);
|
||||
if (col >= 0) {
|
||||
close = current.from + col;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (close < 0 || offset > close) return null;
|
||||
|
||||
let from = open + 1;
|
||||
let to = close;
|
||||
const raw = doc.sliceString(from, to);
|
||||
from += raw.length - raw.trimStart().length;
|
||||
to -= raw.length - raw.trimEnd().length;
|
||||
return from < to ? { from, to } : null;
|
||||
}
|
||||
|
||||
/** Configuration names include hyphens and dots even when the editor's language word
|
||||
* rules split them. Maven element values use the whole value (`cdf-parent`, not its
|
||||
* hyphenated words). Share this range between decoration and lookup. */
|
||||
/** Configuration names include hyphens and dots even when the editor's
|
||||
* language word rules split them. Share this range between decoration and lookup. */
|
||||
export function navigationWord(view: EditorView, offset: number): { from: number; to: number } | null {
|
||||
const doc = docOf(view);
|
||||
if (doc && isMavenPom(doc.path)) {
|
||||
const value = pomElementValueAt(view, offset);
|
||||
if (value) return value;
|
||||
}
|
||||
if (!isConfigurationDocument(view)) return view.state.wordAt(offset);
|
||||
const line = view.state.doc.lineAt(offset);
|
||||
const nameChar = /[\p{L}\p{N}_.$-]/u;
|
||||
|
||||
@@ -35,7 +35,7 @@ import { basename } from "@/platform/project";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { applyCodeAction, quickFixesAt } from "./intentions";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api";
|
||||
import { CONTRIBUTED_HOVER, contributedAt, type ContributedHover } from "@/editor/api";
|
||||
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
|
||||
import { languageSemantics } from "./semantic";
|
||||
|
||||
@@ -47,9 +47,10 @@ function constructAt(state: EditorView["state"], pos: number, language: string |
|
||||
}
|
||||
|
||||
export async function requestHover(view: EditorView, pos: number): Promise<Hover | null> {
|
||||
for (const own of contributedAtAll<ContributedHover>(view.state, CONTRIBUTED_HOVER, pos)) {
|
||||
const own = contributedAt<ContributedHover>(view.state, CONTRIBUTED_HOVER, pos);
|
||||
if (own) {
|
||||
const h = own(view.state, pos);
|
||||
if (!h) continue;
|
||||
if (!h) return null;
|
||||
const range = { start: offsetToPos(view.state.doc, h.from), end: offsetToPos(view.state.doc, h.to) };
|
||||
return { contents: { kind: "markdown", value: h.markdown }, range };
|
||||
}
|
||||
|
||||
@@ -46,8 +46,8 @@ import {
|
||||
} from "@/platform/ipc";
|
||||
import {
|
||||
CONTRIBUTED_DEFINITION,
|
||||
contributedAtAll,
|
||||
activeEditor,
|
||||
contributedAt,
|
||||
whenSynced,
|
||||
type ContributedDefinition,
|
||||
type EditorDocContext,
|
||||
@@ -444,12 +444,8 @@ async function gotoResolved(
|
||||
done: () => void,
|
||||
) {
|
||||
if (kind === "definition" || kind === "declaration") {
|
||||
// More than one feature can attach a definition provider to the same file (the
|
||||
// MyBatis SQL support and the Maven POM navigator both see XML). Providers decline
|
||||
// positions they do not own, so try every one instead of letting the first false
|
||||
// result hide the real target.
|
||||
const own = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
|
||||
if (own.some((definition) => definition(view, offset))) return;
|
||||
const own = contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
|
||||
if (own?.(view, offset)) return;
|
||||
if (showPhpConstructDocumentation(view, offset)) return;
|
||||
const before = view.state.doc;
|
||||
const plugin = await contributedNavigation(view, offset).catch(() => null);
|
||||
@@ -877,9 +873,7 @@ async function probeNavigation(
|
||||
const plugin = await contributedNavigation(view, offset).catch(() => null);
|
||||
if (plugin) return { info: null, plugin };
|
||||
const doc = docOf(view);
|
||||
let navigable = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset).some(
|
||||
(definition) => definition.canHandle?.(view.state, offset) ?? true,
|
||||
);
|
||||
let navigable = !!contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
|
||||
if (!navigable && doc) {
|
||||
const pos = offsetToPos(view.state.doc, offset);
|
||||
let fromSyntax = false;
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import {
|
||||
CONTRIBUTED_DEFINITION,
|
||||
CONTRIBUTED_HOVER,
|
||||
type ContributedDefinition,
|
||||
type ContributedHover,
|
||||
} from "@/editor/api";
|
||||
import type { commands, Location } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { resetNavigationModifier } from "@/platform/navigationModifier";
|
||||
@@ -24,7 +18,7 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
|
||||
const { gotoTargets, navigationExtension } = await import("./navigation");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { quickDefinition, requestHover } = await import("./hover");
|
||||
const { quickDefinition } = await import("./hover");
|
||||
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
|
||||
const { closePopup } = await import("./popupStore");
|
||||
const { provideEditorService } = await import("@/workbench/contributions");
|
||||
@@ -103,49 +97,6 @@ afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("tries a later contributed definition when an earlier provider declines", async () => {
|
||||
const declined = vi.fn<ContributedDefinition>(() => false);
|
||||
const handled = vi.fn<ContributedDefinition>((_view, _pos) => {
|
||||
openFile("/p/Handled.java", {});
|
||||
return true;
|
||||
});
|
||||
view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "maven",
|
||||
extensions: [
|
||||
EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: declined }]),
|
||||
EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: handled }]),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
|
||||
await gotoTargets(view, "definition", 0);
|
||||
expect(declined).toHaveBeenCalledOnce();
|
||||
expect(handled).toHaveBeenCalledOnce();
|
||||
expect(openFile).toHaveBeenCalledWith("/p/Handled.java", {});
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tries a later contributed hover when an earlier provider declines", async () => {
|
||||
const declined = vi.fn<ContributedHover>(() => null);
|
||||
const handled = vi.fn<ContributedHover>(() => ({ from: 1, to: 3, markdown: "handled" }));
|
||||
view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "maven",
|
||||
extensions: [
|
||||
EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: declined }]),
|
||||
EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: handled }]),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
|
||||
expect((await requestHover(view, 1))?.contents.value).toBe("handled");
|
||||
expect(declined).toHaveBeenCalledOnce();
|
||||
expect(handled).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
describe.each(cases)("shared definition requests in $language", (c) => {
|
||||
it("lets a click reuse the hover probe's request for the same word", async () => {
|
||||
editor(c);
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
/* IDEA's Navigate to Managing Dependency icon in the shared editor icon area. */
|
||||
.managedMarker {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius-small);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.managedMarker:hover,
|
||||
.managedMarker:focus-visible {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
@@ -1,19 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
mavenGotoDeclaration: vi.fn(),
|
||||
mavenManagedDeclarations: vi.fn(),
|
||||
cancelRequest: vi.fn(),
|
||||
}));
|
||||
const ipc = vi.hoisted(() => ({ mavenGotoDeclaration: vi.fn() }));
|
||||
const workbench = vi.hoisted(() => ({ openFile: vi.fn() }));
|
||||
const hints = vi.hoisted(() => ({ showHint: vi.fn() }));
|
||||
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
isTauri: () => false,
|
||||
isCancelled: () => false,
|
||||
nextRequestId: () => 7,
|
||||
onIdeEvent: () => () => {},
|
||||
call: async (p: Promise<{ status: string; data?: unknown; error?: unknown }>) => {
|
||||
const r = await p;
|
||||
if (r.status !== "ok") throw r.error;
|
||||
@@ -25,25 +16,15 @@ vi.mock("@/workbench/contributions", () => ({
|
||||
editorService: () => workbench,
|
||||
}));
|
||||
vi.mock("@/editor/lsp/hint", () => ({ showHint: hints.showHint }));
|
||||
vi.mock("@/editor/api", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/editor/api")>()),
|
||||
vi.mock("@/editor/api", () => ({
|
||||
CONTRIBUTED_DEFINITION: "openideaDefinition",
|
||||
whenSynced: () => Promise.resolve(),
|
||||
}));
|
||||
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
|
||||
import type { ContributedDefinition } from "@/editor/api";
|
||||
import { inArtifactElement, placeManagedMarks, pomNavigationExtension, propertyRefAt } from "./pomNavigation";
|
||||
import { inArtifactElement, pomNavigationExtension, propertyRefAt } from "./pomNavigation";
|
||||
|
||||
const DEFINITION = "openideaDefinition";
|
||||
let view: EditorView | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
view?.destroy();
|
||||
view = null;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/** An editor state over `text` with the contribution for `path` installed. */
|
||||
function state(text: string, path = "/p/app/pom.xml") {
|
||||
@@ -51,22 +32,20 @@ function state(text: string, path = "/p/app/pom.xml") {
|
||||
doc: text,
|
||||
extensions: [
|
||||
pomNavigationExtension({
|
||||
doc: 1,
|
||||
path,
|
||||
language: "xml",
|
||||
uiMode: "XML",
|
||||
readOnly: false,
|
||||
} as Parameters<typeof pomNavigationExtension>[0]),
|
||||
iconAreaExtension,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const definitionAt = (s: ReturnType<typeof state>, pos: number) =>
|
||||
s.languageDataAt<ContributedDefinition>(DEFINITION, pos)[0];
|
||||
s.languageDataAt<(v: { state: typeof s }, p: number) => boolean>(DEFINITION, pos)[0];
|
||||
|
||||
/** The definition only reads `view.state`; a bare handle is enough. */
|
||||
const run = (s: ReturnType<typeof state>, pos: number) => definitionAt(s, pos)!({ state: s } as EditorView, pos);
|
||||
const run = (s: ReturnType<typeof state>, pos: number) => definitionAt(s, pos)!({ state: s }, pos);
|
||||
|
||||
const pom = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
@@ -151,13 +130,6 @@ describe("POM go to declaration", () => {
|
||||
expect(definitionAt(s, pom.indexOf("<parent>"))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("declines non-navigation POM positions without invoking the definition", () => {
|
||||
const s = state(pom);
|
||||
const definition = definitionAt(s, pom.indexOf("<artifactId>other-lib"))!;
|
||||
expect(definition.canHandle?.(s, pom.indexOf("<artifactId>other-lib"))).toBe(true);
|
||||
expect(definition.canHandle?.(s, pom.indexOf("<modelVersion>"))).toBe(false);
|
||||
});
|
||||
|
||||
it("opens the declaration the backend resolved", async () => {
|
||||
const target = {
|
||||
path: "/p/pom.xml",
|
||||
@@ -180,58 +152,6 @@ describe("POM go to declaration", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("places one managed-dependency marker per backend line", () => {
|
||||
const s = state(pom);
|
||||
const target = {
|
||||
path: "/p/pom.xml",
|
||||
range: { start: { line: 1, col: 2 }, end: { line: 1, col: 8 } },
|
||||
kind: "managedDependency" as const,
|
||||
label: "com.example:other-lib",
|
||||
};
|
||||
expect(
|
||||
placeManagedMarks(s.doc, [
|
||||
{ line: 15, version: "1.2.3", target },
|
||||
{ line: 15, version: "ignored", target },
|
||||
{ line: 999, version: null, target },
|
||||
]),
|
||||
).toEqual([{ pos: s.doc.line(16).from, link: { line: 15, version: "1.2.3", target } }]);
|
||||
});
|
||||
|
||||
it("opens the managing declaration from its gutter icon", async () => {
|
||||
const target = {
|
||||
path: "/p/pom.xml",
|
||||
range: { start: { line: 4, col: 6 }, end: { line: 4, col: 14 } },
|
||||
kind: "managedDependency" as const,
|
||||
label: "com.example:other-lib",
|
||||
};
|
||||
ipc.mavenManagedDeclarations.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{ line: pom.slice(0, pom.indexOf("<artifactId>other-lib")).split("\n").length - 1, version: "1.0", target },
|
||||
],
|
||||
});
|
||||
view = new EditorView({ state: state(pom), parent: document.body });
|
||||
await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledWith("/p/app/pom.xml", 7));
|
||||
await vi.waitFor(() => expect(view!.dom.querySelector("[data-managed-dependency]")).not.toBeNull());
|
||||
|
||||
fireEvent.click(view.dom.querySelector("[data-managed-dependency]")!);
|
||||
await vi.waitFor(() =>
|
||||
expect(workbench.openFile).toHaveBeenCalledWith("/p/pom.xml", {
|
||||
selection: { line: 4, col: 6, endLine: 4, endCol: 14 },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("cancels an in-flight gutter refresh when the document changes", async () => {
|
||||
let finish!: (value: unknown) => void;
|
||||
ipc.mavenManagedDeclarations.mockImplementation(() => new Promise((resolve) => (finish = resolve)));
|
||||
view = new EditorView({ state: state(pom), parent: document.body });
|
||||
await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledOnce());
|
||||
view.dispatch({ changes: { from: 0, insert: " " } });
|
||||
await vi.waitFor(() => expect(ipc.cancelRequest).toHaveBeenCalledWith(7));
|
||||
finish({ status: "ok", data: [] });
|
||||
});
|
||||
|
||||
it("says so when nothing resolves, without navigating", async () => {
|
||||
ipc.mavenGotoDeclaration.mockResolvedValue({ status: "ok", data: null });
|
||||
const s = state(pom);
|
||||
|
||||
@@ -2,41 +2,21 @@
|
||||
* Go to declaration in `pom.xml`: ⌘/Ctrl-click (or ⌘B) on a `${property}` reference
|
||||
* opens the `<properties>` entry that defines it — the POM's own, else one inherited
|
||||
* along the parent chain (a parent POM outside the project opens from the local
|
||||
* repository, read-only as a plain file). A dependency, plugin or `<parent>` opens the
|
||||
* artifact's own POM (a project module first, then the local repository). Unversioned
|
||||
* declarations also get IDEA's "Navigate to managing dependency" gutter icon, which
|
||||
* opens the exact `<dependencyManagement>` / `<pluginManagement>` entry — including
|
||||
* one in a parent POM or imported BOM — that controls the version. The backend does
|
||||
* the resolution; here only cheap eligibility is computed, so the ⌘-hover underline
|
||||
* stays out of the rest of the file and no marker promises a target that does not exist.
|
||||
* repository, read-only as a plain file) — and a dependency / plugin whose version a
|
||||
* `<dependencyManagement>` / `<pluginManagement>` entry provides opens that managing
|
||||
* declaration; otherwise a dependency, plugin or `<parent>` opens the artifact's own POM
|
||||
* (a project module's, else the local repository's). The backend resolves both with the build model's POM reader and parent
|
||||
* resolver; here only cheap eligibility is computed (a reference span, an artifact
|
||||
* element), so the ⌘-hover underline stays out of the rest of the file, and nothing
|
||||
* resolves to no jump at all: an unresolvable property or parent never navigates
|
||||
* somewhere unrelated.
|
||||
*/
|
||||
import { EditorState, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
CONTRIBUTED_DEFINITION,
|
||||
iconAreaSource,
|
||||
mapLineStart,
|
||||
onEditorEvent,
|
||||
whenSynced,
|
||||
type ContributedDefinition,
|
||||
type EditorDocContext,
|
||||
} from "@/editor/api";
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { CONTRIBUTED_DEFINITION, type ContributedDefinition, type EditorDocContext, whenSynced } from "@/editor/api";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { isMavenPom } from "@/platform/buildFiles";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
isCancelled,
|
||||
nextRequestId,
|
||||
onIdeEvent,
|
||||
type PomGoto,
|
||||
type PomManagedDeclaration,
|
||||
type RequestId,
|
||||
} from "@/platform/ipc";
|
||||
import { gutterIconMarkup } from "@/ui";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import styles from "./PomNavigation.module.css";
|
||||
|
||||
/** The `${property}` reference covering `at`, if any (clicking the `$` counts). */
|
||||
export function propertyRefAt(text: string, at: number): { from: number; to: number } | null {
|
||||
@@ -63,193 +43,9 @@ export function inArtifactElement(text: string, at: number): boolean {
|
||||
return inside("dependency", text, at) || inside("plugin", text, at) || inside("parent", text, at);
|
||||
}
|
||||
|
||||
export interface ManagedMark {
|
||||
pos: number;
|
||||
link: PomManagedDeclaration;
|
||||
}
|
||||
|
||||
/** Places the backend's 0-based lines in a document, one icon per declaration line. */
|
||||
export function placeManagedMarks(doc: Text, links: readonly PomManagedDeclaration[]): ManagedMark[] {
|
||||
const seen = new Set<number>();
|
||||
const out: ManagedMark[] = [];
|
||||
for (const link of links) {
|
||||
if (!Number.isInteger(link.line) || link.line < 0 || link.line >= doc.lines || seen.has(link.line)) continue;
|
||||
seen.add(link.line);
|
||||
out.push({ pos: doc.line(link.line + 1).from, link });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const setManagedMarks = StateEffect.define<ManagedMark[]>();
|
||||
|
||||
const managedMarksField = StateField.define<ManagedMark[]>({
|
||||
create: () => [],
|
||||
update(value, tr) {
|
||||
for (const effect of tr.effects) if (effect.is(setManagedMarks)) return effect.value;
|
||||
if (!tr.docChanged || !value.length) return value;
|
||||
return value.map((mark) => ({ ...mark, pos: mapLineStart(tr, mark.pos) }));
|
||||
},
|
||||
});
|
||||
|
||||
const fileName = (path: string) => path.split(/[\\/]/).pop() || path;
|
||||
|
||||
function managedTitle(link: PomManagedDeclaration): string {
|
||||
const location = `${fileName(link.target.path)}:${link.target.range.start.line + 1}`;
|
||||
return link.version ? tx`Managed version ${link.version} in ${location}` : tx`Managed in ${location}`;
|
||||
}
|
||||
|
||||
class ManagedMarker extends GutterMarker {
|
||||
constructor(
|
||||
readonly mark: ManagedMark,
|
||||
readonly open: () => void,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
override eq(other: GutterMarker): boolean {
|
||||
const a = this.mark.link;
|
||||
const b = other instanceof ManagedMarker ? other.mark.link : null;
|
||||
return (
|
||||
!!b &&
|
||||
a.version === b.version &&
|
||||
a.target.path === b.target.path &&
|
||||
a.target.range.start.line === b.target.range.start.line &&
|
||||
a.target.range.start.col === b.target.range.start.col
|
||||
);
|
||||
}
|
||||
|
||||
override toDOM(): Node {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = styles.managedMarker ?? "";
|
||||
button.dataset.managedDependency = "";
|
||||
button.title = managedTitle(this.mark.link);
|
||||
button.setAttribute("aria-label", button.title);
|
||||
button.innerHTML = gutterIconMarkup("gutter-navigate") ?? "";
|
||||
// Keep the editor caret where it was; a normal click then runs the navigation,
|
||||
// so the icon also works from the keyboard.
|
||||
button.addEventListener("mousedown", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
});
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.open();
|
||||
});
|
||||
return button;
|
||||
}
|
||||
}
|
||||
|
||||
function openGoto(goto: PomGoto): Promise<void> | void {
|
||||
return editorService().openFile(goto.path, {
|
||||
selection: {
|
||||
line: goto.range.start.line,
|
||||
col: goto.range.start.col,
|
||||
endLine: goto.range.end.line,
|
||||
endCol: goto.range.end.col,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function openManaged(view: EditorView, target: PomGoto): void {
|
||||
void Promise.resolve(openGoto(target)).catch((e: unknown) =>
|
||||
showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The icon area is shared with run, inheritance and plugin markers; press handling is source-scoped. */
|
||||
function managedGutter(ctx: EditorDocContext): Extension {
|
||||
if (ctx.doc < 0) return [];
|
||||
return [
|
||||
managedMarksField,
|
||||
ViewPlugin.fromClass(
|
||||
class {
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private generation = 0;
|
||||
private inFlight: RequestId | undefined;
|
||||
private off: () => void;
|
||||
|
||||
constructor(readonly view: EditorView) {
|
||||
this.schedule(0);
|
||||
const offEditor = onEditorEvent((event) => {
|
||||
if (
|
||||
(event.type === "docChanged" || event.type === "docSaved") &&
|
||||
event.path !== ctx.path &&
|
||||
isMavenPom(event.path)
|
||||
)
|
||||
this.schedule(500);
|
||||
});
|
||||
const offFiles = onIdeEvent("fsChanged", (event) => {
|
||||
if ([...event.created, ...event.modified, ...event.removed].some(isMavenPom)) this.schedule(500);
|
||||
});
|
||||
const offRoots = onIdeEvent("projectRootsChanged", () => this.schedule(300));
|
||||
const offSettings = onIdeEvent("settingsChanged", (event) => {
|
||||
if (event.key.startsWith("languages.java.")) this.schedule(300);
|
||||
});
|
||||
this.off = () => {
|
||||
offEditor();
|
||||
offFiles();
|
||||
offRoots();
|
||||
offSettings();
|
||||
};
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged) this.schedule();
|
||||
}
|
||||
|
||||
schedule(delay = 300) {
|
||||
clearTimeout(this.timer);
|
||||
if (this.inFlight !== undefined) {
|
||||
void commands.cancelRequest(this.inFlight);
|
||||
this.inFlight = undefined;
|
||||
}
|
||||
this.timer = setTimeout(() => void this.refresh(), delay);
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const generation = ++this.generation;
|
||||
const current = this.view.state.doc;
|
||||
const request = nextRequestId();
|
||||
this.inFlight = request;
|
||||
try {
|
||||
await whenSynced(this.view);
|
||||
if (generation !== this.generation || this.view.state.doc !== current) return;
|
||||
const links = await call(commands.mavenManagedDeclarations(ctx.path, request));
|
||||
if (generation !== this.generation || this.inFlight !== request || this.view.state.doc !== current) return;
|
||||
this.view.dispatch({ effects: setManagedMarks.of(placeManagedMarks(current, links)) });
|
||||
} catch (e) {
|
||||
if (!isCancelled(e) && generation === this.generation) console.debug("[POM managed dependencies]", e);
|
||||
} finally {
|
||||
if (this.inFlight === request) this.inFlight = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.off();
|
||||
clearTimeout(this.timer);
|
||||
if (this.inFlight !== undefined) void commands.cancelRequest(this.inFlight);
|
||||
this.generation++;
|
||||
}
|
||||
},
|
||||
),
|
||||
iconAreaSource.of({
|
||||
order: 25,
|
||||
markers: (view) =>
|
||||
RangeSet.of(
|
||||
view.state
|
||||
.field(managedMarksField)
|
||||
.map((mark) => new ManagedMarker(mark, () => openManaged(view, mark.link.target)).range(mark.pos)),
|
||||
true,
|
||||
),
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/** Go to declaration in a POM of the project (or an opened parent POM of the local repository). */
|
||||
export function pomNavigationExtension(ctx: EditorDocContext): Extension {
|
||||
if (ctx.virtual || !isMavenPom(ctx.path)) return [];
|
||||
if (ctx.virtual || !/(^|\/)pom\.xml$/.test(ctx.path)) return [];
|
||||
const eligible = (state: EditorState, pos: number) => {
|
||||
const text = state.doc.toString();
|
||||
return propertyRefAt(text, pos) !== null || inArtifactElement(text, pos);
|
||||
@@ -273,7 +69,14 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension {
|
||||
return;
|
||||
}
|
||||
if (view.state.doc !== doc) return; // The user kept typing while the POM resolved.
|
||||
void openGoto(goto);
|
||||
void editorService().openFile(goto.path, {
|
||||
selection: {
|
||||
line: goto.range.start.line,
|
||||
col: goto.range.start.col,
|
||||
endLine: goto.range.end.line,
|
||||
endCol: goto.range.end.col,
|
||||
},
|
||||
});
|
||||
})
|
||||
.catch((e: unknown) =>
|
||||
showHint(view, e instanceof Error ? e.message : String(e), {
|
||||
@@ -282,11 +85,7 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension {
|
||||
);
|
||||
return true;
|
||||
};
|
||||
definition.canHandle = eligible;
|
||||
return [
|
||||
EditorState.languageData.of((state, pos) =>
|
||||
eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
|
||||
),
|
||||
managedGutter(ctx),
|
||||
];
|
||||
return EditorState.languageData.of((state, pos) =>
|
||||
eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
|
||||
);
|
||||
}
|
||||
@@ -108,7 +108,7 @@ function inspections(path: string, sql: SqlText): Extension {
|
||||
}
|
||||
|
||||
function definition(path: string, sql: SqlText): ContributedDefinition {
|
||||
const handle: ContributedDefinition = (view, pos) => {
|
||||
return (view, pos) => {
|
||||
if (sql.at && !sql.at(view.state, pos)) return false;
|
||||
const r = resolver(path, view.state, sql).resolveAt(pos);
|
||||
const sym = r?.symbol;
|
||||
@@ -143,9 +143,6 @@ function definition(path: string, sql: SqlText): ContributedDefinition {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
const at = sql.at;
|
||||
if (at) handle.canHandle = (state, pos) => at(state, pos);
|
||||
return handle;
|
||||
}
|
||||
|
||||
const code = (s: string) => `\`${s.replace(/`/g, "")}\``;
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
} from "@/ui";
|
||||
import { useContributions, type RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { TASK_LABELS, taskLabel, type BeforeLaunchKind } from "./beforeLaunch";
|
||||
import { ExpandableTextarea } from "./ExpandableTextarea";
|
||||
import {
|
||||
commandLine,
|
||||
compoundCycle,
|
||||
@@ -818,6 +817,7 @@ function TypeField({
|
||||
invalid: boolean;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const root = useProject((s) => s.project?.root ?? null);
|
||||
const listId = `run-field-${field.key}`;
|
||||
const [loaded, setLoaded] = useState<ReadonlyArray<{ value: string; label: string; detail?: string }>>([]);
|
||||
@@ -848,13 +848,14 @@ function TypeField({
|
||||
return <Checkbox checked={value === "true"} onChange={(on) => onChange(on ? "true" : "")} label={field.label} />;
|
||||
if (field.control === "textarea")
|
||||
return (
|
||||
<ExpandableTextarea
|
||||
label={field.label}
|
||||
<textarea
|
||||
className={clsx(styles.textarea, invalid && styles.textareaInvalid)}
|
||||
aria-label={tx(field.label)}
|
||||
spellCheck={false}
|
||||
value={value}
|
||||
placeholder={field.placeholder}
|
||||
rows={field.rows}
|
||||
invalid={invalid}
|
||||
onChange={onChange}
|
||||
placeholder={tx(field.placeholder)}
|
||||
rows={field.rows ?? 4}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
);
|
||||
const suggestions = field.suggestions?.(all, params) ?? [];
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { ExpandableTextarea } from "./ExpandableTextarea";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const LONG = "-Ddemo.endpoint=https://example.com/demo/environments/local/feature-flags/configuration/versions/current";
|
||||
const VALUE = `-Xmx512m\n${LONG}\n-Ddemo.mode=local`;
|
||||
|
||||
function editors() {
|
||||
return screen.getAllByRole("textbox", { name: "VM options" }) as HTMLTextAreaElement[];
|
||||
}
|
||||
|
||||
it("edits in an expanded editor that keeps each line on one visual line", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ExpandableTextarea label="VM options" value={VALUE} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand (⇧⏎)" }));
|
||||
const expanded = editors()[1]!;
|
||||
expect(expanded.value).toBe(VALUE);
|
||||
expect(expanded.getAttribute("wrap")).toBe("off");
|
||||
fireEvent.change(expanded, { target: { value: `${VALUE}\n-Dextra=1` } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "OK" }));
|
||||
expect(onChange).toHaveBeenCalledWith(`${VALUE}\n-Dextra=1`);
|
||||
expect(editors()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("leaves the value alone on Cancel or OK without edits, and opens with Shift+Enter", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ExpandableTextarea label="VM options" value={VALUE} onChange={onChange} />);
|
||||
fireEvent.keyDown(editors()[0]!, { key: "Enter", shiftKey: true });
|
||||
fireEvent.change(editors()[1]!, { target: { value: "-Xmx1g" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(editors()).toHaveLength(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand (⇧⏎)" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "OK" }));
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Dialog, IconButton } from "@/ui";
|
||||
import styles from "./Run.module.css";
|
||||
|
||||
/**
|
||||
* A run configuration's multi-line field (VM options, say) with an Expand button (⇧⏎) that
|
||||
* edits it in a larger editor where each line stays on one visual line and scrolls sideways,
|
||||
* so one long argument isn't mistaken for several.
|
||||
*/
|
||||
export function ExpandableTextarea({
|
||||
label,
|
||||
value,
|
||||
placeholder,
|
||||
rows,
|
||||
invalid,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
placeholder?: string;
|
||||
rows?: number;
|
||||
invalid?: boolean;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
return (
|
||||
<div className={styles.textareaWithButton}>
|
||||
<textarea
|
||||
className={clsx(styles.textarea, invalid && styles.textareaInvalid)}
|
||||
aria-label={tx(label)}
|
||||
spellCheck={false}
|
||||
value={value}
|
||||
placeholder={tx(placeholder)}
|
||||
rows={rows ?? 4}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
setExpanded(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<IconButton icon="expand-all" size="small" iconSize={14} title="Expand (⇧⏎)" onClick={() => setExpanded(true)} />
|
||||
{expanded && (
|
||||
<ExpandedTextDialog label={label} value={value} onOk={onChange} onClose={() => setExpanded(false)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ExpandedTextDialog({
|
||||
label,
|
||||
value,
|
||||
onOk,
|
||||
onClose,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onOk: (value: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const [text, setText] = useState(value);
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title={tx(label)}
|
||||
onClose={onClose}
|
||||
width={720}
|
||||
resizable="both"
|
||||
minWidth={360}
|
||||
minHeight={220}
|
||||
buttons={[
|
||||
{
|
||||
label: "OK",
|
||||
role: "default",
|
||||
onClick: () => {
|
||||
if (text !== value) onOk(text);
|
||||
onClose();
|
||||
},
|
||||
},
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<textarea
|
||||
className={clsx(styles.textarea, styles.expandedTextarea)}
|
||||
aria-label={tx(label)}
|
||||
spellCheck={false}
|
||||
wrap="off"
|
||||
rows={14}
|
||||
value={text}
|
||||
autoFocus
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -848,29 +848,6 @@
|
||||
font-size: var(--fs-ui);
|
||||
outline: none;
|
||||
}
|
||||
.textareaWithButton {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
.textareaWithButton > textarea {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.textareaWithButton > button {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
/* One visual line per line of text: a long argument scrolls instead of wrapping. */
|
||||
.expandedTextarea {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 160px;
|
||||
box-sizing: border-box;
|
||||
resize: none;
|
||||
white-space: pre;
|
||||
overflow: auto;
|
||||
}
|
||||
.textarea:focus {
|
||||
box-shadow: inset 0 0 0 1px var(--focus-ring);
|
||||
}
|
||||
|
||||
@@ -200,5 +200,4 @@ describe("appearance & behavior settings", () => {
|
||||
|
||||
it("loads an old attach setting as ask", () => {
|
||||
expect(validateGeneralExtras({ openProjectIn: "attach" }).openProjectIn).toBe("ask");
|
||||
expect(validateGeneralExtras({ openProjectIn: "tab" }).openProjectIn).toBe("tab");
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import { ZOOM_LIMITS } from "@/platform/zoom";
|
||||
import { validateIconThemeOptionsMap } from "@/platform/iconThemeOptions";
|
||||
|
||||
export type Antialiasing = "subpixel" | "greyscale" | "none";
|
||||
export type OpenProjectIn = "ask" | "new" | "same" | "tab";
|
||||
export type OpenProjectIn = "ask" | "new" | "same";
|
||||
export type NotificationDisplay = "balloon" | "sticky" | "none";
|
||||
export type NavigationBarPosition = "top" | "statusBar" | "hidden";
|
||||
export type BackgroundImageFill = "scale" | "plain" | "tile";
|
||||
@@ -306,7 +306,7 @@ export function validateGeneralExtras(raw: unknown): GeneralExtras {
|
||||
const d = DEFAULT_GENERAL_EXTRAS;
|
||||
const df = obj(g.dateFormat);
|
||||
return {
|
||||
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same", "tab"] as const, d.openProjectIn),
|
||||
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same"] as const, d.openProjectIn),
|
||||
updateSource: oneOf(g.updateSource, ["auto", "github", "cnb"] as const, d.updateSource),
|
||||
autoCheckUpdates: bool(g.autoCheckUpdates, d.autoCheckUpdates),
|
||||
showWhatsNewAfterUpdate: bool(g.showWhatsNewAfterUpdate, d.showWhatsNewAfterUpdate),
|
||||
|
||||
@@ -575,7 +575,6 @@ function ToolWindowsGrid() {
|
||||
const OPEN_IN: Array<{ value: OpenProjectIn; label: string }> = [
|
||||
{ value: "new", label: "New window" },
|
||||
{ value: "same", label: "Current window" },
|
||||
{ value: "tab", label: "New tab in current window" },
|
||||
{ value: "ask", label: "Ask" },
|
||||
];
|
||||
|
||||
|
||||
@@ -4,8 +4,3 @@ export function isGradleBuildInput(path: string): boolean {
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
/** A project POM or a POM installed in the local Maven repository. */
|
||||
export function isMavenPom(path: string): boolean {
|
||||
return /(^|[\\/])(?:pom\.xml|[^\\/]+\.pom)$/i.test(path);
|
||||
}
|
||||
@@ -2633,7 +2633,6 @@
|
||||
"Hot reload on save failed: {0}": "Hot reload on save failed: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
|
||||
"New Tab": "New Tab",
|
||||
"New tab in current window": "New tab in current window",
|
||||
"Show Only Widgets": "Show Only Widgets",
|
||||
"Update failed": "Update failed",
|
||||
"Updating branches": "Updating branches",
|
||||
@@ -2730,11 +2729,5 @@
|
||||
"Caret": "Caret",
|
||||
"Code Structure": "Code Structure",
|
||||
"Presentation": "Presentation",
|
||||
"Code Assistance": "Code Assistance",
|
||||
"Managed version {version} in {location}": "Managed version {version} in {location}",
|
||||
"Managed in {location}": "Managed in {location}",
|
||||
"{name} changed on disk": "{name} changed on disk",
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
|
||||
"Load Changes from Disk": "Load Changes from Disk",
|
||||
"Keep Editor Changes": "Keep Editor Changes"
|
||||
"Code Assistance": "Code Assistance"
|
||||
}
|
||||
@@ -1911,7 +1911,6 @@
|
||||
"New name": "新名称",
|
||||
"New terminal sessions run the interpreter's virtualenv activate script.": "新的终端会话会运行解释器的 virtualenv 激活脚本。",
|
||||
"New window": "新窗口",
|
||||
"New tab in current window": "当前窗口的新标签页",
|
||||
"New…": "新建…",
|
||||
"Next Bookmark": "下一个书签",
|
||||
"Next Change": "下一个更改",
|
||||
@@ -9096,11 +9095,5 @@
|
||||
"Remove All Watches": "移除所有监视",
|
||||
"GitHub account": "GitHub 账号",
|
||||
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
|
||||
"github-username": "GitHub 用户名",
|
||||
"Managed version {version} in {location}": "版本 {version} 由 {location} 管理",
|
||||
"Managed in {location}": "由 {location} 管理",
|
||||
"{name} changed on disk": "{name} 已在磁盘上更改",
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "该文件在 IDE 外被修改,而编辑器中还有未保存的更改。保存会保留编辑器中的版本并覆盖该文件。",
|
||||
"Load Changes from Disk": "从磁盘加载更改",
|
||||
"Keep Editor Changes": "保留编辑器中的更改"
|
||||
"github-username": "GitHub 用户名"
|
||||
}
|
||||
@@ -23,8 +23,7 @@ beforeEach(() => {
|
||||
lightEdit: false,
|
||||
});
|
||||
});
|
||||
it("offers attach for this open without remembering it", async () => {
|
||||
const button = "attach";
|
||||
it.each(["attach", "tab"] as const)("offers %s for this open without remembering it", async (button) => {
|
||||
vi.mocked(ask).mockResolvedValue({ button, checked: true });
|
||||
expect(await chooseProjectWindow("B")).toBe(button);
|
||||
const prompt = vi.mocked(ask).mock.calls[0]![0];
|
||||
@@ -50,18 +49,8 @@ it("treats a stored attach policy as ask", () => {
|
||||
useProject.setState({ settings: { general: { openProjectIn: "attach" } } } as never);
|
||||
expect(openPolicy()).toBe("ask");
|
||||
});
|
||||
it.each(["new", "same", "tab"] as const)("remembers %s", async (mode) => {
|
||||
it.each(["new", "same"] as const)("remembers %s", async (mode) => {
|
||||
vi.mocked(ask).mockResolvedValue({ button: mode, checked: true });
|
||||
await chooseProjectWindow("B");
|
||||
expect(commands.settingsSet).toHaveBeenCalledWith("global", "general.openProjectIn", JSON.stringify(mode));
|
||||
});
|
||||
|
||||
it("opens a project tab by policy, or a new window when this one can't take one", async () => {
|
||||
useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never);
|
||||
expect(openPolicy()).toBe("tab");
|
||||
expect(await chooseProjectWindow("B")).toBe("tab");
|
||||
expect(await chooseProjectWindow("remote", false)).toBe("new");
|
||||
useProject.setState({ project: null, lightEdit: true });
|
||||
expect(await chooseProjectWindow("B")).toBe("new");
|
||||
expect(ask).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -7,9 +7,9 @@ import { ask } from "./messages";
|
||||
import { maybeEditorService } from "./contributions";
|
||||
|
||||
/** "Open project in": `new` | `same` | `ask`. */
|
||||
export function openPolicy(): "ask" | "new" | "same" | "tab" {
|
||||
export function openPolicy(): "ask" | "new" | "same" {
|
||||
const v = useProject.getState().settings?.general?.openProjectIn;
|
||||
return v === "new" || v === "same" || v === "tab" ? v : "ask";
|
||||
return v === "new" || v === "same" ? v : "ask";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,8 +26,6 @@ export async function chooseProjectWindow(
|
||||
// Both ways of keeping this window's project: a workspace folder, or a project tab of this window.
|
||||
const canAdd = allowAttach && !!project && !isRemoteWindow();
|
||||
const mode = openPolicy();
|
||||
// A project tab needs this window's project beside it; without one, a new window is the closest.
|
||||
if (mode === "tab") return canAdd ? "tab" : "new";
|
||||
if (mode !== "ask") return mode;
|
||||
const r = await ask({
|
||||
title: t("app.window.askTitle"),
|
||||
@@ -48,9 +46,9 @@ export async function chooseProjectWindow(
|
||||
],
|
||||
checkbox: t("app.window.askRemember"),
|
||||
});
|
||||
// "Attach" is one-off, as in IDEA: "Open project in" has no value for it, so Don't ask again ignores it.
|
||||
// "Attach" and "New Tab" are one-off: "Open project in" has no value for them, so Don't ask again ignores both.
|
||||
if (r.button !== "same" && r.button !== "new" && r.button !== "attach" && r.button !== "tab") return null;
|
||||
if (r.checked && r.button !== "attach") {
|
||||
if (r.checked && (r.button === "same" || r.button === "new")) {
|
||||
try {
|
||||
useProject.setState({
|
||||
settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(r.button))),
|
||||
|
||||
Reference in new issue
Block a user