Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 68ab95a631 fix(debugger): report obsolete methods as a completed hot swap
Treat the obsolete-method response and event as a reload warning. Explain why active frames keep the old code and offer Reset Frame for supported, droppable paused frames while preserving real failures and cancelled-build restart requirements.
2026-11-09 18:06:42 +08:00
Budi Santosoтаboenkkk 8ddf979cfe feat(db): separate procedures and functions into their own schema folders (#2270)
The database tree lists routines in one `routines` folder. A Separate Procedures and Functions option in the Database tool window's menu (off by default, remembered across sessions) lists `procedures` and `functions` folders instead, each holding only routines of that kind, with the same overload-aware keys and object filter. Expanded folders carry over when the option is switched either way.

Co-authored-by: boenkkk <[email protected]>
2026-11-09 18:05:59 +08:00
Qing f3f9fdb1ad fix(run): drop the leftover vue kind from the category table (#2302)
The vue run-configuration kind never shipped upstream — detection is gone
and no type registers it. Its KIND_CATEGORIES row (and the test table row)
are dead data; the plugin-era dev-server story is covered by plain npm
configurations with stable ids.
2026-11-09 18:01:46 +08:00
arookieofc 687471c19e fix(database): table editor focus when the tab opens targets the editor host (#2307) (#2318)
The editor area focuses its own [data-editor-focus] host when a table tab
opens; dbTableEditorFocus only set when focus landed inside
[data-db-table-editor], so Go to Column / Submit / Revert stayed disabled
until a cell was clicked. Treat host focus that wraps a table editor as
table-editor focus too.
2026-11-09 17:58:29 +08:00
yoo hyeong chanтаarookieofc a46d873f6c feat(java): share JDT LS across builds in a project window (#2272)
* feat(java): share JDT LS across builds in a project window

* fix(java): wait for JDT restart before launch requests

* fix(host): give relay final replies ten seconds of EOF grace

relay::tests::final_responses_keep_flowing_after_input_eof flakes on
Windows CI: the target writes one byte per second for seven seconds
after input EOF, but the relay only waits five idle seconds, so a
slow first byte makes the relay return with nothing received.

Raise EOF_GRACE to ten seconds and update the companion test's
server wait and elapsed bound to match.

Refs #2272 (Windows CI failure)

---------

Co-authored-by: arookieofc <[email protected]>
2026-11-09 17:53:59 +08:00
Emanyzwwwтаemanyzwww 5d3432a000 fix(welcome): name the platform's file manager, not Finder (#2265)
On Windows and Linux several places still named macOS's Finder: the recent-project row menu (Show in Finder), Settings › Version Control › Confirmation › When patch is created, the question after a patch is saved, and the reveal error. The wording was an English literal at each call site, one place sniffed the user agent, and the catalogs only had Finder's text. Shared helpers in src/platform/fileManager.ts now name Finder / Explorer / Files from the platform info, and the project view's Reveal action, the editor tab menu, the project tree menu, the welcome page and the patch flow use them, with whole-sentence catalog entries so each locale can translate them.

Co-authored-by: emanyzwww <[email protected]>
2026-11-09 17:51:48 +08:00
ppxb 16ebb6fde8 feat(run): import JetBrains Go Application and Go Test configurations (#2309) 2026-11-09 17:49:59 +08:00
l0ng-ai 0e673c206a fix(editor): keep the saved layout when a session restore meets open tabs (#2325)
A session restore that lands after tabs were already opened (a file launched into LightEdit while the window was still restoring, or a file opened from the CLI into a project window during startup) appended every restored tab to the current pane: saved splits collapsed into one pane, restored pinned tabs landed after unpinned ones, a pane could hold several preview tabs, and the tab limit was skipped. The restore now starts from the saved state and reopens the live tabs into it through the normal tab rules (pin order, one preview per pane, tab limit without evicting the live tabs), keeping their slots and line/column targets; the launched tab ends up active and focused in the saved active pane. An empty window still takes the saved layout as is.

Refs #2229
2026-11-09 17:42:23 +08:00
arookieofc 2680ba8463 fix(agents): notify subscribers when a session report changes the cached provider config (#2308)
* fix(java): pass m2e an effective settings file carrying the configured local repository (#1739)

m2e resolves the local repository from the Maven settings XML, never from
-Dmaven.repo.local, so JDTLS imports kept downloading into ~/.m2/repository
even when the IDE's own mvn runs honored the configured path. When a local
repository is configured but the user settings lack <localRepository>, derive
an effective settings file under <root>/.openidea/ and pass it as
java.configuration.maven.userSettings. Settings that already declare
<localRepository> are passed through untouched.

* fix(agents): notify subscribers when a session report changes the cached provider config (#1490)

Session reports (session/new, session/load, turn updates) and CLI discovery
funnel through Shared::remember_inner, which cached new model lists but never
emitted AgentEvent::Providers. The composer therefore kept showing a stale
model list until the next task's busy-to-idle refresh. Emit Providers when the
cache actually changes; unchanged reports stay silent, and the cache lock is
released before invoking the sink. fetch_settings' unconditional emit is now
covered by remember_discovered and removed.
2026-11-09 17:39:15 +08:00
arookieofc 660587a6fe fix(java): list JDT .classpath libraries and the JDK for manifest-less projects (#2300) (#2304)
* fix(java): list JDT .classpath libraries and the JDK for manifest-less projects (#2300)

External Libraries was empty for a pure-Java project (only .classpath /
.idea/libraries, no pom.xml or build.gradle):

- jdk_groups returned early without a build manifest, so even a
  configured JDK never appeared. It now also treats .classpath, .project,
  .idea, a configured JDK and declared source roots as Java markers.
- The JDT model was never a source of libraries. classpath_groups parses
  each module's .classpath kind="lib" entries (sourcepath preferred when
  it exists) into a per-module group, discovered through the same module
  scan the other ecosystems use.

Adds quick-xml to ide-sdk (already used by ide-run / ide-host) and the
.classpath file to the External Libraries refresh triggers.

* chore: regenerate bindings for classpath library kind
2026-11-09 17:32:07 +08:00
59 змінених файлів з 2306 додано та 205 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -4746,6 +4746,7 @@ dependencies = [
"ide-run",
"ide-vfs",
"ignore",
"quick-xml 0.42.0",
"serde",
"serde_json",
"specta",
+10 -1
Переглянути файл
@@ -169,8 +169,10 @@ impl Shared {
let commands = config::commands_of(&json!({ "availableCommands": commands }), &spec.id);
let options = config::options_of(&json!({ "configOptions": options }));
let _ = tokio::task::spawn_blocking(move || {
// Notifies subscribers itself when the discovery
// changed the cached config; unchanged results
// stay silent.
shared.remember_discovered(&spec.id, &options, &commands);
shared.emit(AgentEvent::Providers);
})
.await;
}
@@ -253,6 +255,13 @@ impl Shared {
{
tracing::warn!("saving agent settings: {e}");
}
// The cached provider config actually changed (a session report, discovery,
// or a turn update): tell subscribers to re-list, so a changed model list
// reaches the composer without waiting for the next task (#1490). Unchanged
// reports stay silent, so routine session traffic emits nothing. The cache
// lock is released first; the sink never runs under it.
drop(cache);
self.emit(AgentEvent::Providers);
}
}
+43
Переглянути файл
@@ -2146,6 +2146,49 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
assert!(probe.error.is_none());
}
/// A session report that changes the cached provider config notifies subscribers,
/// so the composer re-lists models without waiting for the next task (#1490).
/// Reports that change nothing stay silent.
#[tokio::test(flavor = "multi_thread")]
async fn remembered_config_changes_notify_subscribers_once() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
events.lock().clear();
let reported = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
] }));
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a first report changing the cache notifies subscribers"
);
events.lock().clear();
// The same report again: the cache is unchanged, so subscribers hear nothing.
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
// A changed model list notifies again, and providers() serves the new list.
let updated = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
] }));
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a changed model list notifies subscribers"
);
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
let new = || NewAgentTask {
+22
Переглянути файл
@@ -896,6 +896,8 @@ pub struct JavaSettings {
/// Extra JVM options for the Java language server (jdtls), space-separated
/// (VS Code's `java.jdt.ls.vmargs`).
pub jdtls_vm_args: String,
/// Share one JDT LS across builds in an ordinary project window; other windows remain separate.
pub jdtls_shared: bool,
/// Build Tools › Maven.
pub maven: MavenSettings,
/// Build Tools › Gradle.
@@ -1477,6 +1479,26 @@ mod maven_linkage_tests {
}
}
#[cfg(test)]
mod java_settings_tests {
use super::*;
#[test]
fn shared_jdtls_defaults_off_and_round_trips() {
for old in [r#"{}"#, r#"{"jdk":"/jdk"}"#] {
let java: JavaSettings = serde_json::from_str(old).unwrap();
assert!(!java.jdtls_shared);
}
for shared in [false, true] {
let java = JavaSettings { jdtls_shared: shared, ..JavaSettings::default() };
let json = serde_json::to_value(&java).unwrap();
assert_eq!(json["jdtlsShared"], serde_json::json!(shared));
assert_eq!(serde_json::from_value::<JavaSettings>(json).unwrap(), java);
}
assert!(serde_json::from_str::<JavaSettings>(r#"{"jdtlsShared":"true"}"#).is_err());
}
}
#[cfg(test)]
mod gradle_settings_tests {
use super::*;
+1 -1
Переглянути файл
@@ -92,7 +92,7 @@ pub struct SequenceInfo {
pub data_type: String,
}
/// A schema's routines and sequences (the tree's `routines` / `sequences` folders).
/// A schema's routines (procedures and functions) and sequences.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbSchemaObjects")]
+11 -1
Переглянути файл
@@ -83,7 +83,7 @@ impl Host {
let opening = self.opening(window);
let _opening = opening.lock();
// Reject a damaged manifest before replacing the currently open project.
ide_workspace::workspace::Workspace::load(&root)?;
let is_workspace = ide_workspace::workspace::Workspace::load(&root)?.is_some();
// The window reloaded (or asked again) for the project it already has: keep
// it, with its warm index, language servers and unsaved documents.
if let Ok(current) = self.project(window)
@@ -137,6 +137,16 @@ impl Host {
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(extra_roots.clone());
let settings = Arc::new(settings);
{
let settings = settings.clone();
// Workspace members have independent settings; target servers have their own path mappings.
lsp.set_jdtls_shared_hook(Box::new(move || {
let effective = settings.effective();
!is_workspace
&& effective.languages.java.jdtls_shared
&& effective.language_server_targets.get("java").is_none_or(|target| target.target.is_empty())
}));
}
{
let settings = settings.clone();
let root = root.clone();
+4 -4
Переглянути файл
@@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const EOF_GRACE: Duration = Duration::from_secs(5);
const EOF_GRACE: Duration = Duration::from_secs(10);
/// `<host> <port>` from the arguments after `--connect`.
pub fn parse_args(args: &[String]) -> Result<(String, u16), String> {
@@ -25,7 +25,7 @@ pub fn parse_args(args: &[String]) -> Result<(String, u16), String> {
/// Connects to `host:port`, copies `input` to it and its replies to `output`, and returns when
/// the target is done (the copy of `input` may still be blocked: the caller exits). Fails only
/// when the connection can't be opened. An input EOF allows five idle seconds for a final reply.
/// when the connection can't be opened. An input EOF allows ten idle seconds for a final reply.
pub fn relay(host: &str, port: u16, mut input: impl Read + Send + 'static, mut output: impl Write) -> io::Result<()> {
let mut from_target = connect(host, port)?;
from_target.set_read_timeout(Some(Duration::from_millis(100)))?;
@@ -140,11 +140,11 @@ mod tests {
let mut request = Vec::new();
socket.read_to_end(&mut request).unwrap();
// Remain open after seeing EOF, like an idle keep-alive server.
wait.recv_timeout(Duration::from_secs(10)).unwrap();
wait.recv_timeout(Duration::from_secs(15)).unwrap();
});
let start = Instant::now();
relay("127.0.0.1", port, io::empty(), io::sink()).unwrap();
assert!(start.elapsed() < Duration::from_secs(8));
assert!(start.elapsed() < Duration::from_secs(13));
done.send(()).unwrap();
server.join().unwrap();
}
+48 -20
Переглянути файл
@@ -627,7 +627,11 @@ impl LspManager {
.docs
.lock()
.values()
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
.filter(|d| {
d.language.as_str() == "java"
&& d.path.is_absolute()
&& d.servers.iter().any(|a| a.server.id == server.id)
})
.map(|d| crate::uri::path_to_uri_string(&d.path))
.collect();
if uris.is_empty() {
@@ -652,26 +656,50 @@ impl LspManager {
/// started if needed and waited for.
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
let java = LanguageId::new("java");
let server = self
.servers_for(&java, path)
.into_iter()
.find(|s| s.name == SERVER)
.ok_or_else(|| IdeError::unavailable("no Java language server (jdtls) is configured"))?;
self.ensure_started(&server);
match cancellable_wait(cancel, server.wait_ready(READY_TIMEOUT)).await? {
Some(run) => Ok((server, run)),
None => {
let status = server.status();
Err(IdeError::unavailable(match status {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured | ide_core::event::ServerStatus::Crashed => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}))
let deadline = tokio::time::Instant::now() + READY_TIMEOUT;
loop {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let server = self
.servers_for(&java, path)
.into_iter()
.find(|s| s.name == SERVER)
.ok_or_else(|| IdeError::unavailable("no Java language server (jdtls) is configured"))?;
self.ensure_started(&server);
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if let Some(run) = cancellable_wait(cancel, server.wait_ready(remaining)).await? {
return Ok((server, run));
}
let status = server.status();
if !matches!(
status,
ide_core::event::ServerStatus::Missing
| ide_core::event::ServerStatus::Misconfigured
| ide_core::event::ServerStatus::Crashed
) && tokio::time::Instant::now() < deadline
&& let Ok(_restart) =
cancellable_wait(cancel, tokio::time::timeout_at(deadline, self.reconfigure_lock.lock())).await?
{
// A restart publishes Down while reaping its old JVM. Its successor may
// also have a new identity after changing the shared workspace.
if let Some(current) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER)
&& current.root.is_dir()
&& (current.id != server.id || current.is_starting() || current.running().is_some())
{
continue;
}
}
let status = server.status();
return Err(IdeError::unavailable(match status {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured | ide_core::event::ServerStatus::Crashed => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}));
}
}
+233 -45
Переглянути файл
@@ -175,6 +175,20 @@ impl DocSnap {
/// Receives the folders outside the project that servers want watched.
pub type WatchRootsFn = dyn Fn(Vec<PathBuf>) + Send + Sync;
pub type JdtlsSharedFn = dyn Fn() -> bool + Send + Sync;
#[derive(Default)]
struct JdtlsWorkspace {
initialized: bool,
shared: bool,
roots: Vec<PathBuf>,
transitioning: bool,
}
fn is_local_jdtls(config: &LanguageServerConfig) -> bool {
config.name == "jdtls" && config.target_key.is_none() && config.target.is_none()
}
pub struct LspManager {
me: Weak<LspManager>,
project_root: PathBuf,
@@ -195,6 +209,9 @@ pub struct LspManager {
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
excludes_hook: RwLock<Option<Arc<external_project::ExcludesFn>>>,
watch_roots_hook: RwLock<Option<Arc<WatchRootsFn>>>,
jdtls_shared_hook: RwLock<Option<Arc<JdtlsSharedFn>>>,
jdtls_workspace: Mutex<JdtlsWorkspace>,
reconfigure_lock: tokio::sync::Mutex<()>,
shutting_down: AtomicBool,
execution_allowed: AtomicBool,
java_usages_warned: AtomicBool,
@@ -402,6 +419,9 @@ impl LspManager {
candidates_hook: RwLock::new(None),
excludes_hook: RwLock::new(None),
watch_roots_hook: RwLock::new(None),
jdtls_shared_hook: RwLock::new(None),
jdtls_workspace: Mutex::new(Default::default()),
reconfigure_lock: tokio::sync::Mutex::new(()),
shutting_down: AtomicBool::new(false),
execution_allowed: AtomicBool::new(true),
java_usages_warned: AtomicBool::new(false),
@@ -416,7 +436,56 @@ impl LspManager {
// ---- server lookup & lifecycle ----
pub fn set_content_roots(&self, roots: Vec<PathBuf>) {
*self.content_roots.write() = roots;
let changed = {
let mut current = self.content_roots.write();
let changed = *current != roots;
*current = roots;
changed
};
if changed
&& self.desired_jdtls_workspace().0
&& let Some(me) = self.me.upgrade()
{
me.reconfigure_soon();
}
}
/// Shares JDT LS within this manager; callers reconfigure after the hook's value changes.
pub fn set_jdtls_shared_hook(&self, hook: Box<JdtlsSharedFn>) {
*self.jdtls_shared_hook.write() = Some(Arc::from(hook));
}
fn desired_jdtls_workspace(&self) -> (bool, Vec<PathBuf>) {
let shared = self.jdtls_shared_hook.read().as_ref().is_some_and(|hook| hook());
let mut roots = Vec::new();
if shared {
roots.push(self.project_root.clone());
for root in self.content_roots.read().iter() {
if root.is_absolute() && root.is_dir() && !roots.contains(root) {
roots.push(root.clone());
}
}
}
(shared, roots)
}
fn jdtls_workspace_state(&self) -> parking_lot::MutexGuard<'_, JdtlsWorkspace> {
let mut state = self.jdtls_workspace.lock();
if !state.initialized {
(state.shared, state.roots) = self.desired_jdtls_workspace();
state.initialized = true;
}
state
}
fn server_workspace_roots(&self, server: &Server) -> Vec<PathBuf> {
if is_local_jdtls(&server.config) {
let state = self.jdtls_workspace_state();
if state.shared {
return state.roots.clone();
}
}
vec![server.root.clone()]
}
fn project_root_for(&self, path: &Path) -> PathBuf {
@@ -431,16 +500,21 @@ impl LspManager {
}
fn server_for(&self, cfg: &LanguageServerConfig, language: &LanguageId, path: &Path) -> Arc<Server> {
let shared = is_local_jdtls(cfg).then(|| self.jdtls_workspace_state());
let mut servers = self.servers.lock();
let root = launch::find_root(&self.project_root_for(path), path, &cfg.root_markers).unwrap_or_else(|| {
// Outside the project (library sources, …): reuse a running instance.
servers
.iter()
.filter(|s| s.name == cfg.name && s.config.target_key == cfg.target_key)
.min_by_key(|s| s.root != self.project_root)
.map(|s| s.root.clone())
.unwrap_or_else(|| self.project_root.clone())
});
let root = if shared.as_ref().is_some_and(|state| state.shared) {
self.project_root.clone()
} else {
launch::find_root(&self.project_root_for(path), path, &cfg.root_markers).unwrap_or_else(|| {
// Outside the project (library sources, …): reuse a running instance.
servers
.iter()
.filter(|s| s.name == cfg.name && s.config.target_key == cfg.target_key)
.min_by_key(|s| s.root != self.project_root)
.map(|s| s.root.clone())
.unwrap_or_else(|| self.project_root.clone())
})
};
if let Some(s) =
servers.iter().find(|s| s.name == cfg.name && s.root == root && s.config.target_key == cfg.target_key)
{
@@ -490,6 +564,7 @@ impl LspManager {
/// to the open documents (and start them). Also attaches servers newly
/// enabled in settings.
fn attach_fallbacks(&self) {
let _gate = self.injections.gate.lock();
let open: Vec<(DocId, LanguageId, PathBuf)> = self
.docs
.lock()
@@ -538,6 +613,27 @@ impl LspManager {
if self.shutting_down.load(Ordering::Acquire) || !self.execution_allowed.load(Ordering::Acquire) {
return;
}
let workspace = is_local_jdtls(&server.config).then(|| self.jdtls_workspace_state());
if let Some(state) = &workspace {
if state.transitioning || !self.servers.lock().iter().any(|s| s.id == server.id) {
return;
}
let (shared, roots) = self.desired_jdtls_workspace();
if state.shared != shared || (shared && state.roots != roots) {
if let Some(me) = self.me.upgrade() {
me.reconfigure_soon();
}
return;
}
}
let startup = if is_local_jdtls(&server.config) {
match server.startup_lock.clone().try_lock_owned() {
Ok(guard) => Some(guard),
Err(_) => return,
}
} else {
None
};
// `begin_start` only claims Idle servers, so a claimed server is never a
// live one. Its root is the process's working directory: starting with
// one deleted from disk fails (`os error 267` on Windows). Such a
@@ -553,7 +649,10 @@ impl LspManager {
return;
}
let server = server.clone();
self.runtime.spawn(async move { me.run_instance(server, generation).await });
self.runtime.spawn(async move {
let _startup = startup;
me.run_instance(server, generation).await;
});
}
async fn run_instance(self: Arc<Self>, server: Arc<Server>, generation: u64) {
@@ -561,6 +660,7 @@ impl LspManager {
let handler = Arc::new(handler::ClientHandler::new(self.me.clone(), server.clone(), generation));
let me = self.clone();
let tail = server.clone();
let launch_cancel = cancel.clone();
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
// servers may take a while to start listening.
let launched = tokio::task::spawn_blocking(move || {
@@ -568,17 +668,17 @@ impl LspManager {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
let mut cfg = me.configured(&tail);
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
if !me.execution_allowed.load(Ordering::Acquire) || launch_cancel.is_cancelled() {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
tail.set_effective_config(generation, cfg.clone());
let prepare = me.prepare_hook.read().clone();
if cfg.target.is_none()
&& !cancel.is_cancelled()
&& !launch_cancel.is_cancelled()
&& me.launcher.available(&cfg, &tail.root)
&& let Some(prepare) = prepare
{
prepare(&cfg, &tail.root, &cancel);
prepare(&cfg, &tail.root, &launch_cancel);
cfg = me.configured(&tail);
}
tail.set_effective_config(generation, cfg.clone());
@@ -588,7 +688,7 @@ impl LspManager {
let missing = cfg.target.is_none() && !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
}
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
if !me.execution_allowed.load(Ordering::Acquire) || launch_cancel.is_cancelled() {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
me.launcher.launch_resolved(
@@ -596,7 +696,7 @@ impl LspManager {
&root,
handler,
Box::new(move |line| tail.push_stderr(generation, line)),
&cancel,
&launch_cancel,
)
})
.await
@@ -605,7 +705,7 @@ impl LspManager {
let peer = match launched {
Ok((peer, binary)) => {
if !server.set_resolved_binary(generation, binary) {
peer.kill();
Self::kill_peer(&server, &peer).await;
return;
}
peer
@@ -662,9 +762,14 @@ impl LspManager {
init["initializationOptions"]["triggerFiles"] = json!([uri::path_to_uri_string(&path)]);
}
}
let result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, None))
.await
.unwrap_or(Err(RpcError::Timeout));
let result = tokio::select! {
biased;
() = cancel.cancelled() => {
Self::kill_peer(&server, &peer).await;
return;
}
result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, Some(cancel.clone()))) => result.unwrap_or(Err(RpcError::Timeout)),
};
let caps = match result {
Ok(result) => {
if let Some(info) = result.get("serverInfo") {
@@ -681,7 +786,7 @@ impl LspManager {
// The server is exiting: let it, so the crash report has its exit code and last output.
let _ = tokio::time::timeout(Duration::from_secs(3), peer.closed()).await;
}
peer.kill();
Self::kill_peer(&server, &peer).await;
// Treated like a crash so transient failures retry with backoff.
self.spawn_supervisor(server, generation, peer);
return;
@@ -690,7 +795,7 @@ impl LspManager {
let run =
Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)), watchers: Default::default() };
if !server.set_initializing(run.clone()) {
peer.kill();
Self::kill_peer(&server, &peer).await;
return;
}
if let Err(e) = peer.notify("initialized", json!({})) {
@@ -709,24 +814,30 @@ impl LspManager {
// Publish readiness and (re)open attached documents atomically w.r.t. did_change.
let mut reopened = Vec::new();
{
let ready = {
let mut docs = self.docs.lock();
if !server.mark_ready(generation, run.clone()) {
drop(docs);
peer.kill();
return;
}
let open_close = run.caps.read().open_close;
for (id, d) in docs.iter_mut() {
let params = d.did_open_params();
for a in d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation)) {
if open_close && let Err(e) = peer.notify("textDocument/didOpen", params.clone()) {
tracing::debug!("{}: didOpen: {e}", server.name);
false
} else {
let open_close = run.caps.read().open_close;
for (id, d) in docs.iter_mut() {
let params = d.did_open_params();
for a in
d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation))
{
if open_close && let Err(e) = peer.notify("textDocument/didOpen", params.clone()) {
tracing::debug!("{}: didOpen: {e}", server.name);
}
a.opened_gen = Some(generation);
reopened.push(*id);
}
a.opened_gen = Some(generation);
reopened.push(*id);
}
true
}
};
if !ready {
Self::kill_peer(&server, &peer).await;
return;
}
for doc in reopened {
self.schedule_pull(doc, Some(&server), Duration::ZERO);
@@ -767,7 +878,6 @@ impl LspManager {
fn initialize_params(&self, server: &Server) -> Value {
let root_uri = uri::path_to_uri(&server.root);
let name = server.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
let cfg = server.effective_config();
let mut init_options =
cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or(Value::Null);
@@ -776,11 +886,24 @@ impl LspManager {
init_options = json!({});
}
init_options["settings"] = handler::all_settings(&cfg);
let shared = is_local_jdtls(&server.config) && self.jdtls_workspace_state().shared;
if shared {
init_options["workspaceFolders"] = json!(
self.server_workspace_roots(server)
.iter()
.map(|root| uri::path_to_uri_string(root))
.collect::<Vec<_>>()
);
}
let triggers: Vec<_> = self
.docs
.lock()
.values()
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
.filter(|d| {
d.language.as_str() == "java"
&& d.path.is_absolute()
&& d.servers.iter().any(|a| a.server.id == server.id)
})
.map(|d| uri::path_to_uri_string(&d.path))
.collect();
if !triggers.is_empty() && init_options.get("triggerFiles").is_none() {
@@ -794,7 +917,7 @@ impl LspManager {
"locale": "en",
"rootPath": server.root.to_string_lossy(),
"rootUri": root_uri,
"workspaceFolders": [{ "uri": root_uri, "name": name }],
"workspaceFolders": self.workspace_folders(server),
"capabilities": caps::client_capabilities(),
"trace": "off",
});
@@ -811,8 +934,16 @@ impl LspManager {
}
pub(crate) fn workspace_folders(&self, server: &Server) -> Value {
let name = server.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
json!([{ "uri": uri::path_to_uri(&server.root), "name": name }])
json!(
self.server_workspace_roots(server)
.iter()
.map(|root| {
let name =
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
json!({"uri": uri::path_to_uri(root), "name": name})
})
.collect::<Vec<_>>()
)
}
pub(crate) fn sink(&self) -> &SharedSink {
@@ -862,6 +993,7 @@ impl LspManager {
/// Opens a read-only virtual document (`jdt://…`) on the server that
/// returned its URI (`didOpen` only: it is never changed or saved).
pub fn did_open_virtual(&self, doc: DocId, uri: &str, language: &LanguageId, version: u32, text: &str) {
let _gate = self.injections.gate.lock();
if self.docs.lock().contains_key(&doc) {
self.close_injections(doc);
self.close_document(doc);
@@ -2450,15 +2582,18 @@ impl LspManager {
.into_iter()
.flat_map(|(paths, change)| paths.iter().map(move |p| (p, change)));
let watchers = run.watchers.read();
let roots = self.server_workspace_roots(&s);
let changes: Vec<(&PathBuf, Change)> = if watchers.is_empty() {
let languages = s.languages();
all.filter(|(p, change)| {
p.starts_with(&s.root) && languages.contains(&self.languages.detect(p, None)) && send(p, *change)
roots.iter().any(|root| p.starts_with(root))
&& languages.contains(&self.languages.detect(p, None))
&& send(p, *change)
})
.collect()
} else {
all.chain(excluded_dirs.iter().map(|p| (p, Change::Created)))
.filter(|(p, change)| watchers.wants(&s.root, p, *change) && send(p, *change))
.filter(|(p, change)| roots.iter().any(|root| watchers.wants(root, p, *change)) && send(p, *change))
.collect()
};
drop(watchers);
@@ -3036,7 +3171,8 @@ impl LspManager {
}
}
if allowed && !previous {
for server in self.servers.lock().iter() {
let servers = self.servers.lock().clone();
for server in &servers {
server.reset_for_restart();
self.ensure_started(server);
}
@@ -3053,11 +3189,13 @@ impl LspManager {
}
pub async fn reconfigure(&self) {
let _reconfigure = self.reconfigure_lock.lock().await;
if !self.execution_allowed.load(Ordering::Acquire) {
let servers = self.servers.lock().clone();
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
return;
}
self.reconfigure_jdtls_workspace().await;
self.stop_unlisted().await;
let Some(me) = self.me.upgrade() else { return };
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
@@ -3120,6 +3258,39 @@ impl LspManager {
self.injection_providers_changed();
}
async fn reconfigure_jdtls_workspace(&self) {
let (shared, roots) = self.desired_jdtls_workspace();
let retired = {
// Opens attach atomically with root selection; no document can acquire an old
// instance between removing the registry entries and detaching its documents.
let _gate = self.injections.gate.lock();
let mut state = self.jdtls_workspace_state();
if state.shared == shared && (!shared || state.roots == roots) {
return;
}
state.transitioning = true;
state.shared = shared;
state.roots = roots;
let mut servers = self.servers.lock();
let retired: Vec<_> = servers.iter().filter(|s| is_local_jdtls(&s.config)).cloned().collect();
servers.retain(|s| !is_local_jdtls(&s.config));
for doc in self.docs.lock().values_mut() {
doc.servers.retain(|a| !is_local_jdtls(&a.server.config));
}
retired
};
for server in &retired {
self.stop_instance(server, true).await;
}
self.forget(&retired);
self.jdtls_workspace.lock().transitioning = false;
self.attach_fallbacks();
let pending: Vec<_> = self.servers.lock().iter().filter(|s| is_local_jdtls(&s.config)).cloned().collect();
for server in pending {
self.ensure_started(&server);
}
}
/// Detaches fallbacks shadowed by enabled servers and instances whose target
/// no longer matches the document's language. Stop them once unused.
async fn detach_shadowed_servers(&self) {
@@ -3255,6 +3426,7 @@ impl LspManager {
}
pub async fn restart(&self, server: ide_core::ServerId) -> IdeResult<()> {
let _reconfigure = self.reconfigure_lock.lock().await;
let s = self
.servers
.lock()
@@ -3282,7 +3454,12 @@ impl LspManager {
/// Gracefully stops the current instance (`shutdown` + `exit`, then kill).
async fn stop_instance(&self, server: &Arc<Server>, final_stop: bool) {
let Some(run) = server.begin_stop(&self.sink, final_stop) else { return };
let Some(run) = server.begin_stop(&self.sink, final_stop) else {
if is_local_jdtls(&server.config) {
let _startup = server.startup_lock.lock().await;
}
return;
};
let peer = run.peer.clone();
// A server we connected to without starting it (an open Godot editor) is not
// ours to shut down: only the connection closes.
@@ -3302,13 +3479,24 @@ impl LspManager {
peer.kill();
let _ = tokio::time::timeout(Duration::from_secs(2), peer.closed()).await;
}
peer.kill();
Self::kill_peer(server, &peer).await;
if is_local_jdtls(&server.config) {
let _startup = server.startup_lock.lock().await;
}
server.end_stop(run.generation, &self.sink);
self.file_watch_roots_changed();
}
async fn kill_peer(server: &Server, peer: &ide_jsonrpc::Peer) {
peer.kill();
if is_local_jdtls(&server.config) && peer.pid().is_some() {
peer.exited().await;
}
}
pub async fn shutdown_all(&self) {
self.shutting_down.store(true, Ordering::Release);
let _reconfigure = self.reconfigure_lock.lock().await;
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
}
+7
Переглянути файл
@@ -119,6 +119,8 @@ pub struct Server {
phase_notify: Notify,
transient: Mutex<HashMap<PathBuf, Transient>>,
pub java_build_lock: Arc<tokio::sync::Mutex<()>>,
/// JDT retirement waits for launch and initialization cleanup, even before `Ready`.
pub startup_lock: Arc<tokio::sync::Mutex<()>>,
pub java_autobuild_suspended: std::sync::atomic::AtomicBool,
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
pub external_diagnostics: std::sync::atomic::AtomicBool,
@@ -158,6 +160,7 @@ impl Server {
phase_notify: Notify::new(),
transient: Mutex::new(HashMap::new()),
java_build_lock: Arc::new(tokio::sync::Mutex::new(())),
startup_lock: Arc::new(tokio::sync::Mutex::new(())),
java_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
external_project: tokio::sync::Mutex::new(Default::default()),
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
@@ -269,6 +272,10 @@ impl Server {
}
}
pub fn is_starting(&self) -> bool {
matches!(self.state.lock().conn, Conn::Starting)
}
/// The instance told `initialized`, ready or not.
pub fn instance(&self) -> Option<Running> {
self.running().or_else(|| self.initializing.lock().clone())
+477 -7
Переглянути файл
@@ -35,6 +35,8 @@ struct MockState {
responder: Mutex<Option<Responder>>,
/// Holds the handling of notifications of this method until the gate opens.
held: Mutex<Option<(String, Arc<Gate>)>>,
initialize_gate: Mutex<Option<Arc<Gate>>>,
launch_gate: Mutex<Option<Arc<Gate>>>,
peer: Mutex<Option<Peer>>,
}
@@ -73,7 +75,9 @@ fn utf16_to_byte(text: &str, line: u64, col: u64) -> usize {
text.len()
}
struct MockHandler(Arc<MockState>);
type MockConnection = Mutex<Option<Peer>>;
struct MockHandler(Arc<MockState>, std::sync::Weak<MockConnection>);
impl Handler for MockHandler {
fn on_notification(&self, method: &str, params: Value) {
@@ -118,8 +122,14 @@ impl Handler for MockHandler {
s.docs.lock().remove(&uri);
}
"exit" => {
if let Some(p) = s.peer.lock().take() {
p.kill();
if let Some(connection) = self.1.upgrade()
&& let Some(peer) = connection.lock().take()
{
peer.kill();
}
let mut latest = s.peer.lock();
if latest.as_ref().is_some_and(Peer::is_closed) {
*latest = None;
}
}
_ => {}
@@ -131,7 +141,13 @@ impl Handler for MockHandler {
let s = &self.0;
s.requests.lock().push((method.to_owned(), params.clone()));
match method {
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
"initialize" => {
let gate = s.initialize_gate.lock().take();
if let Some(gate) = gate {
gate.hold();
}
Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } }))
}
"shutdown" => Ok(Value::Null),
_ => {
if let Some(error) = s.errors.lock().get(method).cloned() {
@@ -150,6 +166,7 @@ impl Handler for MockHandler {
#[derive(Default)]
struct MockLauncher {
servers: Mutex<HashMap<String, Arc<MockState>>>,
connections: Mutex<Vec<Arc<MockConnection>>>,
}
impl MockLauncher {
@@ -186,10 +203,18 @@ impl Launcher for MockLauncher {
state.docs.lock().clear();
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
let server = Peer::connect(sr, sw, Arc::new(MockHandler(state.clone())));
let connection = Arc::new(Mutex::new(None));
let server = Peer::connect(sr, sw, Arc::new(MockHandler(state.clone(), Arc::downgrade(&connection))));
*connection.lock() = Some(server.clone());
self.connections.lock().push(connection);
*state.peer.lock() = Some(server);
let (cr, cw) = tokio::io::split(client_io);
Ok(Peer::connect(cr, cw, handler))
let client = Peer::connect(cr, cw, handler);
let gate = state.launch_gate.lock().take();
if let Some(gate) = gate {
gate.hold();
}
Ok(client)
}
}
@@ -420,6 +445,451 @@ async fn linked_projects_initialize_separate_language_server_roots() {
h.mgr.shutdown_all().await;
}
fn java_siblings(h: &Harness) -> Vec<PathBuf> {
["first", "second"]
.into_iter()
.map(|name| {
let root = h.root.join(name);
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("mock.toml"), "").unwrap();
let path = root.join("Main.java");
std::fs::write(&path, "class Main {}").unwrap();
path
})
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_is_opt_in_and_keeps_module_requests_on_one_instance() {
for shared in [false, true] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(move || shared));
let paths = java_siblings(&h);
std::thread::scope(|scope| {
for path in &paths {
scope.spawn(|| h.mgr.did_open(DocId::next(), path, &h.lang, 1, "class Main {}"));
}
});
let state = h.launcher.state("jdtls");
let count = if shared { 1 } else { 2 };
eventually(|| state.requested("initialize").len() == count).await;
assert_eq!(state.launches.load(Ordering::SeqCst), count);
assert_eq!(h.mgr.servers().len(), count);
for path in &paths {
h.mgr.java_classpath(path.parent().unwrap(), false, &Default::default()).await.unwrap();
}
let requests = state.requested("workspace/executeCommand");
let classpaths: Vec<_> = requests.iter().filter(|r| r["command"] == "java.project.getClasspaths").collect();
assert_eq!(classpaths.len(), 2);
for path in &paths {
assert!(classpaths.iter().any(|r| r["arguments"][0] == uri_of(path.parent().unwrap())));
}
if shared {
let init = &state.requested("initialize")[0];
assert_eq!(init["rootUri"], uri_of(&h.root));
assert_eq!(init["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root)]));
}
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_toggle_retires_old_instances_and_reopens_every_document() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
let paths = java_siblings(&h);
for path in &paths {
h.mgr.did_open(DocId::next(), path, &h.lang, 1, "class Main {}");
}
let state = h.launcher.state("jdtls");
eventually(|| state.requested("initialize").len() == 2).await;
eventually(|| {
paths
.iter()
.all(|path| state.notified("textDocument/didOpen").iter().any(|v| v["textDocument"]["uri"] == uri_of(path)))
})
.await;
let old: Vec<_> = h.mgr.servers().into_iter().map(|s| s.id).collect();
shared.store(true, Ordering::SeqCst);
h.mgr.reconfigure().await;
eventually(|| state.launches.load(Ordering::SeqCst) == 3 && state.docs.lock().len() == 2).await;
assert_eq!(h.mgr.servers().len(), 1);
for id in old {
assert!(
h.events
.lock()
.iter()
.any(|event| matches!(event, IdeEvent::LanguageServerRemoved {server} if *server == id))
);
}
shared.store(false, Ordering::SeqCst);
h.mgr.reconfigure().await;
eventually(|| state.launches.load(Ordering::SeqCst) == 5).await;
assert_eq!(h.mgr.servers().len(), 2);
eventually(|| {
paths.iter().all(|path| {
state.notified("textDocument/didOpen").iter().filter(|v| v["textDocument"]["uri"] == uri_of(path)).count()
== 3
})
})
.await;
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_cancels_a_retiring_initialize_before_starting_its_replacement() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.initialize_gate.lock() = Some(gate.clone());
let path = java_siblings(&h).remove(0);
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
eventually(|| gate.entered()).await;
let old = state.peer();
shared.store(true, Ordering::SeqCst);
let switched = tokio::time::timeout(Duration::from_secs(2), h.mgr.reconfigure()).await;
let closed_before_response = old.is_closed();
gate.open();
switched.expect("initialize cancellation must not wait for its response");
eventually(|| state.requested("initialize").len() == 2).await;
assert!(closed_before_response, "the old transport must close before its initialize response is released");
assert_eq!(h.mgr.servers().len(), 1);
assert_eq!(h.mgr.servers()[0].root.as_ref(), h.root.as_path());
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn shared_java_waits_for_an_abandoned_launcher_before_replacing_the_workspace() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(|| true));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.launch_gate.lock() = Some(gate.clone());
h.open("Main.java", "class Main {}");
eventually(|| gate.entered()).await;
let old = state.peer();
let id = h.mgr.servers()[0].id;
let external = tempfile::tempdir().unwrap();
h.mgr.set_content_roots(vec![dunce::canonicalize(external.path()).unwrap()]);
eventually(|| h.mgr.servers().iter().all(|s| s.id != id)).await;
h.open("Another.java", "class Another {}");
let mut transition = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
let pending = tokio::time::timeout(Duration::from_millis(100), &mut transition).await.is_err();
let launches = state.launches.load(Ordering::SeqCst);
let old_alive = !old.is_closed();
gate.open();
assert!(pending, "retirement must wait for the launcher to return");
assert_eq!(launches, 1, "the retiring launcher still owns its peer");
assert!(old_alive);
transition.await.unwrap();
h.mgr.reconfigure().await;
eventually(|| state.launches.load(Ordering::SeqCst) == 2 && state.docs.lock().len() == 2).await;
assert!(old.is_closed());
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_classpath_waits_for_a_config_restart_that_is_reaping_startup() {
for (shared, failed) in [(false, false), (true, false), (false, true)] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let changed = changed.clone();
move || shared && changed.load(Ordering::SeqCst)
}));
h.mgr.set_config_hook(Box::new({
let changed = changed.clone();
move |cfg, _| {
let changed = changed.load(Ordering::SeqCst);
cfg.env.insert("MOCK_CONFIG_REVISION".into(), changed.to_string());
if failed && changed {
cfg.launch_error = Some("restart configuration error".into());
}
}
}));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.launch_gate.lock() = Some(gate.clone());
let path = java_siblings(&h).remove(0);
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
eventually(|| gate.entered()).await;
let old = h.mgr.servers()[0].id;
changed.store(true, Ordering::SeqCst);
let restarting = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
h.wait_status("jdtls", ServerStatus::Stopped).await;
let mut query = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.java_classpath(path.parent().unwrap(), false, &Default::default()).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut query).await;
gate.open();
restarting.await.unwrap();
let result = match early {
Ok(result) => result.unwrap(),
Err(_) => query.await.unwrap(),
};
if failed {
assert!(result.unwrap_err().message.contains("restart configuration error"));
} else {
assert!(result.is_ok(), "a configuration restart is transient: {result:?}");
assert_eq!(state.launches.load(Ordering::SeqCst), 2);
assert_eq!(h.mgr.servers()[0].id != old, shared);
}
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_classpath_restart_barrier_wait_remains_cancellable() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_config_hook(Box::new({
let changed = changed.clone();
move |cfg, _| {
cfg.env.insert("MOCK_CONFIG_REVISION".into(), changed.load(Ordering::SeqCst).to_string());
}
}));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.launch_gate.lock() = Some(gate.clone());
h.open("Main.java", "class Main {}");
eventually(|| gate.entered()).await;
changed.store(true, Ordering::SeqCst);
let restarting = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
h.wait_status("jdtls", ServerStatus::Stopped).await;
let cancel = CancellationToken::new();
let mut query = tokio::spawn({
let manager = h.mgr.clone();
let root = h.root.clone();
let cancel = cancel.clone();
async move { manager.java_classpath(&root, false, &cancel).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut query).await;
let waiting = early.is_err();
cancel.cancel();
let result = match early {
Ok(result) => Ok(result),
Err(_) => tokio::time::timeout(Duration::from_secs(1), query).await,
};
gate.open();
restarting.await.unwrap();
assert!(waiting, "the query must wait behind the restart barrier");
assert_eq!(result.unwrap().unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_classpath_does_not_retry_permanently_unavailable_servers() {
for missing in [false, true] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
if missing {
h.launcher.state("jdtls").missing.store(true, Ordering::SeqCst);
} else {
h.mgr.set_config_hook(Box::new(|cfg, _| {
cfg.launch_error = Some("permanent mock configuration error".into())
}));
}
let result =
tokio::time::timeout(Duration::from_secs(1), h.mgr.java_classpath(&h.root, false, &Default::default()))
.await
.expect("permanent failures must not incur the Java readiness timeout");
let error = result.unwrap_err();
assert!(error.message.contains(if missing { "not installed" } else { "permanent mock configuration error" }));
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn shared_java_external_roots_reach_initialization_queries_and_watches() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(|| true));
let external = tempfile::tempdir().unwrap();
let external = dunce::canonicalize(external.path()).unwrap();
h.mgr.set_content_roots(vec![external.clone(), external.clone(), h.root.clone()]);
let file = external.join("External.java");
std::fs::write(&file, "class External {}").unwrap();
h.mgr.did_open(DocId::next(), &file, &h.lang, 1, "class External {}");
let state = h.launcher.state("jdtls");
h.wait_status("jdtls", ServerStatus::Ready).await;
let init = &state.requested("initialize")[0];
assert_eq!(init["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root), uri_of(&external)]));
assert_eq!(init["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
let folders: Value = state.peer().request("workspace/workspaceFolders", Value::Null, None).await.unwrap();
assert_eq!(folders, init["workspaceFolders"]);
state.peer().request::<_, Value>("client/registerCapability", json!({"registrations":[{
"id":"external-java", "method":"workspace/didChangeWatchedFiles", "registerOptions":{"watchers":[{"globPattern":"**/*.java"}]}
}]}), None).await.unwrap();
let other = external.join("Other.java");
h.mgr.watched_files_changed(std::slice::from_ref(&other), &[], &[], &[]);
eventually(|| {
state.notified("workspace/didChangeWatchedFiles").iter().any(|v| v["changes"][0]["uri"] == uri_of(&other))
})
.await;
h.mgr.set_content_roots(vec![]);
h.mgr.reconfigure().await;
eventually(|| state.requested("initialize").len() == 2).await;
assert_eq!(state.requested("initialize")[1]["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root)]));
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn trusting_an_existing_java_instance_restarts_it_without_locking_the_registry() {
for shared in [false, true] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(move || shared));
h.open("Main.java", "class Main {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
h.mgr.set_execution_allowed(false);
h.mgr.reconfigure().await;
h.mgr.set_execution_allowed(true);
eventually(|| state.launches.load(Ordering::SeqCst) == 2 && state.docs.lock().len() == 1).await;
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_preserves_other_servers_and_marker_scoped_fallbacks() {
for fallback in [false, true] {
let h = harness_for(
"java",
"java",
&[("jdtls", incremental_caps()), ("other", incremental_caps())],
if fallback { &["other"] } else { &[] },
);
h.mgr.set_jdtls_shared_hook(Box::new(|| true));
h.launcher.state("jdtls").missing.store(fallback, Ordering::SeqCst);
for path in java_siblings(&h) {
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
}
eventually(|| h.launcher.state("other").requested("initialize").len() == 2).await;
let servers = h.mgr.servers();
assert_eq!(servers.iter().filter(|s| s.name == "jdtls").count(), 1);
assert_eq!(servers.iter().filter(|s| s.name == "other").count(), 2);
assert_eq!(h.launcher.state("jdtls").launches.load(Ordering::SeqCst), usize::from(!fallback));
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_keeps_target_instances_separate_and_preserves_them_on_toggle() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(true));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
h.mgr.set_servers_hook(Box::new(|_, configs| {
let mut target = configs[0].clone();
target.target_key = Some("container".into());
target
.initialization_options
.as_mut()
.unwrap()
.as_table_mut()
.unwrap()
.insert("selectedTarget".into(), toml::Value::Boolean(true));
vec![configs[0].clone(), target]
}));
h.open("Main.java", "class Main {}");
for path in java_siblings(&h) {
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
}
let state = h.launcher.state("jdtls");
eventually(|| h.mgr.servers().iter().filter(|s| s.status == ServerStatus::Ready).count() == 4).await;
let initial = state.requested("initialize");
assert_eq!(initial.len(), 4);
let targets: Vec<_> = initial.iter().filter(|v| v["initializationOptions"]["selectedTarget"] == true).collect();
assert_eq!(targets.len(), 3, "target roots retain their marker-based identity");
assert!(targets.iter().all(|v| v["initializationOptions"].get("workspaceFolders").is_none()));
let local = initial.iter().find(|v| v["initializationOptions"]["selectedTarget"] != true).unwrap();
assert_eq!(local["rootUri"], uri_of(&h.root));
assert_eq!(local["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root)]));
let old: HashSet<_> = h.mgr.servers().into_iter().map(|s| s.id).collect();
shared.store(false, Ordering::SeqCst);
h.mgr.reconfigure().await;
eventually(|| h.mgr.servers().iter().filter(|s| s.status == ServerStatus::Ready).count() == 6).await;
assert_eq!(
h.mgr.servers().iter().filter(|s| old.contains(&s.id)).count(),
3,
"local sharing does not retire targets"
);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn virtual_java_documents_opened_during_a_toggle_attach_to_the_successor() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
let (doc, _) = h.open("Main.java", "class Main {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
let uris: Vec<_> = (0..16).map(|n| format!("jdt://contents/project/Virtual{n}.class")).collect();
state.respond(
"textDocument/definition",
json!(
uris.iter()
.map(|uri| json!({"uri":uri,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}))
.collect::<Vec<_>>()
),
);
h.mgr.goto(doc, Pos::default(), GotoKind::Definition).await.unwrap();
shared.store(true, Ordering::SeqCst);
let toggle = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
let mut opened = Vec::new();
for uri in uris {
let manager = h.mgr.clone();
let language = h.lang.clone();
let doc = DocId::next();
opened.push((
doc,
std::thread::spawn(move || manager.did_open_virtual(doc, &uri, &language, 0, "class Virtual {}")),
));
}
let docs: Vec<_> = opened
.into_iter()
.map(|(doc, thread)| {
thread.join().unwrap();
doc
})
.collect();
toggle.await.unwrap();
eventually(|| state.docs.lock().len() == docs.len() + 1).await;
assert_eq!(h.mgr.servers().len(), 1);
for doc in docs {
h.mgr.hover(doc, Pos::default(), Default::default()).await.unwrap();
}
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn files_changed_on_disk_reach_the_servers_of_their_language() {
let h = harness(&[("mock", incremental_caps())]);
@@ -2730,7 +3200,7 @@ async fn noop_handler_is_usable_for_raw_peers() {
let (a, b) = tokio::io::duplex(1024);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let _server = Peer::connect(br, bw, Arc::new(MockHandler(Arc::default())));
let _server = Peer::connect(br, bw, Arc::new(MockHandler(Arc::default(), std::sync::Weak::new())));
let client = Peer::connect(ar, aw, Arc::new(NoopHandler));
let v: Value = client.request("shutdown", (), None).await.unwrap();
assert_eq!(v, Value::Null);
+98
Переглянути файл
@@ -63,6 +63,104 @@ fn lang(id: &str, ext: &str, server: LanguageServerConfig) -> LanguageConfig {
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires OPENIDEA_TEST_JDTLS and OPENIDEA_TEST_GRADLE_HOME, with JDK 21+"]
async fn shared_jdtls_imports_independent_gradle_builds_and_external_root() {
use serde_json::json;
let jdtls = std::env::var("OPENIDEA_TEST_JDTLS").expect("set OPENIDEA_TEST_JDTLS");
let gradle_home = std::env::var("OPENIDEA_TEST_GRADLE_HOME").expect("set OPENIDEA_TEST_GRADLE_HOME");
let dir = tempfile::tempdir().unwrap();
let temp_root = dunce::canonicalize(dir.path()).unwrap();
let root = temp_root.join("workspace");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
let external = temp_root.join("external");
let mut files = Vec::new();
for (name, build) in [("alpha", root.join("alpha")), ("beta", root.join("beta")), ("external", external.clone())] {
let source_dir = build.join("app/src/main/java/demo");
std::fs::create_dir_all(&source_dir).unwrap();
std::fs::write(build.join("settings.gradle"), format!("rootProject.name = '{name}'\ninclude 'app'\n")).unwrap();
std::fs::write(build.join("build.gradle"), "").unwrap();
std::fs::write(build.join("app/build.gradle"), "plugins { id 'java' }\n").unwrap();
let source = format!(
"package demo; public class Main {{ public static void main(String[] args) {{ {name}Marker(); }} static void {name}Marker() {{}} }}\n"
);
let path = source_dir.join("Main.java");
std::fs::write(&path, &source).unwrap();
files.push((name, path, source));
}
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
java.language_servers.retain(|s| s.name == "jdtls");
let server = &mut java.language_servers[0];
server.command = jdtls;
server.env.insert("GRADLE_USER_HOME".into(), dir.path().join("gradle-user-home").to_string_lossy().into_owned());
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
let options = server.initialization_options.as_mut().unwrap().as_table_mut().unwrap();
let settings = options.get_mut("settings").unwrap().as_table_mut().unwrap();
let java_settings = settings.get_mut("java").unwrap().as_table_mut().unwrap();
let imports = java_settings.get_mut("import").unwrap().as_table_mut().unwrap();
let gradle = imports.get_mut("gradle").unwrap().as_table_mut().unwrap();
gradle.insert("home".into(), toml::Value::String(gradle_home));
gradle.insert("wrapper".into(), toml::Value::try_from(json!({"enabled": false})).unwrap());
if let Ok(home) = std::env::var("OPENIDEA_TEST_GRADLE_JAVA_HOME") {
gradle.insert("java".into(), toml::Value::try_from(json!({"home": home})).unwrap());
}
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
mgr.set_jdtls_shared_hook(Box::new(|| true));
mgr.set_content_roots(vec![external]);
for (_, path, source) in &files {
mgr.did_open(DocId::next(), path, &LanguageId::new("java"), 1, source);
}
retry("shared jdtls ready", Duration::from_secs(60), || {
let status = last_status(&events, "jdtls");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
panic!("shared jdtls failed: {message:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
for (name, path, _) in &files {
let cp = retry(&format!("{name} Gradle classpath"), Duration::from_secs(180), || async {
let cp =
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(path, false, &Default::default()))
.await
.ok()?
.ok()?;
cp.class_paths.iter().any(|p| p.contains(&format!("/{name}/app/"))).then_some(cp)
})
.await;
assert!(
cp.class_paths
.iter()
.all(|p| !files.iter().any(|(other, _, _)| other != name && p.contains(&format!("/{other}/app/")))),
"classpath leaked between builds: {cp:?}"
);
let launch = tokio::time::timeout(
Duration::from_secs(30),
mgr.java_launch(path, false, false, false, false, &Default::default()),
)
.await
.expect("launch resolution timed out")
.expect("launch resolution failed");
assert_eq!(launch.class_paths, cp.class_paths, "launch resolved a different build for {name}");
}
let servers = mgr.servers().into_iter().filter(|s| s.name == "jdtls").collect::<Vec<_>>();
assert_eq!(servers.len(), 1, "expected one JDT LS: {servers:?}");
assert!(servers[0].pid.is_some(), "JDT LS process is not running");
for (_, path, _) in [&files[0], &files[2]] {
let bad = path.parent().unwrap().join("Broken.java");
let bad_source = "package demo; class Broken { MissingType x; }";
std::fs::write(&bad, bad_source).unwrap();
mgr.did_open(DocId::next(), &bad, &LanguageId::new("java"), 1, bad_source);
retry("diagnostics from shared JDT LS", Duration::from_secs(120), || {
let found = events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { path, items, .. } if path.0 == bad && items.iter().any(|d| d.message.contains("MissingType"))));
async move { found.then_some(()) }
}).await;
}
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires kmp-lsp on PATH (or OPENIDEA_TEST_KMP_LSP)"]
async fn kmp_lsp_java_end_to_end() {
+84 -2
Переглянути файл
@@ -4,8 +4,8 @@
//! than one place is taken from the first, in that order.
//!
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script,
//! Application, Spring Boot and compound configurations become the matching kinds; other types
//! are skipped with their type.
//! Application, Spring Boot, Go Application / Go Test and compound configurations become the
//! matching kinds; other types are skipped with their type.
//! `$PROJECT_DIR$` (and `$MODULE_DIR$`, `$MODULE_WORKING_DIR$`, `$ContentRoot$`,
//! `$ProjectFileDir$`, all the project directory here) and `$USER_HOME$` are replaced; another
//! path variable skips the configuration.
@@ -165,6 +165,8 @@ const SHELL: &str = "ShConfigurationType";
const COMPOUND: &str = "CompoundRunConfigurationType";
const APPLICATION: &str = "Application";
const SPRING_BOOT: &str = "SpringBootApplicationConfigurationType";
const GO_APPLICATION: &str = "GoApplicationRunConfiguration";
const GO_TEST: &str = "GoTestRunConfiguration";
type Res<T> = Result<T, SkipReason>;
@@ -343,6 +345,8 @@ impl Cx<'_> {
SHELL => self.shell(name, c)?,
APPLICATION => self.java_app(name, c, false, &mut ignored)?,
SPRING_BOOT => self.java_app(name, c, true, &mut ignored)?,
GO_APPLICATION => self.go_config(name, c, false, &mut ignored)?,
GO_TEST => self.go_config(name, c, true, &mut ignored)?,
COMPOUND => {
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
config(name, "compound", String::new(), Vec::new(), None)
@@ -353,6 +357,84 @@ impl Cx<'_> {
Ok(Found { config, members, ignored })
}
/// A Go Application (`GoApplicationRunConfiguration`) or Go Test configuration. Both share
/// the kind (package / file / directory), the target node, `go_parameters` (go tool
/// arguments) and envs; a test adds a `pattern` and program arguments go after `-args`.
fn go_config(&self, name: &str, c: &El, test: bool, _ignored: &mut Vec<String>) -> Res<RunConfig> {
let (dir, cwd) = self.cwd(c.value("working_directory"))?;
let scope = match c.value("kind").unwrap_or("PACKAGE") {
"FILE" => "file",
"DIRECTORY" => "directory",
_ => "package",
};
let path_target = |value: Option<&str>| -> Res<Option<String>> {
Ok(self.path(value)?.map(|p| path_from(self.root, p, &dir)).filter(|p| !p.is_empty()))
};
let target = match scope {
"file" => path_target(c.value("filePath"))?
.or(self.text(c.value("package"))?)
.filter(|t| !t.is_empty())
.unwrap_or_else(|| ".".to_owned()),
"directory" => path_target(c.value("directory"))?.unwrap_or_else(|| ".".to_owned()),
_ => self.text(c.value("package"))?.filter(|t| !t.is_empty()).unwrap_or_else(|| ".".to_owned()),
};
let raw_tool = self.text(c.value("go_parameters"))?.unwrap_or_default();
let tool_args = parse_params(&raw_tool, Quotes::Double);
let raw_program = self.text(c.value("parameters"))?.unwrap_or_default();
let program_args = parse_params(&raw_program, Quotes::Double);
let pattern = self.text(c.value("pattern"))?.unwrap_or_default();
let output_dir =
self.path(c.value("output_directory"))?.map(|p| path_from(self.root, p, self.root)).unwrap_or_default();
// The form's module is the working directory relative to the project root.
let module = cwd.as_ref().map(|d| d.to_string_lossy().replace('\\', "/")).unwrap_or_default();
let run_after_build = c.option("run") != Some("false");
let targets: Vec<String> = if scope == "file" {
target.split('|').map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect()
} else {
vec![target.clone()]
};
let mut args = vec![if test { "test".to_owned() } else { "build".to_owned() }];
args.extend(tool_args.clone());
if test {
if !pattern.is_empty() {
args.extend(["-run".to_owned(), pattern.clone()]);
}
args.extend(targets);
if !program_args.is_empty() {
args.push("-args".to_owned());
args.extend(program_args.clone());
}
} else {
args.extend(targets);
}
let mut rc = config(name, "go", "go".into(), args, Some("delve"));
rc.cwd = cwd.map(Into::into);
rc.is_test = test;
let mut params = BTreeMap::from([
("goKind".to_owned(), if test { "test" } else { "build" }.to_owned()),
("scope".to_owned(), scope.to_owned()),
("target".to_owned(), target),
("toolArgs".to_owned(), raw_tool),
("programArgs".to_owned(), raw_program),
("module".to_owned(), module),
]);
if test {
if !pattern.is_empty() {
params.insert("pattern".to_owned(), pattern);
}
} else {
params.insert("outputDir".to_owned(), output_dir);
params.insert("runAfterBuild".to_owned(), run_after_build.to_string());
}
if !program_args.is_empty() {
params.insert("programArgv".to_owned(), serde_json::to_string(&program_args).unwrap_or_default());
}
params.retain(|_, value| !value.is_empty());
rc.extras.params = params;
self.envs(c, &mut rc);
Ok(rc)
}
// ------------------------------------------------------------- Python
/// The interpreter (`SDK_HOME` when the configuration doesn't use the module's), its
+71
Переглянути файл
@@ -1007,3 +1007,74 @@ fn file_urls_expand_module_and_home_macros() {
assert_eq!(cwd(home), Some(PathBuf::from("jobs dir")));
assert!(home.extras.local);
}
#[test]
fn imports_go_application_and_test_configurations() {
let dir = tempfile::tempdir().unwrap();
write(
dir.path(),
".run/build-linux-amd64.run.xml",
&run_file(
"build-linux-amd64",
r#"<configuration default="false" name="NAME" type="GoApplicationRunConfiguration" factoryName="Go Application" folderName="go-build">
<module name="goproject" />
<working_directory value="$PROJECT_DIR$" />
<go_parameters value="-ldflags &quot;-s -w&quot; -o bin/goproject.linux-amd64" />
<envs>
<env name="CGO_ENABLED" value="0" />
<env name="GOARCH" value="amd64" />
<env name="GOOS" value="linux" />
</envs>
<kind value="PACKAGE" />
<package value="goproject" />
<directory value="$PROJECT_DIR$" />
<filePath value="$PROJECT_DIR$/main.go" />
<output_directory value="$PROJECT_DIR$/bin" />
<option name="run" value="false" />
<method v="2" />
</configuration>"#,
),
);
write(
dir.path(),
".run/Test.run.xml",
&run_file(
"Run tests",
r#"<configuration default="false" name="NAME" type="GoTestRunConfiguration" factoryName="Go Test">
<module name="goproject" />
<working_directory value="$PROJECT_DIR$/pkg" />
<go_parameters value="-tags integration" />
<kind value="PACKAGE" />
<package value="example.com/pkg" />
<pattern value="TestLogin" />
<parameters value="-v -count=1" />
<method v="2" />
</configuration>"#,
),
);
let r = import_from(dir.path(), &[]);
let app = get(&r, "build-linux-amd64");
assert_eq!(app.kind, "go");
assert_eq!(app.command, "go");
assert_eq!(app.args, s(&["build", "-ldflags", "-s -w", "-o", "bin/goproject.linux-amd64", "goproject"]));
assert_eq!(app.env["GOOS"], "linux");
assert_eq!(app.extras.params["goKind"], "build");
assert_eq!(app.extras.params["scope"], "package");
assert_eq!(app.extras.params["target"], "goproject");
assert_eq!(app.extras.params["outputDir"], "bin");
assert_eq!(app.extras.params["runAfterBuild"], "false");
assert_eq!(app.extras.folder.as_deref(), Some("go-build"));
let test = get(&r, "Run tests");
assert!(test.is_test);
assert_eq!(test.kind, "go");
assert_eq!(
test.args,
s(&["test", "-tags", "integration", "-run", "TestLogin", "example.com/pkg", "-args", "-v", "-count=1"])
);
assert_eq!(cwd(test), Some(PathBuf::from("pkg")));
assert_eq!(test.extras.params["goKind"], "test");
assert_eq!(test.extras.params["pattern"], "TestLogin");
assert_eq!(test.extras.params["module"], "pkg");
}
+1
Переглянути файл
@@ -12,6 +12,7 @@ ide-core.workspace = true
ide-language.workspace = true
ide-run.workspace = true
ide-vfs.workspace = true
quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+141 -3
Переглянути файл
@@ -14,6 +14,7 @@ use crate::exe;
use crate::exec::{query_in, query_in_cancellable, which};
use ide_core::CancellationToken;
use ide_core::settings::Settings;
use quick_xml::{Reader, XmlVersion, events::Event};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
@@ -27,7 +28,7 @@ use std::time::{Duration, SystemTime};
pub struct LibraryGroup {
/// Display name, e.g. `Python 3.12 (.venv)`.
pub name: String,
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle`.
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`.
pub kind: String,
pub roots: Vec<LibraryRoot>,
}
@@ -148,6 +149,7 @@ pub fn project_libraries_stream(
return Vec::new();
}
let mut groups = dependency_groups(root, &settings, dependencies);
groups.extend(classpath_groups(&roots));
groups.extend(project_structure_groups(root, &settings));
if !cancel.is_cancelled() && !groups.is_empty() {
on_groups(groups.clone());
@@ -433,10 +435,20 @@ fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Lib
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
// Java modules without a build manifest carry `.classpath` / `.project` /
// `.idea` instead; a configured JDK or declared source roots mark one too.
let files = match manifests(root, JAVA_MANIFESTS) {
Some(files) => files,
None if !s.languages.java.jdk.trim().is_empty() || !s.project_structure.source_roots.is_empty() => Vec::new(),
None => return Vec::new(),
None => {
let java = [".classpath", ".project"].iter().any(|f| root.join(f).is_file())
|| root.join(".idea").is_dir()
|| !s.languages.java.jdk.trim().is_empty()
|| !s.project_structure.source_roots.is_empty();
if !java {
return Vec::new();
}
[".classpath", ".project"].iter().map(|f| root.join(f)).collect()
}
};
cached_cancellable(root, "jdk", s.languages.java.jdk.clone(), &files, cancel, || {
let jdk = crate::apply::project_jdk(root, s).or_else(|| {
@@ -470,6 +482,84 @@ fn project_structure_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
out
}
/// JDT libraries of modules without a Maven / Gradle manifest: each `.classpath`
/// in `roots` (the project root and its discovered modules) becomes a group.
fn classpath_groups(roots: &[PathBuf]) -> Vec<LibraryGroup> {
let mut out = Vec::new();
for dir in roots {
let file = dir.join(".classpath");
let Ok(text) = std::fs::read_to_string(&file) else { continue };
let mut seen = std::collections::HashSet::new();
let entries: Vec<LibraryRoot> = classpath_entries(dir, &text)
.into_iter()
.filter(|path| seen.insert(dunce::canonicalize(path).unwrap_or_else(|_| path.clone())))
.filter_map(|path| {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
if path.is_file() {
Some(LibraryRoot { name, path: ide_vfs::archive_root(&path).into() })
} else {
path.is_dir().then(|| LibraryRoot { name, path: path.into() })
}
})
.collect();
if !entries.is_empty() {
let name = dir
.file_name()
.map(|n| format!(".classpath ({})", n.to_string_lossy()))
.unwrap_or_else(|| ".classpath".into());
out.push(LibraryGroup { name, kind: "classpath".into(), roots: entries });
}
}
out
}
/// `path` (or its `sourcepath`, when it exists) of `.classpath` `kind="lib"`
/// entries resolved against the module dir; entries pointing nowhere are dropped.
pub(crate) fn classpath_entries(dir: &Path, text: &str) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut reader = Reader::from_str(text);
loop {
match reader.read_event() {
Ok(Event::Empty(ref tag)) | Ok(Event::Start(ref tag)) => {
if !tag.local_name().as_ref().eq_ignore_ascii_case("classpathentry") {
continue;
}
let (mut kind, mut path, mut srcpath) = (String::new(), String::new(), String::new());
for a in tag.attributes().flatten() {
let Ok(value) = a.normalized_value(XmlVersion::Implicit1_0) else { continue };
match a.key.as_ref() {
"kind" => kind = value.into_owned(),
"path" => path = value.into_owned(),
"sourcepath" => srcpath = value.into_owned(),
_ => {}
}
}
if kind != "lib" {
continue;
}
for p in [&srcpath, &path] {
let p = p.trim_matches('/');
if p.is_empty() {
continue;
}
let candidate = dir.join(p);
if candidate.exists() {
out.push(candidate);
break;
}
}
}
Ok(Event::Eof) => break,
Err(_) => break,
_ => {}
}
}
out
}
/// The JDK home and its sources (`lib/src.zip`, `src.zip` in JDK 8) as library roots.
pub(crate) fn jdk_library(jdk: &crate::java::Jdk) -> Option<LibraryGroup> {
let name = jdk_name(&jdk.home).unwrap_or_else(|| format!("JDK {}", jdk.major));
@@ -1108,4 +1198,52 @@ mod go_cache_tests {
cached(dir.path(), "go", "same".into(), &[], detect);
assert_eq!(count.get(), 2);
}
#[test]
fn classpath_entries_resolve_lib_paths_against_the_module() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("guava.jar"), "").unwrap();
std::fs::create_dir_all(root.join("classes")).unwrap();
std::fs::create_dir_all(root.join("lib")).unwrap();
std::fs::write(root.join("lib/servlet.jar"), "").unwrap();
let text = r#"<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="guava.jar" sourcepath="sources.zip"/>
<classpathentry kind="lib" path="classes"/>
<classpathentry kind="lib" path="/lib/servlet.jar"/>
<classpathentry kind="lib" path="missing.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>"#;
std::fs::write(root.join("sources.zip"), "").unwrap();
assert_eq!(
classpath_entries(root, text),
vec![root.join("sources.zip"), root.join("classes"), root.join("lib/servlet.jar")]
);
}
#[test]
fn classpath_groups_lists_jars_per_module() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join(".classpath"), r#"<classpath><classpathentry kind="lib" path="a.jar"/></classpath>"#)
.unwrap();
std::fs::write(root.join("a.jar"), "").unwrap();
let module = root.join("module-b");
std::fs::create_dir_all(&module).unwrap();
std::fs::write(
module.join(".classpath"),
r#"<classpath><classpathentry kind="lib" path="../shared.jar"/></classpath>"#,
)
.unwrap();
std::fs::write(root.join("shared.jar"), "").unwrap();
let groups = classpath_groups(&[root.to_path_buf(), module]);
assert_eq!(groups.len(), 2);
assert_eq!(groups[0].kind, "classpath");
assert_eq!(groups[0].roots.len(), 1);
assert!(groups[0].roots[0].path.to_string_lossy().ends_with("a.jar!"));
assert_eq!(groups[1].roots.len(), 1);
}
}
+7 -2
Переглянути файл
@@ -6,6 +6,11 @@ wire-compatible products listed in **New ▸ Data Source**. Connections are save
per project in `.openidea/data-sources.toml`; passwords live outside the project
(and never in that file).
The Database tree groups procedures and functions in one `routines` folder by
default. Enable **Separate Procedures and Functions** in the Database window’s
**Options** menu to show `procedures` and `functions` folders instead. This view
option is remembered across sessions.
## Oracle: Oracle Instant Client
Oracle support uses the Oracle Call Interface, so the Oracle client libraries
@@ -50,8 +55,8 @@ search path.
- Schemas = Oracle users (`ALL_USERS`); system accounts (`SYS`, `SYSTEM`,
`XDB`, `MDSYS`…) appear only with **Schemas ▸ Show system**.
- Tables, views, columns, indexes, foreign keys, triggers, routines and
sequences are read from the `ALL_*` views.
- Tables, views, columns, indexes, foreign keys, triggers, procedures, functions
and sequences are read from the `ALL_*` views.
- The query console runs SQL and PL/SQL blocks; `BEGIN … END;` blocks (nested
`;` included) are sent as one statement, and a lone `/` on its own line ends
one as in SQL*Plus.
+4 -2
Переглянути файл
@@ -3195,7 +3195,7 @@ export type DbRoutineInfo = {
*/
export type DbRowEdit = { kind: "update"; key: DbCellValue[]; values: DbCellValue[] } | { kind: "insert"; values: DbCellValue[] } | { kind: "delete"; key: DbCellValue[] };
/** A schema's routines and sequences (the tree's `routines` / `sequences` folders). */
/** A schema's routines (procedures and functions) and sequences. */
export type DbSchemaObjects = {
routines: DbRoutineInfo[],
sequences: DbSequenceInfo[],
@@ -5271,6 +5271,8 @@ export type JavaSettings = {
* (VS Code's `java.jdt.ls.vmargs`).
*/
jdtlsVmArgs?: string,
/** Share one JDT LS across builds in an ordinary project window; other windows remain separate. */
jdtlsShared?: boolean,
/** Build Tools › Maven. */
maven?: MavenSettings,
/** Build Tools › Gradle. */
@@ -5552,7 +5554,7 @@ export type LaunchConfig = {
export type LibraryGroup = {
/** Display name, e.g. `Python 3.12 (.venv)`. */
name: string,
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle`. */
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`. */
kind: string,
roots: LibraryRoot[],
};
+45 -33
Переглянути файл
@@ -41,7 +41,7 @@ import { t } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { usePlatform } from "@/platform/platformInfo";
import { fileManagerName } from "@/platform/fileManager";
import {
activateTab,
changeSplitOrientation,
@@ -338,8 +338,8 @@ export class EditorController implements SlotHost {
.catch((e) => this.documentError(e))
.then(() => {
if (generation !== this.projectGeneration) return;
if (root) this.restoreSession(root);
else if (s.lightEdit) this.restoreSession(LIGHT_EDIT_SESSION);
if (root) return this.restoreSession(root);
else if (s.lightEdit) return this.restoreSession(LIGHT_EDIT_SESSION);
});
} else if (previous.opening && !s.opening && this.closeCommitted) {
// A failed project open returns to the same project.
@@ -354,7 +354,7 @@ export class EditorController implements SlotHost {
this.upgradeWrappedImageTabs(wrappers);
}),
);
if (prevRoot) this.restoreSession(prevRoot);
if (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
if (this.manager.backend.onFsChanged)
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
const onWindowBlur = () => {
@@ -520,7 +520,7 @@ export class EditorController implements SlotHost {
}
/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */
restoreSession(root: string) {
async restoreSession(root: string) {
this.sessionRoot = root;
const session = loadSession(root);
if (!session) return;
@@ -528,17 +528,29 @@ export class EditorController implements SlotHost {
const kinds = useContributions.getState().editorKinds;
for (const pane of Object.values(state.panes))
pane.tabs = pane.tabs.map((tab) => (documentLifecycle(tab.input, kinds) ? { ...tab, preview: false } : tab));
this.restoredViews = new Map(Object.entries(session.files));
const current = useTabs.getState();
const liveKeys = openKeys(current);
this.restoredViews = new Map(Object.entries(session.files).filter(([path]) => !liveKeys.has(fileKey(path))));
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
this.restoring = true;
try {
// A restore landing after tabs were already opened (e.g. a launched file
// admitted while the transition was still in flight) must not wipe them.
useTabs.setState((current) => mergeSessionTabs(current, state), true);
useTabs.setState(mergeSessionTabs(current, state), true);
} finally {
this.restoring = false;
}
for (const pane of Object.values(state.panes)) if (pane.active) void this.ensureSlot(pane.active);
if (liveKeys.size)
for (const paneId of paneIds(useTabs.getState())) await this.enforcePaneTabLimit(paneId, undefined, liveKeys);
const next = useTabs.getState();
for (const pane of Object.values(next.panes)) if (pane.active) void this.ensureSlot(pane.active);
if (liveKeys.size) {
const active = this.activeTabOf(next);
if (active) {
await this.ensureSlot(active.id);
if (this.activeTabOf()?.id === active.id) this.focus();
}
}
}
private activeTabOf(s: TabsState = useTabs.getState()): Tab | null {
@@ -1131,24 +1143,7 @@ export class EditorController implements SlotHost {
this.admitting = false;
}
const canFocus = () => this.isCurrentOpening(generation) && this.activeTabOf()?.id === tabId;
const tabPrefs = editorPrefs().tabs;
await this.removeGuarded(
(current) =>
current.panes[paneId]
? enforceTabLimit(
current,
paneId,
tabPrefs.tabLimit,
tabPrefs.closingPolicy,
(tab) =>
inputDirty(tab.input, useContributions.getState().editorKinds) ??
!!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
activate ? tabId : (current.panes[paneId]?.active ?? tabId),
(tab) => inputDirty(tab.input, useContributions.getState().editorKinds) === true,
)
: current,
{ protect: (tab) => inputDirty(tab.input, useContributions.getState().editorKinds) === true },
);
await this.enforcePaneTabLimit(paneId, activate ? tabId : (useTabs.getState().panes[paneId]?.active ?? tabId));
if (!isTextInput(input)) {
if (o.focus !== false)
requestAnimationFrame(() => {
@@ -1184,6 +1179,29 @@ export class EditorController implements SlotHost {
}
}
private enforcePaneTabLimit(paneId: string, keep?: string, liveKeys?: ReadonlySet<string>) {
const prefs = editorPrefs().tabs;
const protect = (tab: Tab) =>
!!liveKeys?.has(tab.input.key) || inputDirty(tab.input, useContributions.getState().editorKinds) === true;
return this.removeGuarded(
(current) =>
current.panes[paneId]
? enforceTabLimit(
current,
paneId,
prefs.tabLimit,
prefs.closingPolicy,
(tab) =>
inputDirty(tab.input, useContributions.getState().editorKinds) ??
!!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
keep ?? current.panes[paneId]?.active ?? undefined,
protect,
)
: current,
{ protect },
);
}
activate(paneId: string, tabId: string, focus = true) {
const restored = restoreMaximizedToolWindow();
++this.activationGeneration;
@@ -1901,7 +1919,7 @@ function openInMenu(path: string): MenuItem {
label: "Open In",
submenu: [
{ kind: "action", action: "navigate.selectIn", arg: { path }, label: "Project View" },
{ kind: "action", action: "project.revealInFinder", arg: path, label: revealLabel() },
{ kind: "action", action: "project.revealInFinder", arg: path, label: fileManagerName() },
{ kind: "action", action: "project.openInTerminal", arg: path, label: "Terminal" },
{ kind: "separator" },
...menuGroupItems("openIn", { paths: [path] }),
@@ -1986,12 +2004,6 @@ export function editorController(): EditorController {
return (controller ??= new EditorController());
}
/** "Finder" / "Explorer" / "Files", like IDEA's Open In submenu. */
function revealLabel(): string {
const os = usePlatform.getState().os;
return os === "macos" ? "Finder" : os === "windows" ? "Explorer" : "Files";
}
function inPopup(target: EventTarget | null): boolean {
return target instanceof Element && !!target.closest("[data-popup]");
}
+176 -3
Переглянути файл
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorController, LIGHT_EDIT_SESSION, openFilePaths, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { initialTabsState } from "./model/tabs";
import { storeSession } from "./model/session";
import { initialTabsState, openTab, paneIds, togglePin } from "./model/tabs";
import { restoreTabsState, storeSession, type EditorSession } from "./model/session";
import { useProject } from "@/platform/project";
let ctrl: EditorController | null = null;
@@ -15,6 +15,7 @@ afterEach(() => {
useProject.setState({ project: null, lightEdit: false, settings: initialSettings } as never);
try {
localStorage.removeItem(`openidea.editorSession.v1:${LIGHT_EDIT_SESSION}`);
storeSession("/p", null);
} catch {
/* ignore */
}
@@ -55,9 +56,181 @@ describe("lightedit launch (#2229)", () => {
useProject.setState({ project: null, lightEdit: true });
await ctrl.openFile("/p/b.ts", { focus: true });
// A stale/second transition restore landing after the admit (#2229).
ctrl.restoreSession(LIGHT_EDIT_SESSION);
await ctrl.restoreSession(LIGHT_EDIT_SESSION);
await new Promise((r) => setTimeout(r, 50));
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
});
function savedSplit(dir: "row" | "column" = "row"): EditorSession {
return {
version: 1,
layout: {
kind: "split",
dir,
children: [
{
kind: "pane",
tabs: [
{ path: "/p/a.ts", pinned: true },
{ path: "/p/shared.ts", preview: true },
],
active: 1,
},
{ kind: "pane", tabs: [{ path: "/p/c.ts", preview: true }, { path: "/p/shared.ts" }], active: 1 },
],
},
activePane: 1,
files: {},
};
}
function setupRestore() {
ctrl = new EditorController(
createMemoryBackend({
"/p/a.ts": "a",
"/p/b.ts": "b\nsecond",
"/p/c.ts": "c",
"/p/shared.ts": "shared",
}),
);
ctrl.start();
return ctrl;
}
describe.each([LIGHT_EDIT_SESSION, "/p"])("late session restore: %s", (root) => {
it.each(["row", "column"] as const)(
"keeps the saved %s split and intentional copies, with the CLI file active in the saved active pane",
async (dir) => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { selection: { line: 1, col: 2 } });
const live = controller.activeSlot!;
storeSession(root, savedSplit(dir));
await controller.restoreSession(root);
const state = useTabs.getState();
expect(state.layout).toMatchObject({ kind: "split", dir });
expect(paneIds(state)).toHaveLength(2);
expect(state.activePane).toBe(paneIds(state)[1]);
expect(
Object.values(state.panes)
.flatMap((p) => p.tabs)
.filter((t) => t.input.path === "/p/shared.ts"),
).toHaveLength(2);
expect(activePath()).toBe("/p/b.ts");
expect(controller.activeSlot).toBe(live);
expect(live.caret()).toMatchObject({ line: 1, col: 2 });
expect(live.wantsFocus).toBe(true);
},
);
it("keeps pins before regular tabs, including after a subsequent pin and open", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { focus: false });
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts", pinned: true }], active: 0 },
activePane: 0,
files: {},
});
await controller.restoreSession(root);
let state = useTabs.getState();
expect(state.panes[state.activePane]!.tabs.map((t) => t.pinned)).toEqual([true, false]);
const pinned = togglePin(state, state.activePane, state.panes[state.activePane]!.active!);
state = openTab(pinned, pinned.activePane, { kind: "file", key: "file:/p/c.ts", path: "/p/c.ts" }).state;
expect(state.panes[state.activePane]!.tabs.map((t) => t.pinned)).toEqual([true, true, false]);
});
it("keeps at most one preview per pane when the live tab and both saved panes have previews", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { preview: true, focus: false });
storeSession(root, savedSplit());
await controller.restoreSession(root);
for (const pane of Object.values(useTabs.getState().panes))
expect(pane.tabs.filter((t) => t.preview).length).toBeLessThanOrEqual(1);
expect(openFilePaths(useTabs.getState())).toContain("/p/b.ts");
});
it("enforces the tab limit without evicting the launched tab", async () => {
useProject.setState({ settings: { editor: { tabs: { tabLimit: 1, closingPolicy: "lru" } } } as never });
const controller = setupRestore();
await controller.openFile("/p/b.ts", { focus: false });
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
activePane: 0,
files: {},
});
await controller.restoreSession(root);
expect(openFilePaths(useTabs.getState())).toEqual(["/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
it("keeps the live same-key slot and launch target instead of the saved caret", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { selection: { line: 1, col: 2 } });
const slot = controller.activeSlot!;
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/b.ts", pinned: true }], active: 0 },
activePane: 0,
files: { "/p/b.ts": { anchor: 0, head: 0 } },
});
await controller.restoreSession(root);
expect(openFilePaths(useTabs.getState())).toEqual(["/p/b.ts"]);
expect(controller.activeSlot).toBe(slot);
expect(slot.caret()).toMatchObject({ line: 1, col: 2 });
expect(useTabs.getState().panes[useTabs.getState().activePane]!.tabs[0]!.pinned).toBe(true);
});
it("moves a saved same-key launch target into the saved active pane without losing the split", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { selection: { line: 1, col: 2 } });
const slot = controller.activeSlot!;
const session = savedSplit();
if (session.layout.kind !== "split") throw new Error("expected split");
session.layout.children[0] = { kind: "pane", tabs: [{ path: "/p/b.ts", pinned: true }], active: 0 };
storeSession(root, session);
await controller.restoreSession(root);
const state = useTabs.getState();
expect(state.layout).toMatchObject({ kind: "split", dir: "row" });
expect(state.activePane).toBe(paneIds(state)[1]);
expect(
Object.values(state.panes)
.flatMap((p) => p.tabs)
.filter((t) => t.input.path === "/p/b.ts"),
).toHaveLength(1);
expect(controller.activeSlot).toBe(slot);
expect(slot.caret()).toMatchObject({ line: 1, col: 2 });
expect(state.panes[state.activePane]!.tabs[0]!.pinned).toBe(true);
});
it("protects every live tab when they already exceed the configured limit", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { focus: false });
await controller.openFile("/p/c.ts", { preview: true, focus: false });
useProject.setState({ settings: { editor: { tabs: { tabLimit: 1 } } } as never });
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
activePane: 0,
files: {},
});
await controller.restoreSession(root);
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/b.ts", "/p/c.ts"]);
expect(activePath()).toBe("/p/c.ts");
});
it("takes the saved state unchanged when the window is empty", async () => {
const controller = setupRestore();
storeSession(root, savedSplit());
await controller.restoreSession(root);
const saved = restoreTabsState(savedSplit(), (p) => `file:${p}`);
const state = useTabs.getState();
expect(paneIds(state)).toHaveLength(2);
expect(Object.values(state.panes).map((p) => p.tabs.map((t) => [t.input.path, t.pinned, t.preview]))).toEqual(
Object.values(saved.panes).map((p) => p.tabs.map((t) => [t.input.path, t.pinned, t.preview])),
);
expect(activePath()).toBe("/p/shared.ts");
});
});
+47 -19
Переглянути файл
@@ -93,27 +93,55 @@ export function openKeys(s: TabsState): Set<string> {
return keys;
}
/**
* Folds restored tabs into the current tabs without losing anything open: tabs
* already open stay (with their active tab), restored tabs missing by key are
* appended to the active pane. An empty window takes the restored state as-is,
* keeping its saved layout and active tab.
*/
/** Replays live tabs into the saved layout, retaining their slots and the launch target. */
export function mergeSessionTabs(current: TabsState, restored: TabsState): TabsState {
const target = current.panes[current.activePane];
if (!target || !Object.values(current.panes).some((p) => p.tabs.length)) return restored;
const seen = openKeys(current);
const additions: Tab[] = [];
for (const pane of Object.values(restored.panes))
for (const tab of pane.tabs) {
if (seen.has(tab.input.key)) continue;
seen.add(tab.input.key);
additions.push(tab);
const live = new Map<string, Tab>();
for (const pane of Object.values(current.panes)) for (const tab of pane.tabs) live.set(tab.input.key, tab);
if (!live.size) return restored;
const active = current.panes[current.activePane]?.tabs.find(
(t) => t.id === current.panes[current.activePane]?.active,
);
if (active) live.set(active.input.key, active);
let next = restored;
for (const tab of live.values()) {
let found = findTab(next, tab.input.key, restored.activePane);
let opening = tab;
// Put the launch target in the saved active pane without collapsing its saved source pane.
if (tab === active && found && found.paneId !== restored.activePane) {
const source = paneOf(next, found.paneId);
const savedId = found.tab.id;
const tabs = source.tabs.filter((t) => t.id !== savedId);
const mru = source.mru.filter((id) => id !== savedId);
next = withPane(next, {
...source,
tabs,
mru,
active: source.active === savedId ? (mru[0] ?? tabs[0]?.id ?? null) : source.active,
});
opening = { ...found.tab, input: tab.input };
found = null;
}
if (!additions.length) return current;
const tabs = [...target.tabs, ...additions];
const mru = [...target.mru, ...additions.map((t) => t.id).filter((id) => !target.mru.includes(id))];
return withPane(current, { ...target, tabs, mru });
if (!found) {
const pane = paneOf(next, restored.activePane);
const opened = openTab(next, pane.id, tab.input, {
pinned: opening.pinned,
preview: opening.preview && !pane.tabs.some((t) => t.preview),
preservePreview: true,
activate: false,
});
next = opened.state;
found = { paneId: pane.id, tab: paneOf(next, pane.id).tabs.find((t) => t.id === opened.tabId)! };
}
const pane = paneOf(next, found.paneId);
const savedId = found.tab.id;
next = withPane(next, {
...pane,
tabs: pane.tabs.map((t) => (t.id === savedId ? { ...t, id: tab.id, input: tab.input } : t)),
active: pane.active === savedId ? tab.id : pane.active,
mru: pane.mru.map((id) => (id === savedId ? tab.id : id)),
});
}
return active ? activateTab(next, restored.activePane, active.id) : next;
}
function withPane(s: TabsState, pane: Pane): TabsState {
+108
Переглянути файл
@@ -0,0 +1,108 @@
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DatabaseView } from "./DatabaseView";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { registerDatabaseTreeActions } from "./treeActions";
import { tablesKey, useDatabase } from "./store";
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
measure: () => {},
}),
}));
let dispose: () => void;
beforeEach(() => {
localStorage.removeItem("openidea.database.viewOptions");
setContext("projectOpen", true);
dispose = registerDatabaseTreeActions();
useDatabase.setState({
loaded: true,
sources: [{ id: "pg", name: "PostgreSQL", driver: "postgres", options: { singleDatabase: true } }],
schemas: { pg: { status: "ok", value: ["public"] } },
tables: { [tablesKey("pg", "public")]: { status: "ok", value: [] } },
objects: {
[tablesKey("pg", "public")]: {
routines: [
{ name: "calculate", kind: "function", arguments: "integer", returns: "integer" },
{ name: "calculate", kind: "function", arguments: "text", returns: "text" },
{ name: "refresh_data", kind: "procedure", arguments: "", returns: null },
],
sequences: [],
},
},
treeFilter: "",
separateProceduresAndFunctions: false,
treeExpanded: new Set(["pg", "pg/public", "pg/public/routines"]),
});
});
afterEach(() => dispose());
describe("routine grouping", () => {
it("keeps an existing expanded routines folder and both overloads by default", () => {
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
expect(tree.getByText("routines").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "true");
expect(tree.getAllByText("calculate")).toHaveLength(2);
expect(tree.getByText("refresh_data")).toBeInTheDocument();
expect(tree.queryByText("procedures")).toBeNull();
expect(tree.queryByText("functions")).toBeNull();
fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 });
expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/routines/calculate(text)");
act(() => useDatabase.setState({ treeFilter: "refresh" }));
expect(tree.queryAllByText("calculate")).toHaveLength(0);
expect(tree.getByText("refresh_data")).toBeInTheDocument();
});
it("toggles through the action, persists the option, and restores the old expansion", async () => {
expect(useDatabase.getInitialState().separateProceduresAndFunctions).toBe(false);
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
await act(() => executeAction("db.separateProceduresAndFunctions"));
expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({
separateProceduresAndFunctions: true,
});
expect(tree.queryByText("routines")).toBeNull();
const procedures = tree.getByText("procedures").closest('[role="treeitem"]')!;
const functions = tree.getByText("functions").closest('[role="treeitem"]')!;
expect(within(procedures as HTMLElement).getByText("1")).toBeInTheDocument();
expect(within(functions as HTMLElement).getByText("2")).toBeInTheDocument();
fireEvent.mouseDown(functions.querySelector("[data-tree-toggle]")!, { button: 0 });
expect(tree.getAllByText("calculate")).toHaveLength(2);
fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 });
expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/functions/calculate(text)");
await act(() => executeAction("db.separateProceduresAndFunctions"));
expect(tree.getByText("routines").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "true");
expect(tree.getAllByText("calculate")).toHaveLength(2);
expect(tree.getByText("refresh_data")).toBeInTheDocument();
expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({
separateProceduresAndFunctions: false,
});
});
it.each([false, true])("applies object and quick filters before grouping (separate: %s)", (separate) => {
const source = useDatabase.getState().sources[0]!;
useDatabase.setState({
separateProceduresAndFunctions: separate,
sources: [{ ...source, introspection: { objectFilter: "calculate" } }],
treeExpanded: new Set(["pg", "pg/public", "pg/public/routines", "pg/public/functions"]),
});
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
expect(tree.queryByText("procedures")).toBeNull();
expect(tree.queryByText("refresh_data")).toBeNull();
expect(tree.getAllByText("calculate")).toHaveLength(2);
const folder = tree.getByText(separate ? "functions" : "routines").closest('[role="treeitem"]')!;
expect(within(folder as HTMLElement).getByText("2")).toBeInTheDocument();
act(() => useDatabase.setState({ treeFilter: "refresh" }));
expect(tree.queryByText("public")).toBeNull();
expect(tree.queryByText("routines")).toBeNull();
expect(tree.queryByText("functions")).toBeNull();
});
});
+45 -19
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Database tool window (IDEA's layout): data source → database (PostgreSQL) → schema → `tables` /
* `views` / `materialized views` / `routines` / `sequences` folders → table → `columns` / `keys` /
* `foreign keys` / `indexes` / `triggers`,
* `views` / `materialized views` / `routines` (optionally `procedures` / `functions`) / `sequences`
* folders → table → `columns` / `keys` / `foreign keys` / `indexes` / `triggers`,
* with counts and column types, loaded lazily. Double-click a table to open its data, a data
* source to open its query console.
*/
@@ -32,7 +32,15 @@ import {
splitTarget,
targetOf,
} from "./model";
import { nodeTarget, schemaObjectOf, tableFolder, type DbNode as Node, type Folder, type Group } from "./nodes";
import {
nodeTarget,
routineFolder,
schemaObjectOf,
tableFolder,
type DbNode as Node,
type Folder,
type Group,
} from "./nodes";
import {
connect,
detailsKey,
@@ -66,10 +74,20 @@ const FOLDER_LABELS: Record<Folder, string> = {
views: "views",
materializedViews: "materialized views",
routines: "routines",
procedures: "procedures",
functions: "functions",
sequences: "sequences",
};
const FOLDERS: readonly Folder[] = ["tables", "views", "materializedViews", "routines", "sequences"];
const SEPARATE_FOLDERS: readonly Folder[] = [
"tables",
"views",
"materializedViews",
"procedures",
"functions",
"sequences",
];
function status<T>(key: string, l: Loaded<T> | undefined, map: (v: T) => Node[]): Node[] | undefined {
if (!l) return undefined;
@@ -101,6 +119,7 @@ function groupSize(d: DbTableDetails, g: Group): number {
export function DatabaseView() {
const st = useDatabase();
const folders = st.separateProceduresAndFunctions ? SEPARATE_FOLDERS : FOLDERS;
const tree = useRef<TreeHandle>(null);
useEffect(() => {
if (!st.loaded) void loadSources();
@@ -149,9 +168,12 @@ export function DatabaseView() {
(st.objects[tablesKey(id, schema)]?.routines ?? []).filter(shown(id));
const sequencesOf = (id: string, schema: string) =>
(st.objects[tablesKey(id, schema)]?.sequences ?? []).filter(shown(id));
/** Members of a schema folder: tables / views / materialized views, routines or sequences. */
/** Members of a schema folder, after object and quick filtering. */
const folderSize = (id: string, schema: string, folder: Folder): number => {
if (folder === "routines") return routinesOf(id, schema).length;
if (folder === "routines" || folder === "procedures" || folder === "functions")
return routinesOf(id, schema).filter(
(routine) => routineFolder(routine.kind, st.separateProceduresAndFunctions) === folder,
).length;
if (folder === "sequences") return sequencesOf(id, schema).length;
return (tablesOf(id, schema) ?? []).filter((t) => tableFolder(t.kind) === folder).length;
};
@@ -205,24 +227,28 @@ export function DatabaseView() {
return schemasOf(n.key, n.id);
case "schema":
return status(n.key, st.tables[tablesKey(n.id, n.schema)], () =>
FOLDERS.filter((f) => folderSize(n.id, n.schema, f) > 0).map((folder): Node => ({
kind: "folder",
key: `${n.key}/${folder}`,
id: n.id,
schema: n.schema,
folder,
})),
folders
.filter((f) => folderSize(n.id, n.schema, f) > 0)
.map((folder): Node => ({
kind: "folder",
key: `${n.key}/${folder}`,
id: n.id,
schema: n.schema,
folder,
})),
);
case "folder": {
const at = { id: n.id, schema: n.schema };
if (n.folder === "routines")
if (n.folder === "routines" || n.folder === "procedures" || n.folder === "functions")
// Overloads share a name: the key tells them apart by their arguments.
return routinesOf(n.id, n.schema).map((routine) => ({
kind: "routine",
key: `${n.key}/${routine.name}(${routine.arguments})`,
routine,
...at,
}));
return routinesOf(n.id, n.schema)
.filter((routine) => routineFolder(routine.kind, st.separateProceduresAndFunctions) === n.folder)
.map((routine) => ({
kind: "routine",
key: `${n.key}/${routine.name}(${routine.arguments})`,
routine,
...at,
}));
if (n.folder === "sequences")
return sequencesOf(n.id, n.schema).map((sequence) => ({
kind: "sequence",
+7 -1
Переглянути файл
@@ -4,7 +4,7 @@
* results grids, and a table data editor. Connections, introspection and
* statements run in Rust (`ide-db`).
*/
import { lazyComponent, lazyWhen } from "@/ui";
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { onIdeEvent } from "@/platform/ipc";
@@ -41,6 +41,11 @@ import {
watchIdleConnections,
} from "./store";
function useDatabaseHeaderMenu(): MenuItem[] {
const separate = useDatabase((s) => s.separateProceduresAndFunctions);
return [{ kind: "action", action: "db.separateProceduresAndFunctions", checked: separate }];
}
const useDialogOpen = () => useDatabase((s) => !!s.dialog);
export function activate(): () => void {
@@ -55,6 +60,7 @@ export function activate(): () => void {
anchor: "right",
order: 20,
component: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseView)),
headerMenu: useDatabaseHeaderMenu,
headerActions: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseHeaderActions)),
}),
registerServiceView({
+17
Переглянути файл
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { routineFolder, tableFolder } from "./nodes";
describe("schema folders", () => {
it("combines routines by default and separates them on request", () => {
expect(routineFolder("procedure")).toBe("routines");
expect(routineFolder("function")).toBe("routines");
expect(routineFolder("procedure", true)).toBe("procedures");
expect(routineFolder("function", true)).toBe("functions");
});
it("keeps tables, views and materialized views apart", () => {
expect(tableFolder("table")).toBe("tables");
expect(tableFolder("view")).toBe("views");
expect(tableFolder("materializedView")).toBe("materializedViews");
});
});
+8 -2
Переглянути файл
@@ -15,14 +15,20 @@ import type { DbObjectRef } from "./objects";
export type Group = "columns" | "keys" | "foreignKeys" | "indexes" | "triggers";
/** Folders under a schema: IDEA's `tables`, `views`, `materialized views`, `routines`, `sequences`. */
export type Folder = "tables" | "views" | "materializedViews" | "routines" | "sequences";
/** Schema folders; routines can optionally be separated into procedures and functions. */
export type Folder = "tables" | "views" | "materializedViews" | "routines" | "procedures" | "functions" | "sequences";
/** The folder a table, view or materialized view is listed in. */
export function tableFolder(kind: DbTableKind): Folder {
return kind === "view" ? "views" : kind === "materializedView" ? "materializedViews" : "tables";
}
/** IDEA's *Separate Procedures and Functions* option: the folder a routine is listed in. */
export function routineFolder(kind: DbRoutineInfo["kind"], separate = false): "routines" | "procedures" | "functions" {
if (!separate) return "routines";
return kind === "procedure" ? "procedures" : "functions";
}
/** Where a table-level node lives: connection target, schema, table. */
interface InTable {
id: string;
+22
Переглянути файл
@@ -57,6 +57,7 @@ export const DB_TOOL_WINDOW = "database";
export const RESULTS_VIEW = "dbResults";
const BINDINGS_KEY = "openidea.database.consoles";
const CONSOLE_SCHEMAS_KEY = "openidea.database.consoleSchemas";
const VIEW_OPTIONS_KEY = "openidea.database.viewOptions";
const MAX_TABS = 12;
export interface ResultTab {
@@ -144,6 +145,7 @@ interface DatabaseState {
consoleSchemas: Record<string, string>;
/** The Database tree's quick object filter (empty: everything shows). */
treeFilter: string;
separateProceduresAndFunctions: boolean;
completion: Record<string, DbCompletion>;
results: ResultTab[];
/** Result tab id, or `OUTPUT_TAB`. */
@@ -189,6 +191,15 @@ function readConsoleSchemas(): Record<string, string> {
}
}
function readSeparateProceduresAndFunctions(): boolean {
try {
const raw = localStorage.getItem(VIEW_OPTIONS_KEY);
return raw ? JSON.parse(raw)?.separateProceduresAndFunctions === true : false;
} catch {
return false;
}
}
export const useDatabase = create<DatabaseState>(() => ({
sources: [],
loaded: false,
@@ -201,6 +212,7 @@ export const useDatabase = create<DatabaseState>(() => ({
consoles: readBindings(),
consoleSchemas: readConsoleSchemas(),
treeFilter: "",
separateProceduresAndFunctions: readSeparateProceduresAndFunctions(),
completion: {},
results: [],
activeResult: null,
@@ -218,6 +230,16 @@ export const useDatabase = create<DatabaseState>(() => ({
pendingTx: new Set(),
}));
export function toggleSeparateProceduresAndFunctions() {
const separateProceduresAndFunctions = !useDatabase.getState().separateProceduresAndFunctions;
useDatabase.setState({ separateProceduresAndFunctions });
try {
localStorage.setItem(VIEW_OPTIONS_KEY, JSON.stringify({ separateProceduresAndFunctions }));
} catch {
// Per-viewer convenience only.
}
}
export const tablesKey = (id: string, schema: string) => `${id}\u0000${schema}`;
export const detailsKey = (id: string, schema: string, table: string) => `${id}\u0000${schema}\u0000${table}`;
+25
Переглянути файл
@@ -125,4 +125,29 @@ describe("table editor capabilities", () => {
uninstall();
}
});
it("counts the editor-area host focusing the tab as table-editor focus (#2307)", async () => {
backend.driver = "postgres";
const uninstall = installTableEditorFocus();
try {
let root!: HTMLElement;
await act(async () => {
const r = render(<TableEditor input={tableInput("source", "public", "users")} />);
root = r.container;
});
// Mimic EditorArea wrapping the tab in its focusable host, then focusing the host on open.
const host = root.closest("div")!;
host.setAttribute("data-editor-focus", "");
host.tabIndex = -1;
act(() => host.focus());
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: false });
// A later focus inside a text field still turns it off.
const input = document.createElement("input");
root.querySelector("[data-db-table-editor]")!.appendChild(input);
act(() => input.focus());
expect(getContext().dbTableEditorFocus).toBe(false);
} finally {
uninstall();
}
});
});
+5 -1
Переглянути файл
@@ -23,7 +23,11 @@ function update() {
function onFocusIn(event: FocusEvent) {
const target = event.target instanceof Element ? event.target : null;
const root = target?.closest("[data-db-table-editor]");
// The editor area focuses its host `[data-editor-focus]` when the tab opens —
// treat that as focus inside a table editor so ⌘F12 / ⌘↩ work right away.
const root =
target?.closest("[data-db-table-editor]") ??
(target?.hasAttribute("data-editor-focus") ? target.querySelector("[data-db-table-editor]") : null);
active = (root && !isTextField(target!) && handles.get(root)) || null;
update();
}
+6
Переглянути файл
@@ -32,6 +32,7 @@ import {
runSql,
sourceById,
tablesKey,
toggleSeparateProceduresAndFunctions,
useDatabase,
withConnection,
removeSource,
@@ -462,6 +463,11 @@ export function registerDatabaseTreeActions(): () => void {
useDatabase.setState({ newMenuOpen: true });
},
}),
tree({
id: "db.separateProceduresAndFunctions",
title: "Separate Procedures and Functions",
run: toggleSeparateProceduresAndFunctions,
}),
tree({
id: "db.collapseAll",
title: "Collapse All",
+114 -1
Переглянути файл
@@ -1,5 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const executeAction = vi.hoisted(() => vi.fn());
vi.mock("@/platform/actions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/actions")>()),
executeAction,
}));
const ipc = vi.hoisted(() => {
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
return {
@@ -18,7 +24,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
return { ...real, isTauri: () => true, commands: { ...real.commands, ...cmds } };
});
const notes = vi.hoisted(() => [] as Array<{ level: string; title: string; body?: unknown; actions?: unknown[] }>);
const notes = vi.hoisted(
() => [] as Array<{ level: string; title: string; body?: unknown; actions?: { label: string; run: () => void }[] }>,
);
vi.mock("@/workbench/contributions", async (importOriginal) => {
const real = await importOriginal<typeof import("@/workbench/contributions")>();
return {
@@ -74,6 +82,7 @@ function session(id: number, hotCodeReplace: boolean): DebugSession {
describe("HotSwap", () => {
beforeEach(() => {
notes.length = 0;
executeAction.mockClear();
ipc.cancelRequest.mockClear();
ipc.javaBuildWorkspace.mockClear();
ipc.debugRedefineClasses.mockReset();
@@ -226,6 +235,110 @@ describe("HotSwap", () => {
expect(hotSwapMessage(3, ["boom"])).toMatchObject({ level: "error", body: "boom" });
});
it.each([0, 1, 3])("reports obsolete methods as a reload warning even with %s returned classes", (changed) => {
expect(hotSwapMessage(changed, ["JVM contains obsolete methods"])).toMatchObject({
level: "warning",
title: "Classes reloaded",
body: expect.stringContaining("Active frames keep running the old code"),
});
expect(hotSwapMessage(changed, ["JVM contains obsolete methods"], true).body).toContain(
"bottom frame cannot be reset",
);
});
it.each([
"Failed to redefine classes: add method not implemented",
"Failed to redefine classes: schema change not implemented",
"Failed to redefine classes: JVM contains obsolete methods",
])("keeps a real failure even alongside obsolete methods: %s", (failure) => {
for (const errors of [[failure], ["JVM contains obsolete methods", failure]]) {
expect(hotSwapMessage(1, errors)).toMatchObject({ level: "error", title: "Hot Swap failed" });
}
});
function pausedFrames(names: string[], restartFrame = true): DebugSession {
return {
...session(1, true),
status: "paused",
caps: { hotCodeReplace: true, restartFrame } as DebugCapabilities,
selectedThread: 1,
selectedFrame: 11,
frames: names.map((name, i) => ({
id: 11 + i,
name,
path: "/p/App.java",
line: 11,
column: 0,
presentationHint: null,
})),
};
}
it.each([
[true, ["App.main(String[])"], false],
[false, ["OrderBook.place()", "App.main(String[])"], false],
[true, ["OrderBook.place()", "Native.call()[native method]"], false],
[true, ["Native.call()[native method]", "App.main(String[])"], false],
[true, ["OrderBook.place()", "App.main(String[])"], true],
])("offers Reset Frame only when supported and droppable (%s, %j)", async (supported, names, offered) => {
useDebug.setState({ sessions: { 1: pausedFrames(names, supported) } });
ipc.debugRedefineClasses.mockImplementationOnce(() =>
ipc.ok({ changedClasses: [], errorMessage: "JVM contains obsolete methods" }),
);
await reloadChangedClasses(false);
const note = notes.at(-1)!;
expect(note).toMatchObject({ level: "warning", title: "Classes reloaded" });
expect(note.actions).toHaveLength(offered ? 1 : 0);
if (offered) {
useDebug.setState({ active: 2 });
note.actions![0]!.run();
expect(executeAction).toHaveBeenCalledWith("debug.resetFrame");
expect(useDebug.getState().active).toBe(1);
expect(useDebug.getState().sessions[1]?.selectedFrame).toBe(11);
}
});
it("does not reset a stale frame from an earlier suspension", async () => {
const s = pausedFrames(["OrderBook.place()", "App.main(String[])"]);
useDebug.setState({ sessions: { 1: s } });
ipc.debugRedefineClasses.mockImplementationOnce(() =>
ipc.ok({ changedClasses: [], errorMessage: "JVM contains obsolete methods" }),
);
await reloadChangedClasses(false);
useDebug.setState({ sessions: { 1: { ...s, frames: [...s.frames] } } });
notes.at(-1)!.actions![0]!.run();
expect(executeAction).not.toHaveBeenCalled();
});
it("maps java-debug's obsolete-method ERROR event to the same warning", () => {
useDebug.setState({ sessions: { 1: pausedFrames(["App.main(String[])"]) } });
onHotCodeReplace(1 as DebugSessionId, {
kind: "hotCodeReplace",
changeType: "ERROR",
message: "JVM contains obsolete methods",
});
expect(notes.at(-1)).toMatchObject({
level: "warning",
title: "Classes reloaded",
body: expect.stringContaining("bottom frame cannot be reset"),
actions: [],
});
});
it("does not let the obsolete-method event replace the response's real failure", async () => {
ipc.debugRedefineClasses.mockImplementationOnce(async () => {
onHotCodeReplace(1 as DebugSessionId, {
kind: "hotCodeReplace",
changeType: "ERROR",
message: "JVM contains obsolete methods",
});
return ipc.ok({ changedClasses: [], errorMessage: "Failed to redefine classes: add method not implemented" });
});
await reloadChangedClasses(false);
expect(notes).toHaveLength(1);
expect(notes[0]).toMatchObject({ level: "error", title: "Hot Swap failed" });
});
it("translates the reload count with the sentence", async () => {
await setLocale("zh");
try {
+78 -6
Переглянути файл
@@ -16,8 +16,9 @@ import {
type RequestId,
} from "@/platform/ipc";
import { setContext } from "@/platform/context";
import { executeAction } from "@/platform/actions";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { isLive, useDebug, type DebugSession } from "./state";
import { isLive, selectFrame, selectSession, useDebug, type DebugSession } from "./state";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui/Menu";
@@ -48,16 +49,61 @@ export function hotSwapMenuItems(paths: readonly string[]): MenuItem[] {
/** "3 classes", translated per count (the sentence around it is translated on its own). */
const classesText = (n: number) => (n === 1 ? tx`${n} class` : tx`${n} classes`);
// java-debug reports this after redefineClasses succeeds, with no changedClasses count.
const obsoleteMethods = (message: string) => message.trim() === "JVM contains obsolete methods";
/** Message for the reload result (IDEA wording). */
export function hotSwapMessage(
changed: number,
errors: string[],
): { level: "info" | "error"; title: string; body?: string } {
if (errors.length) return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
bottomFrame = false,
): { level: "info" | "warning" | "error"; title: string; body?: string } {
if (errors.some((e) => !obsoleteMethods(e)))
return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
if (errors.length)
return {
level: "warning",
title: "Classes reloaded",
body:
tx("Active frames keep running the old code until they return. New calls use the reloaded code.") +
(bottomFrame
? " " +
tx(
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.",
)
: ""),
};
if (changed === 0) return { level: "info", title: "Loaded classes are up to date. Nothing to reload." };
return { level: "info", title: tx`${classesText(changed)} reloaded` };
}
function obsoleteFrameActions(sessions: DebugSession[]) {
return sessions.flatMap((s) => {
const frame = s.frames[0];
// java-debug cannot drop the bottom frame or frames involving a native caller.
if (
s.status !== "paused" ||
!s.caps?.restartFrame ||
!frame ||
s.frames.length < 2 ||
s.frames.slice(0, 2).some((f) => f.name.includes("[native method]"))
)
return [];
return [
{
label: sessions.length > 1 ? tx`Reset Frame (${s.name})` : "Reset Frame",
run: () => {
const current = useDebug.getState().sessions[s.id];
if (current?.status !== "paused" || current.frames !== s.frames) return;
selectSession(s.id);
selectFrame(s.id, frame.id, false);
void executeAction("debug.resetFrame");
},
},
];
});
}
/** Compiles (unless `build` is false) and reloads changed classes into every Java debug session. */
export async function reloadChangedClasses(build = true, configId?: string): Promise<void> {
if (reloading) return;
@@ -136,17 +182,31 @@ export async function reloadChangedClasses(build = true, configId?: string): Pro
}
const changed = new Set<string>();
const errors: string[] = [];
const obsolete: DebugSessionId[] = [];
for (const s of sessions) {
try {
const r = await call(commands.debugRedefineClasses(s.id));
r.changedClasses.forEach((c) => changed.add(c));
if (r.errorMessage) errors.push(r.errorMessage);
if (r.errorMessage) {
errors.push(r.errorMessage);
if (obsoleteMethods(r.errorMessage)) obsolete.push(s.id);
}
} catch (e) {
errors.push(e instanceof Error ? e.message : String(e));
}
}
const m = hotSwapMessage(changed.size, errors);
notifications().notify({ group: "run", key: KEY, ...m });
const affected = obsolete.flatMap((id) => useDebug.getState().sessions[id] ?? []);
const m = hotSwapMessage(
changed.size,
errors,
affected.some((s) => s.status === "paused" && s.frames.length === 1),
);
notifications().notify({
group: "run",
key: KEY,
...m,
...(m.level === "warning" ? { sticky: true, actions: obsoleteFrameActions(affected) } : {}),
});
} finally {
reloading = false;
quietUntil = Date.now() + 2_000;
@@ -170,6 +230,18 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
break;
case "ERROR":
case "WARNING":
if (obsoleteMethods(event.message)) {
if (reloading) return;
const s = useDebug.getState().sessions[session]!;
notifications().notify({
group: "run",
key: KEY,
...hotSwapMessage(0, [event.message], s.status === "paused" && s.frames.length === 1),
sticky: true,
actions: obsoleteFrameActions([s]),
});
return;
}
notifications().notify({
group: "run",
level: event.changeType === "ERROR" ? "error" : "warning",
+2
Переглянути файл
@@ -29,6 +29,7 @@ const GROUP_ICONS: Record<string, string> = {
goModules: "file-gomod",
maven: "maven-project",
gradle: "file-gradle",
classpath: "file-java",
ruby: "file-ruby",
gems: "file-ruby",
};
@@ -58,6 +59,7 @@ const MANIFESTS = new Set([
"go.mod",
"go.sum",
"go.work",
".classpath",
"pyproject.toml",
"setup.py",
"requirements.txt",
+2 -1
Переглянути файл
@@ -2,6 +2,7 @@
import { activeEditor } from "@/editor/api";
import { getAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { revealInFileManagerLabel } from "@/platform/fileManager";
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
@@ -388,7 +389,7 @@ export function registerProjectActions(): () => void {
copyPath("source", "project.copySourceRootPath", "Copy Path From Source Root"),
{
id: "project.revealInFinder",
title: tx`Reveal in ${revealLabel()}`,
title: revealInFileManagerLabel(),
category: "Project View",
icon: "external-link",
when: OPEN,
+2 -4
Переглянути файл
@@ -1,5 +1,6 @@
/** Context menu and "New" popup of the project view. */
import { executeAction, getAction } from "@/platform/actions";
import { fileManagerName } from "@/platform/fileManager";
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
import { relativePath, useProject } from "@/platform/project";
import { currentDetectedRoots, currentRoots } from "@/platform/projectRoots";
@@ -458,10 +459,7 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
}
export function revealLabel() {
const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
if (/Win/i.test(ua)) return "Explorer";
if (/Linux/i.test(ua)) return "Files";
return "Finder";
return fileManagerName();
}
/** What contributed menu groups see: the selected (non-placeholder) paths. */
+2 -3
Переглянути файл
@@ -1,10 +1,9 @@
/** Navigate › File Path (⌥⌘F12): the file and its folders, each revealed in the OS file manager. */
import { openPopup } from "@/editor/lsp/popupStore";
import { revealInFileManager } from "@/platform/fileManager";
import { fileManagerName, revealInFileManager } from "@/platform/fileManager";
import { notifications } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { nameOf, parentOf } from "./paths";
import { revealLabel } from "./contextMenu";
const DRIVE_ROOT = /^[A-Za-z]:\/?$/;
@@ -24,7 +23,7 @@ async function reveal(path: string) {
try {
await revealInFileManager(path);
} catch (e) {
const fileManager = revealLabel();
const fileManager = tx(fileManagerName());
notifications().notify({
level: "error",
title: tx`Cannot reveal in ${fileManager}`,
+3 -5
Переглянути файл
@@ -5,7 +5,7 @@
import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
import { fileManagerPath, revealInFileManager } from "@/platform/fileManager";
import { fileManagerName, fileManagerPath, revealInFileManager } from "@/platform/fileManager";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
@@ -837,10 +837,8 @@ export async function revealInFinder(nodes: ProjectNode[] = selectedNodes()) {
try {
await revealInFileManager(nodes.map((n) => n.path));
} catch (e) {
// Same names as contextMenu.revealLabel (kept local: contextMenu imports
// this module, so importing it back would be a cycle).
const desktop = usePlatform.getState().os;
fail(`Cannot reveal in ${desktop === "windows" ? "Explorer" : desktop === "linux" ? "Files" : "Finder"}`, e);
const fileManager = tx(fileManagerName());
fail(tx`Cannot reveal in ${fileManager}`, e);
}
}
+34
Переглянути файл
@@ -1,6 +1,8 @@
import { afterEach, describe, expect, it } from "vitest";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
import { resolveMenuItems, useContextMenuStore, type MenuItem } from "@/ui";
import { provideEditorService, registerMenuGroup, type EditorService } from "@/workbench/contributions";
import { registerProjectActions, selectInTargets } from "./actions";
@@ -33,6 +35,38 @@ describe("Open in Terminal", () => {
});
describe("Select In (⌥F1)", () => {
it.each([
["macos", "Finder", "Reveal in Finder"],
["windows", "Explorer", "Show in Explorer"],
["linux", "Files", "Show in Files"],
])("uses the platform store for %s menus and action titles", (os, name, title) => {
const previous = usePlatform.getState().os;
try {
usePlatform.setState({ os });
disposers.push(registerProjectActions());
expect(revealLabel()).toBe(name);
expect(labels(selectInTargets("/p/a.ts"))).toContain(name);
expect(getAction("project.revealInFinder")?.title).toBe(title);
} finally {
usePlatform.setState({ os: previous });
}
});
it("retranslates the file manager action after registering in Chinese", async () => {
const previous = usePlatform.getState().os;
try {
usePlatform.setState({ os: "windows" });
await setLocale("zh");
disposers.push(registerProjectActions());
expect(getAction("project.revealInFinder")?.title).toBe("在资源管理器中显示");
await setLocale("en");
expect(getAction("project.revealInFinder")?.title).toBe("Show in Explorer");
} finally {
usePlatform.setState({ os: previous });
_resetI18nForTests();
}
});
it("lists the project view, contributed targets, Finder and the terminal", () => {
disposers.push(
registerMenuGroup({
-1
Переглянути файл
@@ -62,7 +62,6 @@ export const KIND_CATEGORIES: Record<string, string> = {
make: "Build Tools",
just: "Build Tools",
npm: "JavaScript",
vue: "JavaScript",
node: "JavaScript",
bun: "JavaScript",
deno: "JavaScript",
-1
Переглянути файл
@@ -382,7 +382,6 @@ describe("add service categories", () => {
it("categorizes every built-in kind; update the table when adding kinds", () => {
const expected: Record<string, string> = {
npm: "JavaScript",
vue: "JavaScript",
node: "JavaScript",
bun: "JavaScript",
deno: "JavaScript",
+88
Переглянути файл
@@ -514,6 +514,94 @@ describe("Settings dialog", () => {
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsVmArgs", '"-Xmx2g"']]);
});
it("stages shared JDT LS in the project and writes it on Apply", async () => {
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).not.toBeChecked();
fireEvent.click(checkbox);
expect(checkbox).toBeChecked();
expect(settingsSet).not.toHaveBeenCalled();
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["project", "languages.java.jdtlsShared", "true"]]);
});
it("keeps the global shared JDT LS preference separate from the project's override", async () => {
global = setAt(global, "languages.java.jdtlsShared", true);
current = setAt(global, "languages.java.jdtlsShared", false);
useProject.setState({ settings: current });
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).not.toBeChecked();
fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeChecked();
fireEvent.click(checkbox);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "false"]]);
});
it("discards a shared JDT LS toggle on Cancel", async () => {
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
fireEvent.click(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" }));
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
expect(settingsSet).not.toHaveBeenCalled();
expect(current.languages?.java?.jdtlsShared).toBe(false);
});
it("disables shared JDT LS only in a native Workspace's project scope", async () => {
useProject.setState((s) => ({
project: { ...s.project!, workspace: { version: 1, name: "Workspace", projects: ["/p/member"] } },
}));
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).toBeDisabled();
expect(within(dialog).getByText(/Open a workspace member as a project/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeEnabled();
fireEvent.click(checkbox);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "true"]]);
});
it("disables sharing for a Java language server target only in project scope", async () => {
current = setAt(current, "languageServerTargets", { java: { target: "docker:java", server: "jdtls" } });
useProject.setState({ settings: current });
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeDisabled();
expect(within(dialog).getByText(/Select Local machine for the Java language server/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
expect(checkbox).toBeEnabled();
fireEvent.click(checkbox);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "true"]]);
});
it.each([{ java: { target: "", server: "jdtls" } }, { python: { target: "docker:python" } }])(
"keeps sharing available when Java runs locally: %j",
async (targets) => {
current = setAt(current, "languageServerTargets", targets);
useProject.setState({ settings: current });
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).toBeEnabled();
},
);
it("uses a staged project Java language server target before Apply", async () => {
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeEnabled();
act(() => stage("languages.servers", "project", "languageServerTargets.java.target", "docker:java"));
expect(checkbox).toBeDisabled();
expect(settingsSet).not.toHaveBeenCalled();
});
it("Settings for New Projects edits the global layer on every page", async () => {
render(<SettingsDialog />);
await act(async () => {
+9
Переглянути файл
@@ -192,6 +192,15 @@ describe("languages settings", () => {
expect(folderRole(ps, "src")).toBeNull();
});
it("defaults shared JDT LS to off and accepts only boolean values", () => {
expect(DEFAULT_LANGUAGES.java.jdtlsShared).toBe(false);
expect(validateLanguages({}).java.jdtlsShared).toBe(false);
expect(validateSettings({ languages: { java: { jdtlsShared: true } } }).languages.java.jdtlsShared).toBe(true);
expect(validateLanguages({ java: { jdtlsShared: false } }).java.jdtlsShared).toBe(false);
for (const invalid of ["true", 1, null, []])
expect(validateLanguages({ java: { jdtlsShared: invalid } }).java.jdtlsShared).toBe(false);
});
it("defaults Java language level to SDK default and keeps only supported levels", () => {
expect(validateLanguages({}).java.languageLevel).toBe("");
expect(validateLanguages({ java: { languageLevel: "8" } }).java.languageLevel).toBe("8");
+21 -2
Переглянути файл
@@ -4,15 +4,16 @@
* use (applied by `ide-sdk` when language servers start and when run configurations load).
*/
import { LanguageServerTargetRows, LanguageServerTargetsPage } from "./LanguageServerTarget";
import { useProject } from "@/platform/project";
import { useRunTargets } from "@/platform/pluginRunTargets";
import { tx } from "@/platform/i18n";
import { useEffect, useId, useMemo, useState } from "react";
import { call, commands, type Sdk } from "@/platform/ipc";
import { call, commands, type LanguageServerTarget, type Sdk } from "@/platform/ipc";
import { IconButton, Input, type SelectOption, T } from "@/ui";
import { JAVA_LANGUAGE_LEVELS, PHP_LANGUAGE_LEVELS } from "@/platform/languageSettings";
import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form";
import { choosePath } from "./api";
import { useSetting } from "../components/context";
import { usePageContext, useSetting } from "../components/context";
import { SdkField, tildify, useDetected } from "./components";
import styles from "./Sdk.module.css";
@@ -387,6 +388,11 @@ export const JAVA_LEVEL_OPTIONS: SelectOption[] = JAVA_LANGUAGE_LEVELS.map((leve
);
export function JavaPage() {
const [shared, setShared] = useSetting<boolean>("languages.java.jdtlsShared");
const [serverTargets] = useSetting<Record<string, LanguageServerTarget>>("languageServerTargets", "project");
const { scope } = usePageContext();
const workspace = useProject((s) => !!s.project?.workspace);
const sharedDisabled = scope === "project" && (workspace || !!serverTargets?.java?.target);
const [vmArgs, setVmArgs] = useSetting<string>("languages.java.jdtlsVmArgs");
const [languageLevel, setLanguageLevel] = useSetting<string>("languages.java.languageLevel");
const id = useId();
@@ -417,6 +423,19 @@ export function JavaPage() {
</Row>
</Section>
<Section title="Language Server">
<Toggle
label="Share JDT LS across builds"
checked={shared}
onChange={setShared}
disabled={sharedDisabled}
hint={
sharedDisabled
? workspace
? "Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it."
: "Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it."
: "Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes."
}
/>
<SdkRow
k="languages.java.jdtlsJdk"
label="JDK"
+3
Переглянути файл
@@ -132,6 +132,9 @@ export const LANGUAGE_PAGES: PageSpec[] = [
"lombok",
"javaagent",
"eclipse jdt",
"shared jdtls",
"linked builds",
"server process",
],
component: JavaPage,
},
+2 -1
Переглянути файл
@@ -8,6 +8,7 @@ import { useEffect, useId, useState } from "react";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { WORKFLOW_LIMITS, type IssueLinkValid } from "@/platform/workflowSettings";
import { showInFileManagerLabel } from "@/platform/fileManager";
import { Button, Icon, Input, type SelectOption, T } from "@/ui";
import { Row, SettingSelect } from "../components/Form";
import { useSetting } from "../components/context";
@@ -222,7 +223,7 @@ function PushDialogRows() {
const PATCH_CREATED: SelectOption[] = [
{ value: "ask", label: "Ask" },
{ value: "no", label: "No" },
{ value: "reveal", label: "Show in Finder" },
{ value: "reveal", label: showInFileManagerLabel() },
];
const INCOMING: SelectOption[] = [
+22
Переглянути файл
@@ -0,0 +1,22 @@
import { afterEach, expect, it } from "vitest";
import { _resetI18nForTests, setLocale, tx } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
import { patchSavedBody } from "../patches";
afterEach(() => _resetI18nForTests());
it.each([
["macos", "Patch file created successfully. Show it in Finder?", "补丁文件已创建。是否在访达中显示?"],
["windows", "Patch file created successfully. Show it in Explorer?", "补丁文件已创建。是否在资源管理器中显示?"],
["linux", "Patch file created successfully. Show it in Files?", "补丁文件已创建。是否在文件管理器中显示?"],
])("asks to show the saved patch in the %s file manager", async (os, english, chinese) => {
const previous = usePlatform.getState().os;
try {
usePlatform.setState({ os });
expect(patchSavedBody()).toBe(english);
await setLocale("zh");
expect(tx(patchSavedBody())).toBe(chinese);
} finally {
usePlatform.setState({ os: previous });
}
});
+13 -3
Переглянути файл
@@ -2,7 +2,7 @@ import { commitRepo } from "./multiRoot";
/** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */
import { useEffect, useState } from "react";
import type { Commit, FileStatus, PatchFile, PatchSource, ShelvedChangeList } from "@/bindings";
import { revealInFileManager } from "@/platform/fileManager";
import { fileManagerName, revealInFileManager } from "@/platform/fileManager";
import { call, commands } from "@/platform/ipc";
import { Button, Checkbox, Dialog, Icon, Input, List, Spinner, fileIconName, T } from "@/ui";
import { workflowSettings } from "@/platform/workflowSettings";
@@ -82,14 +82,24 @@ async function browseSave(current: string): Promise<string | null> {
}
}
/** Settings › Version Control › Confirmation › When patch is created: ask / no / show in Finder. */
/** Whole sentences let each locale translate the patch question. */
export function patchSavedBody(): string {
const name = fileManagerName();
return name === "Finder"
? "Patch file created successfully. Show it in Finder?"
: name === "Explorer"
? "Patch file created successfully. Show it in Explorer?"
: "Patch file created successfully. Show it in Files?";
}
/** Settings › Version Control › Confirmation › When patch is created: ask / no / show in the file manager. */
async function afterPatchSaved(path: string) {
const mode = workflowSettings().vcs.confirmation.onPatchCreated;
if (mode === "no") return;
if (mode === "ask") {
const r = await ask({
title: "Create Patch",
body: tx("Patch file created successfully. Show it in Finder?"),
body: tx(patchSavedBody()),
checkbox: "Don't ask again",
buttons: [{ id: "show", label: "Show", primary: true }],
});
+2 -2
Переглянути файл
@@ -1,7 +1,7 @@
import { useMemo, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import clsx from "clsx";
import { call, commands, type RecentProject, type RecentProjectGroup } from "@/platform/ipc";
import { revealInFileManager } from "@/platform/fileManager";
import { revealInFileManager, showInFileManagerLabel } from "@/platform/fileManager";
import { parseRemoteLocation } from "@/platform/remote";
import {
HighlightedText,
@@ -137,7 +137,7 @@ export function recentMenu(project: RecentProject, onOpened?: () => void, onRemo
: { kind: "action", action: "file.openInNewWindow", arg: project.path, label: "Open in New Window" },
{
id: "reveal",
label: "Show in Finder",
label: showInFileManagerLabel(),
icon: "external-link",
run: () => void revealInFileManager(project.path).catch(() => undefined),
},
+22 -1
Переглянути файл
@@ -31,6 +31,7 @@ vi.mock("@tauri-apps/api/webview", () => ({
}));
import { registerActions } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { ContextMenuHost } from "@/ui";
import { registerSettingsPage } from "@/workbench/contributions";
@@ -38,6 +39,7 @@ import { MessagesHost } from "@/workbench/messages";
import { projectInitials } from "@/workbench/projectColor";
import { handleListKey } from "./ProjectsPage";
import { customizeView } from "./CustomizePage";
import { recentMenu } from "./RecentList";
import { filterRecent, useRecent } from "./recent";
import { WelcomeView } from "./WelcomeView";
@@ -126,11 +128,30 @@ describe("Welcome › Projects", () => {
fireEvent.click(within(screen.getAllByRole("option")[0]!).getByRole("button", { name: "Project actions" }));
const menu = await screen.findByRole("menu");
expect(within(menu).getByText("Open in New Window")).toBeTruthy();
expect(within(menu).getByText("Show in Finder")).toBeTruthy();
expect(within(menu).getByText("Remove from Recent Projects…")).toBeTruthy();
dispose();
});
// Regression: the welcome menus are shared by the projects page and the two
// recent-project popups, and used to hardcode "Show in Finder" on every OS.
it("names the platform's file manager for the reveal action", () => {
const previous = usePlatform.getState().os;
const revealLabel = () => {
const items = recentMenu(p("acme-api", "/Users/me/repo/acme-api"));
return (items.find((i) => "id" in i && i.id === "reveal") as { label?: string } | undefined)?.label;
};
try {
usePlatform.setState({ os: "windows" });
expect(revealLabel()).toBe("Show in Explorer");
usePlatform.setState({ os: "linux" });
expect(revealLabel()).toBe("Show in Files");
usePlatform.setState({ os: "macos" });
expect(revealLabel()).toBe("Show in Finder");
} finally {
usePlatform.setState({ os: previous });
}
});
it("shows the landing page without recent projects", async () => {
recent = [];
await renderWelcome();
+40 -2
Переглянути файл
@@ -1,8 +1,46 @@
import { describe, expect, it } from "vitest";
import { fileManagerPath } from "./fileManager";
import { afterEach, describe, expect, it } from "vitest";
import { fileManagerName, fileManagerPath, revealInFileManagerLabel, showInFileManagerLabel } from "./fileManager";
import { _resetI18nForTests, setLocale, tx } from "./i18n";
const raw = String.raw;
afterEach(() => _resetI18nForTests());
describe("file manager labels", () => {
it.each([
["macos", "Finder", "Reveal in Finder"],
["windows", "Explorer", "Show in Explorer"],
["linux", "Files", "Show in Files"],
["web", "Files", "Show in Files"],
])("names the %s file manager in submenus and project actions", (os, name, label) => {
expect(fileManagerName(os)).toBe(name);
expect(revealInFileManagerLabel(os)).toBe(label);
});
it("translates the project action on every desktop platform", async () => {
await setLocale("zh");
expect(tx(revealInFileManagerLabel("macos"))).toBe("在访达中显示");
expect(tx(revealInFileManagerLabel("windows"))).toBe("在资源管理器中显示");
expect(tx(revealInFileManagerLabel("linux"))).toBe("在文件管理器中显示");
});
});
describe("showInFileManagerLabel", () => {
it("names the file manager of the platform instead of always Finder", () => {
expect(showInFileManagerLabel("macos")).toBe("Show in Finder");
expect(showInFileManagerLabel("windows")).toBe("Show in Explorer");
expect(showInFileManagerLabel("linux")).toBe("Show in Files");
expect(showInFileManagerLabel("web")).toBe("Show in Files");
});
it("is translated into the platform's file manager, not Finder", async () => {
await setLocale("zh");
expect(tx(showInFileManagerLabel("macos"))).toBe("在访达中显示");
expect(tx(showInFileManagerLabel("windows"))).toBe("在资源管理器中显示");
expect(tx(showInFileManagerLabel("linux"))).toBe("在文件管理器中显示");
});
});
describe("fileManagerPath", () => {
it("converts verbatim UNC paths to the form Windows Shell accepts", () => {
expect(
+14
Переглянути файл
@@ -29,6 +29,20 @@ export function fileManagerPath(
return path;
}
/** English source text; callers and the action registry translate it. */
export function fileManagerName(os = usePlatform.getState().os): string {
return os === "macos" ? "Finder" : os === "windows" ? "Explorer" : "Files";
}
export function showInFileManagerLabel(os = usePlatform.getState().os): string {
return os === "macos" ? "Show in Finder" : os === "windows" ? "Show in Explorer" : "Show in Files";
}
/** The project action has historically used "Reveal" on macOS. */
export function revealInFileManagerLabel(os = usePlatform.getState().os): string {
return os === "macos" ? "Reveal in Finder" : showInFileManagerLabel(os);
}
/** Reveals files in Explorer, Finder or the Linux desktop's file manager. */
export async function revealInFileManager(paths: string | readonly string[]): Promise<void> {
if (!isTauri()) return;
+3
Переглянути файл
@@ -164,6 +164,7 @@ export interface LanguagesValid {
languageLevel: (typeof JAVA_LANGUAGE_LEVELS)[number];
jdtlsJdk: string;
jdtlsVmArgs: string;
jdtlsShared: boolean;
gradle: {
linkedProjects: string[] | null;
jvm: string;
@@ -243,6 +244,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
languageLevel: "",
jdtlsJdk: "",
jdtlsVmArgs: "",
jdtlsShared: false,
gradle: { linkedProjects: null, jvm: "", distribution: "wrapper", home: "", userHome: "", runUsing: "gradle" },
maven: {
runnerJre: "",
@@ -401,6 +403,7 @@ export function validateLanguages(raw: unknown): LanguagesValid {
languageLevel: oneOf(java.languageLevel, JAVA_LANGUAGE_LEVELS, d.java.languageLevel),
jdtlsJdk: text(java.jdtlsJdk, d.java.jdtlsJdk),
jdtlsVmArgs: text(java.jdtlsVmArgs, d.java.jdtlsVmArgs),
jdtlsShared: bool(java.jdtlsShared, d.java.jdtlsShared),
gradle: {
linkedProjects: Array.isArray(gradle.linkedProjects)
? gradle.linkedProjects.filter((p): p is string => typeof p === "string")
+20
Переглянути файл
@@ -1,4 +1,24 @@
{
"Separate Procedures and Functions": "Separate Procedures and Functions",
"Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it.": "Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it.",
"Share JDT LS across builds": "Share JDT LS across builds",
"Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it.": "Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it.",
"Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes.": "Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes.",
"Finder": "Finder",
"Explorer": "Explorer",
"Files": "Files",
"Show in Finder": "Show in Finder",
"Show in Explorer": "Show in Explorer",
"Show in Files": "Show in Files",
"Reveal in Finder": "Reveal in Finder",
"Patch file created successfully. Show it in Finder?": "Patch file created successfully. Show it in Finder?",
"Patch file created successfully. Show it in Explorer?": "Patch file created successfully. Show it in Explorer?",
"Patch file created successfully. Show it in Files?": "Patch file created successfully. Show it in Files?",
"Cannot reveal in {fileManager}": "Cannot reveal in {fileManager}",
"Classes reloaded": "Classes reloaded",
"Active frames keep running the old code until they return. New calls use the reloaded code.": "Active frames keep running the old code until they return. New calls use the reloaded code.",
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.": "The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.",
"Reset Frame ({0})": "Reset Frame ({0})",
"Active Editor": "Active Editor",
"Soft-Wrap": "Soft-Wrap",
"The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.": "The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.",
+4 -1
Переглянути файл
@@ -2072,6 +2072,8 @@
"Show file extension": "Mostrar extensión de archivo",
"Show gutter icons": "Mostrar iconos del margen",
"Show hard wrap and visual guides (configured in Code Style options)": "Mostrar ajuste de línea fijo y guías visuales (configurado en las opciones de Estilo de código)",
"Show in Explorer": "Mostrar en el Explorador",
"Show in Files": "Mostrar en Archivos",
"Show in Finder": "Mostrar en Finder",
"Show in tool window": "Mostrar en ventana de herramientas",
"Show inlay Run to Cursor popup": "Mostrar ventana emergente integrada Ejecutar hasta el cursor",
@@ -4069,7 +4071,6 @@
"Include {path}": "Incluir {path}",
"Project View: {option}": "Vista del proyecto: {option}",
"Project View: Show {view}": "Vista del proyecto: Mostrar {view}",
"Reveal in {fileManager}": "Mostrar en {fileManager}",
"Unmark as {role}": "Desmarcar como {role}",
"Updated references in {count} file": "Referencias actualizadas en {count} archivo",
"Updated references in {count} files": "Referencias actualizadas en {count} archivos",
@@ -4779,6 +4780,8 @@
"Show Push dialog for Commit and Push": "Mostrar diálogo de Push al Confirmar y hacer Push",
"Show Push dialog only when committing to protected branches": "Mostrar diálogo de Push solo al confirmar en ramas protegidas",
"Combine stashes and shelves in one tab": "Combinar stashes y estantes en una sola pestaña",
"Patch file created successfully. Show it in Explorer?": "Archivo de parche creado correctamente. ¿Mostrarlo en el Explorador?",
"Patch file created successfully. Show it in Files?": "Archivo de parche creado correctamente. ¿Mostrarlo en Archivos?",
"Patch file created successfully. Show it in Finder?": "Archivo de parche creado correctamente. ¿Mostrarlo en Finder?",
"File names": "Nombres de archivo",
"Large files": "Archivos grandes",
+4 -1
Переглянути файл
@@ -1971,6 +1971,8 @@
"Show file extension": "Afficher l'extension du fichier",
"Show gutter icons": "Afficher les icônes de la gouttière",
"Show hard wrap and visual guides (configured in Code Style options)": "Afficher le retour à la ligne forcé et les repères visuels (configurés dans les options de style de code)",
"Show in Explorer": "Afficher dans l'Explorateur",
"Show in Files": "Afficher dans Fichiers",
"Show in Finder": "Afficher dans le Finder",
"Show in tool window": "Afficher dans la fenêtre d'outil",
"Show inlay Run to Cursor popup": "Afficher la fenêtre intégrée Exécuter jusqu'au curseur",
@@ -3926,7 +3928,6 @@
"Include {path}": "Inclure {path}",
"Project View: {option}": "Vue Projet : {option}",
"Project View: Show {view}": "Vue Projet : afficher {view}",
"Reveal in {fileManager}": "Afficher dans {fileManager}",
"Unmark as {role}": "Retirer le marquage {role}",
"Updated references in {count} file": "Références mises à jour dans {count} fichier",
"Updated references in {count} files": "Références mises à jour dans {count} fichiers",
@@ -4627,6 +4628,8 @@
"Show Push dialog for Commit and Push": "Afficher la boîte de dialogue Push pour Commit et push",
"Show Push dialog only when committing to protected branches": "Afficher la boîte de dialogue Push uniquement pour les commits sur des branches protégées",
"Combine stashes and shelves in one tab": "Regrouper les remises et les modifications mises de côté dans un seul onglet",
"Patch file created successfully. Show it in Explorer?": "Fichier de patch créé. L'afficher dans l'Explorateur ?",
"Patch file created successfully. Show it in Files?": "Fichier de patch créé. L'afficher dans Fichiers ?",
"Patch file created successfully. Show it in Finder?": "Fichier de patch créé. L'afficher dans le Finder ?",
"File names": "Noms de fichiers",
"Large files": "Fichiers volumineux",
+4 -1
Переглянути файл
@@ -2128,6 +2128,8 @@
"Show file extension": "파일 확장자 표시",
"Show gutter icons": "여백 아이콘 표시",
"Show hard wrap and visual guides (configured in Code Style options)": "하드 랩 및 시각적 가이드 표시(코드 스타일 옵션에서 구성)",
"Show in Explorer": "탐색기에서 표시",
"Show in Files": "파일에서 표시",
"Show in Finder": "Finder에서 표시",
"Show in tool window": "도구 창에 표시",
"Show inlay Run to Cursor popup": "인레이 “커서 위치까지 실행” 팝업 표시",
@@ -4135,7 +4137,6 @@
"Include {path}": "{path} 포함",
"Project View: {option}": "프로젝트 뷰: {option}",
"Project View: Show {view}": "프로젝트 뷰: {view} 표시",
"Reveal in {fileManager}": "{fileManager}에서 표시",
"Unmark as {role}": "{role} 표시 해제",
"Updated references in {count} file": "파일 {count}개의 참조를 업데이트했습니다",
"Updated references in {count} files": "파일 {count}개의 참조를 업데이트했습니다",
@@ -4852,6 +4853,8 @@
"Show Push dialog for Commit and Push": "커밋 및 푸시에 대한 푸시 대화 상자 표시",
"Show Push dialog only when committing to protected branches": "보호된 브랜치에 커밋할 때만 푸시 대화 상자 표시",
"Combine stashes and shelves in one tab": "스태시와 보류 항목을 하나의 탭에 결합",
"Patch file created successfully. Show it in Explorer?": "패치 파일이 생성되었습니다. 탐색기에서 표시하시겠습니까?",
"Patch file created successfully. Show it in Files?": "패치 파일이 생성되었습니다. 파일에서 표시하시겠습니까?",
"Patch file created successfully. Show it in Finder?": "패치 파일이 생성되었습니다. Finder에서 표시하시겠습니까?",
"File names": "파일 이름",
"Large files": "대용량 파일",
+4 -1
Переглянути файл
@@ -2053,6 +2053,8 @@
"Show file extension": "Pokaż rozszerzenie pliku",
"Show gutter icons": "Pokaż ikony na marginesie",
"Show hard wrap and visual guides (configured in Code Style options)": "Pokaż twarde zawijanie i linie pomocnicze (skonfigurowane w opcjach Stylu Kodu)",
"Show in Explorer": "Pokaż w Eksploratorze",
"Show in Files": "Pokaż w programie Pliki",
"Show in Finder": "Pokaż w Finderze",
"Show in tool window": "Pokaż w oknie narzędziowym",
"Show inlay Run to Cursor popup": "Pokaż wewnątrzlinijkowe okno wyskakujące 'Uruchom do kursora'",
@@ -4028,7 +4030,6 @@
"Include {path}": "Dołącz {path}",
"Project View: {option}": "Widok projektu: {option}",
"Project View: Show {view}": "Widok projektu: Pokaż {view}",
"Reveal in {fileManager}": "Pokaż w programie {fileManager}",
"Unmark as {role}": "Odznacz jako {role}",
"Updated references in {count} file": "Zaktualizowano odnośniki w {count} pliku",
"Updated references in {count} files": "Zaktualizowano odnośniki w {count} plikach",
@@ -4730,6 +4731,8 @@
"Show Push dialog for Commit and Push": "Pokaż okno dialogowe Wysyłania (Push) podczas zatwierdzania i wysyłania (Commit and Push)",
"Show Push dialog only when committing to protected branches": "Pokaż okno dialogowe Wysyłania tylko przy zatwierdzaniu do chronionych gałęzi",
"Combine stashes and shelves in one tab": "Połącz schowki (stashes) i półki (shelves) na jednej karcie",
"Patch file created successfully. Show it in Explorer?": "Plik łatki utworzono pomyślnie. Wyświetlić w Eksploratorze?",
"Patch file created successfully. Show it in Files?": "Plik łatki utworzono pomyślnie. Wyświetlić w programie Pliki?",
"Patch file created successfully. Show it in Finder?": "Plik łatki utworzono pomyślnie. Wyświetlić w programie Finder?",
"File names": "Nazwy plików",
"Large files": "Duże pliki",
+4 -1
Переглянути файл
@@ -2054,6 +2054,8 @@
"Show file extension": "Mostrar extensão do arquivo",
"Show gutter icons": "Mostrar ícones na margem",
"Show hard wrap and visual guides (configured in Code Style options)": "Mostrar quebra forçada e guias visuais (configurado nas opções de Estilo de Código)",
"Show in Explorer": "Mostrar no Explorer",
"Show in Files": "Mostrar nos Arquivos",
"Show in Finder": "Mostrar no Finder",
"Show in tool window": "Mostrar na janela de ferramentas",
"Show inlay Run to Cursor popup": "Mostrar popup inline de Executar até o Cursor",
@@ -4034,7 +4036,6 @@
"Include {path}": "Incluir {path}",
"Project View: {option}": "Visualização do projeto: {option}",
"Project View: Show {view}": "Visualização do projeto: mostrar {view}",
"Reveal in {fileManager}": "Revelar no {fileManager}",
"Unmark as {role}": "Desmarcar como {role}",
"Updated references in {count} file": "Referências atualizadas em {count} arquivo",
"Updated references in {count} files": "Referências atualizadas em {count} arquivos",
@@ -4744,6 +4745,8 @@
"Show Push dialog for Commit and Push": "Mostrar caixa de diálogo de Push para Commit e Push",
"Show Push dialog only when committing to protected branches": "Mostrar caixa de diálogo de Push apenas ao comitar em branches protegidas",
"Combine stashes and shelves in one tab": "Combinar stashes e shelves em uma única aba",
"Patch file created successfully. Show it in Explorer?": "Arquivo de patch criado com sucesso. Mostrar no Explorer?",
"Patch file created successfully. Show it in Files?": "Arquivo de patch criado com sucesso. Mostrar nos Arquivos?",
"Patch file created successfully. Show it in Finder?": "Arquivo de patch criado com sucesso. Mostrar no Finder?",
"File names": "Nomes de arquivos",
"Large files": "Arquivos grandes",
+16 -1
Переглянути файл
@@ -1,4 +1,16 @@
{
"Separate Procedures and Functions": "分别显示过程和函数",
"Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it.": "共享 JDT LS 仅适用于本机的普通项目窗口。请将 Java 语言服务器的运行位置设为本机后再使用。",
"Share JDT LS across builds": "在构建间共享 JDT LS",
"Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it.": "共享 JDT LS 仅适用于本机的普通项目窗口。请将工作区成员作为项目打开,再修改其此项设置。",
"Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes.": "在每个本机普通项目窗口中,已关联的构建共用一个 JDT LS 进程。其他项目窗口使用各自独立的进程。",
"Finder": "访达",
"Explorer": "资源管理器",
"Reveal in Finder": "在访达中显示",
"Classes reloaded": "类已重新加载",
"Active frames keep running the old code until they return. New calls use the reloaded code.": "活动栈帧将继续执行旧代码,直到方法返回。新的调用将使用重新加载的代码。",
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.": "无法重置栈底帧。请重新进入该方法或重启调试会话,以执行新代码。",
"Reset Frame ({0})": "重置栈帧({0})",
"Active Editor": "活动编辑器",
"The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.": "语言服务器的 Java 可执行文件({path})无法在此机器上运行。请在 {setting} 中选择可正常运行的 JDK,或设为自动。",
"Input queue is full (4 MiB or 1024 writes); input was not sent.": "输入队列已满(4 MiB 或 1024 次写入);本次输入未发送。",
@@ -2341,6 +2353,8 @@
"Show file extension": "显示文件扩展名",
"Show gutter icons": "显示装订区域图标",
"Show hard wrap and visual guides (configured in Code Style options)": "显示硬换行和视觉参考线(在代码样式选项中配置)",
"Show in Explorer": "在资源管理器中显示",
"Show in Files": "在文件管理器中显示",
"Show in Finder": "在访达中显示",
"Show in tool window": "在工具窗口中显示",
"Show inlay Run to Cursor popup": "显示内嵌的“运行到光标处”按钮",
@@ -4379,7 +4393,6 @@
"Include {path}": "包含 {path}",
"Project View: {option}": "项目视图:{option}",
"Project View: Show {view}": "项目视图:显示{view}",
"Reveal in {fileManager}": "在{fileManager}中显示",
"Unmark as {role}": "取消标记为{role}",
"Updated references in {count} file": "已更新 {count} 个文件中的引用",
"Updated references in {count} files": "已更新 {count} 个文件中的引用",
@@ -5109,6 +5122,8 @@
"Show Push dialog for Commit and Push": "提交并推送时显示推送对话框",
"Show Push dialog only when committing to protected branches": "仅在提交到受保护分支时显示推送对话框",
"Combine stashes and shelves in one tab": "在同一个标签页中合并显示贮藏和搁置",
"Patch file created successfully. Show it in Explorer?": "补丁文件已创建。是否在资源管理器中显示?",
"Patch file created successfully. Show it in Files?": "补丁文件已创建。是否在文件管理器中显示?",
"Patch file created successfully. Show it in Finder?": "补丁文件已创建。是否在访达中显示?",
"File names": "文件名",
"Large files": "大文件",