diff --git a/crates/ide-dap/src/adapter.rs b/crates/ide-dap/src/adapter.rs index ad47c10ee..097f47d57 100644 --- a/crates/ide-dap/src/adapter.rs +++ b/crates/ide-dap/src/adapter.rs @@ -120,6 +120,12 @@ fn builtin(adapter: &str) -> Option { "stdio", "Install GDB 14 or newer (apt install gdb, dnf install gdb, brew install gdb)", ), + "unity" => cfg( + "unity-debug", + &[], + "stdio", + "Install Unity Debugger in Settings > Language Servers, or configure the unity-debug tool path", + ), "rdbg" => cfg("rdbg", &["-O", "--port", PORT_PLACEHOLDER, "-c"], "tcp", "gem install debug"), // A jdtls bundle: the session is started through jdtls and reached via `debugServer`. "java-debug" => cfg( diff --git a/crates/ide-dap/src/attach.rs b/crates/ide-dap/src/attach.rs index 7ca01b47f..7ba80d772 100644 --- a/crates/ide-dap/src/attach.rs +++ b/crates/ide-dap/src/attach.rs @@ -12,6 +12,7 @@ use std::path::Path; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum AttachKind { + Unity, Java, Node, Python, diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 18f05ca43..4593293ed 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -19,6 +19,7 @@ mod jvm_memory; pub mod kotlin; pub mod kotlin_lsp; mod session; +pub mod unity; use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher}; use connection::{Connection, DapError}; @@ -1121,6 +1122,16 @@ impl DebugManager { let _ = tokio::time::timeout(INIT_TIMEOUT, initialized.wait_for(|v| *v)).await; } + if s.adapter == "unity" { + if launch_result.is_none() + && let Some(launch) = launch.as_mut() + { + launch.await?; + launch_result = Some(()); + } + unity::wait_for_threads(s).await?; + } + // A fresh adapter has no breakpoints, so a file with none enabled needs no request; the // others go out together, as VS Code sends them, instead of one round trip per file. let (files, idle): (Vec<_>, Vec<_>) = self @@ -1202,6 +1213,10 @@ impl DebugManager { if let Some(link) = s.jdwp_link.lock().as_ref() { link.release(); } + if s.adapter == "unity" { + unity::settle_startup(s).await; + s.emit(ide_core::event::DebugEvent::Initialized); + } Ok(()) } diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index d071267c5..52d028b2d 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -17,7 +17,7 @@ use std::process::Stdio; use std::sync::Arc; use std::sync::Weak; use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::io::{AsyncRead, AsyncReadExt}; use tokio::process::Child; use tokio::sync::{mpsc, watch}; @@ -116,6 +116,7 @@ pub(crate) struct Session { pub jvm_memory: tokio::sync::Mutex, /// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`]. pub(crate) quirks: kotlin_lsp::Quirks, + pub(crate) unity_startup_activity: Mutex, } /// Which threads of the program are suspended: each from its `stopped` event until a @@ -270,6 +271,7 @@ impl Session { kotlin_mirror: Mutex::new(None), jvm_memory: tokio::sync::Mutex::default(), quirks: kotlin_lsp::Quirks::default(), + unity_startup_activity: Mutex::new(Instant::now()), } } @@ -716,6 +718,15 @@ pub(crate) async fn event_loop( } async fn on_event(mgr: &Arc, s: &Arc, event: &str, mut body: Value) { + if s.adapter == "unity" + && event == "output" + && body + .get("output") + .and_then(Value::as_str) + .is_some_and(|text| text.starts_with("Loaded assembly:") || text.starts_with("Resolved pending breakpoint")) + { + *s.unity_startup_activity.lock() = Instant::now(); + } if let Some(mirror) = s.kotlin_mirror.lock().as_ref() { mirror.translate(&mut body); } @@ -724,7 +735,9 @@ async fn on_event(mgr: &Arc, s: &Arc, event: &str, mut bo match event { "initialized" => { s.initialized.send_replace(true); - s.emit(DebugEvent::Initialized); + if s.adapter != "unity" { + s.emit(DebugEvent::Initialized); + } } "stopped" => { let all = body.get("allThreadsStopped").and_then(Value::as_bool).unwrap_or(false); diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index d40fcace1..c43ac5cab 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -158,6 +158,7 @@ struct Script { /// `launch`, and a `configurationDone` sent while it runs is refused with `notStopped`. gdb15_starts_at_launch: bool, launch_after_configuration: bool, + empty_thread_responses: usize, /// Requests of the adapter's own (js-debug's `setCustomBreakpoints`…) answered with an empty body. accept: &'static [&'static str], /// Requests of the adapter's own answered with a body and followed by events. @@ -198,6 +199,7 @@ impl Default for Script { close_during_startup: false, gdb15_starts_at_launch: false, launch_after_configuration: false, + empty_thread_responses: 0, accept: &[], custom: None, } @@ -244,6 +246,8 @@ async fn fake_adapter(stream let mut held: Vec = Vec::new(); let mut stopped = false; let mut running = false; + let mut thread_requests = 0; + let mut unity = false; macro_rules! send { ($v:expr) => {{ let mut v: Value = $v; @@ -268,13 +272,14 @@ async fn fake_adapter(stream } match msg["command"].as_str().unwrap_or_default() { "initialize" => { + unity = msg["arguments"]["adapterID"] == "unity"; if let Some(delay) = script.delay_initialize { tokio::time::sleep(delay).await; } ok!( msg, json!({ - "supportsConfigurationDoneRequest": true, + "supportsConfigurationDoneRequest": !unity, "supportsCompletionsRequest": true, "supportsTerminateRequest": script.supports_terminate, "supportsSetVariable": true, @@ -293,8 +298,15 @@ async fn fake_adapter(stream // defers it sends late). send!(json!({"type": "event", "event": "initialized"})); } + if unity { + send!(json!({"type": "event", "event": "initialized"})); + } } "launch" | "attach" => { + if unity { + ok!(msg, Value::Null); + continue; + } if script.gdb15_starts_at_launch { // GDB 15 starts the program here and answers `launch` right away. running = true; @@ -448,7 +460,14 @@ async fn fake_adapter(stream tokio::time::sleep(Duration::from_millis(50)).await; ok!(msg, json!({"threads": [{"id": 1, "name": "\"main\"@1"}]})); } - "threads" => ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]})), + "threads" => { + thread_requests += 1; + if thread_requests <= script.empty_thread_responses { + ok!(msg, json!({"threads": []})); + } else { + ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]})); + } + } "stackTrace" => ok!( msg, json!({"stackFrames": [ @@ -878,6 +897,32 @@ async fn stop_terminates_and_disconnects() { assert!(h.manager.threads(id).await.is_err()); } +#[tokio::test] +async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() { + let h = harness(Script { empty_thread_responses: 2, ..Script::default() }); + h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap(); + let start = h.start(LaunchConfig { + adapter: "unity".into(), + request: "attach".into(), + program: None, + extra_json: Some(json!({ "name": "Unity Editor (42)", "__exceptionOptions": [] }).to_string()), + ..config() + }); + let ready = async { + h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await; + let commands = h.commands(); + let before_breakpoints = commands.iter().take_while(|c| *c != "setBreakpoints"); + assert!(before_breakpoints.filter(|c| *c == "threads").count() >= 3); + assert!(commands.iter().any(|c| c == "setBreakpoints")); + }; + let (id, ()) = tokio::join!(start, ready); + let id = id.unwrap(); + assert_eq!(h.request("attach")["arguments"]["name"], "Unity Editor (42)"); + h.manager.stop(id).await.unwrap(); + assert!(!h.commands().iter().any(|c| c == "launch" || c == "terminate")); + assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false); +} + #[tokio::test] async fn concurrent_sessions_are_independent() { let h = harness(Script::default()); diff --git a/crates/ide-dap/src/unity.rs b/crates/ide-dap/src/unity.rs new file mode 100644 index 000000000..f3da9ed7f --- /dev/null +++ b/crates/ide-dap/src/unity.rs @@ -0,0 +1,187 @@ +//! Lists the Unity Editors to attach to through UnityDebug's discovery (`unity-debug list`). + +use crate::{ + adapter, + attach::{AttachKind, AttachableProcess}, +}; +use ide_core::{IdeError, IdeResult}; +use std::{path::PathBuf, process::Stdio, time::Duration}; + +/// Waits until Mono reports its threads. +pub(crate) async fn wait_for_threads(session: &crate::session::Session) -> IdeResult<()> { + tokio::time::timeout(Duration::from_secs(20), async { + loop { + let body = session.conn.request_timeout("threads", serde_json::json!({}), Duration::from_secs(5)).await?; + if body.get("threads").and_then(serde_json::Value::as_array).is_some_and(|t| !t.is_empty()) { + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .map_err(|_| { + IdeError::unavailable( + "Unity debugger did not become ready. Enable Editor Attaching and Debug Mode in Unity, then retry.", + ) + })? +} + +// Mono binds breakpoints asynchronously and resumes threads itself during startup: wait for that burst to end. +pub(crate) async fn settle_startup(session: &crate::session::Session) { + *session.unity_startup_activity.lock() = std::time::Instant::now(); + let _ = tokio::time::timeout(Duration::from_secs(3), async { + while session.unity_startup_activity.lock().elapsed() < Duration::from_secs(1) { + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await; +} + +pub fn require_runtime(cwd: &std::path::Path) -> IdeResult<()> { + if cfg!(unix) && ide_core::tool_path::find_command("mono", &ide_core::tool_path::search_path(), cwd).is_none() { + return Err(IdeError::unavailable( + "Unity Debugger requires Mono. Install Mono, make sure mono is on PATH, then refresh the Unity process list.", + )); + } + Ok(()) +} + +const NOT_INSTALLED: &str = "debug adapter `unity` not found. Install Unity Debugger in Settings > Language Servers or configure the unity-debug tool path"; + +pub async fn editors(command: Option, cwd: PathBuf) -> IdeResult> { + require_runtime(&cwd)?; + let command = command.unwrap_or_else(|| "unity-debug".into()); + let lookup = command.clone(); + let dir = cwd.clone(); + let binary = tokio::task::spawn_blocking(move || adapter::resolve_binary(&lookup, &dir)) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + .ok_or_else(|| IdeError::unavailable(NOT_INSTALLED))?; + let mut cmd = tokio::process::Command::new(binary); + ide_core::process::prepare(cmd.as_std_mut()); + cmd.arg("list") + .current_dir(&cwd) + .env("PATH", ide_core::tool_path::search_path()) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + let out = tokio::time::timeout(Duration::from_secs(15), cmd.output()) + .await + .map_err(|_| { + IdeError::unavailable("Unity process discovery timed out. Check that Unity Editor is responsive.") + })? + .map_err(|e| IdeError::unavailable(format!("Cannot start Unity process discovery: {e}")))?; + if !out.status.success() { + return Err(IdeError::unavailable(format!( + "Unity process discovery failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + let mut rows = parse_editors(&String::from_utf8_lossy(&out.stdout)); + #[cfg(windows)] + if !rows.is_empty() { + match editor_process_ids() { + Ok(editors) => rows.retain(|p| editors.contains(&p.pid)), + Err(error) => tracing::warn!(%error, "Unity process filtering failed; using adapter discovery results"), + } + } + // The Editor of the open project comes first; the user picks which one to attach to. + let path = cwd.join("Library/EditorInstance.json"); + let pid = std::fs::File::open(path).ok().and_then(|file| { + use std::io::Read; + let json: serde_json::Value = serde_json::from_reader(file.take(4096)).ok()?; + json.get("process_id")?.as_u64().and_then(|n| u32::try_from(n).ok()) + }); + for row in &mut rows { + if Some(row.pid) == pid { + row.command_line = cwd.to_string_lossy().into_owned(); + } + } + rows.sort_by_key(|p| Some(p.pid) != pid); + Ok(rows) +} + +#[cfg(windows)] +fn editor_process_ids() -> IdeResult> { + use std::collections::HashMap; + use windows_sys::Win32::{ + Foundation::{CloseHandle, INVALID_HANDLE_VALUE}, + System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS, + }, + }; + + let mut unity = HashMap::new(); + // The adapter also finds the asset import worker processes: keep the Unity processes whose parent isn't Unity. + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if snapshot == INVALID_HANDLE_VALUE { + return Err(std::io::Error::last_os_error().into()); + } + let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::() as u32, ..std::mem::zeroed() }; + let mut found = Process32FirstW(snapshot, &mut entry); + if found == 0 { + let error = std::io::Error::last_os_error(); + CloseHandle(snapshot); + return Err(error.into()); + } + while found != 0 { + let end = entry.szExeFile.iter().position(|c| *c == 0).unwrap_or(entry.szExeFile.len()); + let name = String::from_utf16_lossy(&entry.szExeFile[..end]); + if name.eq_ignore_ascii_case("Unity.exe") { + unity.insert(entry.th32ProcessID, entry.th32ParentProcessID); + } + found = Process32NextW(snapshot, &mut entry); + } + CloseHandle(snapshot); + } + Ok(unity.iter().filter_map(|(&pid, parent)| (!unity.contains_key(parent)).then_some(pid)).collect()) +} + +pub fn parse_editors(output: &str) -> Vec { + let mut editors = Vec::new(); + for line in output.lines() { + let line = line.trim().trim_start_matches('\u{feff}'); + if !line.starts_with("Unity Editor (") { + continue; + } + // 3.0.1 prints `Unity Editor (Unity) (123)`; later versions append the project name. + let Some((name, pid, project)) = line.match_indices(" (").find_map(|(at, _)| { + let (id, project) = line[at + 2..].split_once(')')?; + let pid = id.parse::().ok().filter(|n| *n > 0)?; + Some((&line[..at], pid, project)) + }) else { + continue; + }; + if editors.iter().any(|p: &AttachableProcess| p.pid == pid) { + continue; + } + editors.push(AttachableProcess { + pid, + name: "Unity Editor".into(), + command_line: if project.trim().is_empty() { name.into() } else { project.trim().into() }, + kind: AttachKind::Unity, + adapter: "unity".into(), + host: None, + port: None, + }); + } + editors.sort_by(|a, b| a.command_line.cmp(&b.command_line).then(a.pid.cmp(&b.pid))); + editors +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn parses_editor_ids_and_projects_without_mistaking_players_or_logs_for_editors() { + let rows = parse_editors( + "\u{feff}Unity Editor (Unity) (42) Game (Test)\r\nUnity Editor (7) My Game\nUnity Editor (42) duplicate\nWindowsPlayer (123) Player\nUnity Hub (44)\nUnity Editor (invalid)\nUnity Editor (0)\nlog text", + ); + assert_eq!(rows.len(), 2); + assert_eq!((rows[0].pid, rows[0].command_line.as_str()), (42, "Game (Test)")); + assert_eq!(rows[1].pid, 7); + assert!(rows.iter().all(|p| p.kind == AttachKind::Unity && p.adapter == "unity")); + } +} diff --git a/crates/ide-dap/tests/unity.rs b/crates/ide-dap/tests/unity.rs new file mode 100644 index 000000000..41c7b5c47 --- /dev/null +++ b/crates/ide-dap/tests/unity.rs @@ -0,0 +1,187 @@ +//! Attaches to a real Unity Editor, with its own temporary project and Editor instance. +//! OPENIDEA_UNITY_EDITOR= OPENIDEA_UNITY_ADAPTER= +//! cargo test -p ide-dap --test unity -- --ignored --nocapture + +use ide_core::{IdeEvent, SharedSink, event::DebugEvent}; +use ide_dap::{Breakpoint, DebugManager, LaunchConfig, SessionOwner, StepKind}; +use ide_language::LanguageRegistry; +use parking_lot::Mutex; +use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration}; + +const SCRIPT: &str = r#"using System.IO; +using UnityEditor; +using UnityEngine; +[InitializeOnLoad] +public static class OpenIdeaAttachProbe +{ + static readonly string Root = Directory.GetParent(Application.dataPath).FullName; + static OpenIdeaAttachProbe() + { + EditorApplication.update += Tick; + } + static void Tick() + { + if (EditorApplication.isCompiling || EditorApplication.isUpdating) return; + if (!File.Exists(Path.Combine(Root, "ready"))) + File.WriteAllText(Path.Combine(Root, "ready"), System.Diagnostics.Process.GetCurrentProcess().Id.ToString()); + if (File.Exists(Path.Combine(Root, "exit"))) { EditorApplication.Exit(0); return; } + if (!File.Exists(Path.Combine(Root, "go"))) return; + File.Delete(Path.Combine(Root, "go")); + int result = Hit(41); + File.WriteAllText(Path.Combine(Root, "done"), result.ToString()); + } + static int Hit(int seed) + { + int answer = seed + 1; + return answer; + } +} +"#; + +async fn stopped(events: &Mutex>, expected_reason: &str) -> i64 { + for _ in 0..600 { + if let Some(thread) = events.lock().iter().find_map(|e| match e { + IdeEvent::Debug { event: DebugEvent::Stopped { thread_id, reason, .. }, .. } + if reason == expected_reason => + { + Some(*thread_id) + } + _ => None, + }) { + return thread; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + let events = events.lock(); + panic!("No breakpoint/step event: {:?}", &events[events.len().saturating_sub(16)..]); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs a licensed Unity Editor and the Unity DAP adapter"] +async fn real_editor_attach_breakpoint_step_variables_and_detach() { + let editor = std::env::var("OPENIDEA_UNITY_EDITOR").expect("OPENIDEA_UNITY_EDITOR"); + let adapter = std::env::var("OPENIDEA_UNITY_ADAPTER").expect("OPENIDEA_UNITY_ADAPTER"); + let target = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target").canonicalize().unwrap(); + // Keep the Editor log for diagnosing a failure. + let root = tempfile::Builder::new().prefix("unity-dap-smoke-").tempdir_in(target).unwrap().keep(); + let root = root.to_string_lossy().trim_start_matches(r"\\?\").replace('\\', "/"); + let root = PathBuf::from(root); + std::fs::create_dir_all(root.join("Assets/Editor")).unwrap(); + std::fs::create_dir(root.join("ProjectSettings")).unwrap(); + std::fs::create_dir(root.join("Packages")).unwrap(); + std::fs::write( + root.join("ProjectSettings/ProjectVersion.txt"), + format!( + "m_EditorVersion: {}\n", + PathBuf::from(&editor).ancestors().nth(2).and_then(|p| p.file_name()).unwrap().to_string_lossy() + ), + ) + .unwrap(); + std::fs::write(root.join("Packages/manifest.json"), r#"{"dependencies":{}}"#).unwrap(); + let source = root.join("Assets/Editor/OpenIdeaAttachProbe.cs"); + std::fs::write(&source, SCRIPT).unwrap(); + let mut command = tokio::process::Command::new(&editor); + ide_core::process::prepare(command.as_std_mut()); + // The test project has no packages: skip the package manager. + command + .args(["-batchmode", "-nographics", "-noUpm", "-debugCodeOptimization", "-projectPath"]) + .arg(&root) + .arg("-logFile") + .arg(root.join("Editor.log")) + .current_dir(&root) + .kill_on_drop(true); + let mut child = command.spawn().unwrap(); + let pid = child.id().unwrap(); + eprintln!("Isolated Unity pid {pid}, project {}", root.display()); + for _ in 0..1200 { + if root.join("ready").exists() { + break; + } + assert!(child.try_wait().unwrap().is_none(), "Unity exited; inspect {}/Editor.log", root.display()); + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert!(root.join("ready").exists(), "Editor failed to load the test script"); + let rows = ide_dap::unity::editors(Some(adapter.clone()), root.clone()).await.unwrap(); + assert!(rows.iter().any(|p| p.pid == pid), "test Editor absent: {rows:?}"); + let events: Arc>> = Arc::default(); + let saved = events.clone(); + let sink: SharedSink = Arc::new(move |event| saved.lock().push(event)); + let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new()))); + let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32; + manager + .set_breakpoints( + source.clone(), + vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }], + ) + .await + .unwrap(); + let start = || { + manager.start_with( + LaunchConfig { + name: format!("Unity Editor ({pid})"), + adapter: "unity".into(), + request: "attach".into(), + program: None, + args: vec![], + cwd: Some(root.clone().into()), + env: BTreeMap::new(), + extra_json: Some( + serde_json::json!({ "name": format!("Unity Editor ({pid})"), "__exceptionOptions": [] }) + .to_string(), + ), + }, + SessionOwner::new("smoke", sink.clone()), + |_| Some(adapter.clone()), + ) + }; + let session = start().await.unwrap(); + eprintln!("Attached; breakpoint states: {:?}", manager.breakpoint_states(&source)); + // Mono is ready to run once the start returns. + assert!(!manager.threads(session).await.unwrap().is_empty()); + std::fs::write(root.join("go"), "").unwrap(); + let thread = stopped(&events, "breakpoint").await; + let frames = manager.stack_trace(session, thread).await.unwrap(); + assert!(!frames.is_empty(), "Empty breakpoint stack: {:?}", events.lock()); + assert_eq!(frames[0].line, line); + let scopes = manager.scopes(session, frames[0].id).await.unwrap(); + let variables = manager.variables(session, scopes[0].variables_reference).await.unwrap(); + assert!(variables.iter().any(|v| v.name == "seed" && v.value == "41"), "{variables:?}"); + assert_eq!(manager.evaluate(session, Some(frames[0].id), "seed + 1".into()).await.unwrap().value, "42"); + events.lock().clear(); + manager.step(session, thread, StepKind::Over).await.unwrap(); + let thread = stopped(&events, "step").await; + let frames = manager.stack_trace(session, thread).await.unwrap(); + assert!(!frames.is_empty(), "Empty step stack: {:?}", events.lock()); + assert!(frames[0].line > line); + // Detaching at a breakpoint resumes the Editor. + manager.stop(session).await.unwrap(); + verify_resumed(&root, &mut child).await; + + // Attaching again to the same Editor hits the existing breakpoint. + std::fs::remove_file(root.join("done")).unwrap(); + events.lock().clear(); + let session = start().await.unwrap_or_else(|error| { + let events = events.lock(); + panic!("Reattach failed: {error:?}, recent events: {:?}", &events[events.len().saturating_sub(12)..]); + }); + std::fs::write(root.join("go"), "").unwrap(); + let thread = stopped(&events, "breakpoint").await; + assert_eq!(manager.stack_trace(session, thread).await.unwrap()[0].line, line); + manager.stop(session).await.unwrap(); + verify_resumed(&root, &mut child).await; + std::fs::write(root.join("exit"), "").unwrap(); + assert!(tokio::time::timeout(Duration::from_secs(30), child.wait()).await.unwrap().unwrap().success()); + eprintln!("Verified discovery, attachment, breakpoint, locals, evaluation, step, detach and reattachment"); +} + +async fn verify_resumed(root: &std::path::Path, child: &mut tokio::process::Child) { + let path = root.join("done"); + for _ in 0..100 { + assert!(child.try_wait().unwrap().is_none(), "disconnect terminated the Unity Editor"); + if std::fs::read_to_string(&path).is_ok_and(|text| text == "42") { + return; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("Unity did not complete the script after disconnect: {:?}", std::fs::read_to_string(path)); +} diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 885a6223c..0b2e22f3c 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -12,6 +12,25 @@ use std::path::PathBuf; /// Starts a session owned by this window: its events (and those of child sessions) go here only. pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult { host.require_trust(window)?; + let unity_pid = if config.adapter == "unity" { + if config.request != "attach" { + return Err(ide_core::IdeError::invalid("Unity debugging only supports attachment to a running Editor")); + } + let arguments = launch_arguments(&config)?; + let pid = arguments["name"] + .as_str() + .and_then(|name| name.strip_prefix("Unity Editor (")) + .and_then(|name| name.strip_suffix(')')) + .and_then(|pid| pid.parse::().ok()); + if let Some(pid) = pid { + require_unity_editor(pid)?; + } + let cwd = config.cwd.as_ref().map(|path| path.as_ref()).unwrap_or_else(|| std::path::Path::new(".")); + unity::require_runtime(cwd)?; + pid + } else { + None + }; let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows)); if config.adapter == "debugpy" && config.request == "launch" @@ -100,12 +119,26 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide let server_port = debug_server_port(&config); let result = host.debugger.start_with(config, owner, custom).await; flush_output(); + if result.is_err() + && let Some(pid) = unity_pid + { + require_unity_editor(pid)?; + } if let (Ok(id), Some(port)) = (&result, server_port) { attach_jvm_inspector(host, window, *id, port); } result } +fn require_unity_editor(pid: u32) -> IdeResult<()> { + if !ide_core::process::process_alive(pid) { + return Err(ide_core::IdeError::unavailable(format!( + "Unity Editor (PID {pid}) is no longer running. Refresh the Unity process list and select a running Editor." + ))); + } + Ok(()) +} + /// The port of the java-debug server this machine's jdtls started; `debugServer` as `host:port` /// names an adapter on another machine, whose jdtls is not ours to ask. fn debug_server_port(config: &LaunchConfig) -> Option { @@ -460,6 +493,17 @@ pub async fn debug_free_port(host: &Host, window: &str) -> IdeResult { ide_dap::adapter::free_port().map_err(ide_core::IdeError::from) } +pub async fn debug_unity_processes(host: &Host, window: &str) -> IdeResult> { + host.require_trust(window)?; + let project = host.project(window)?; + if ide_workspace::unity::detect(&project.root).is_none() { + return Err(ide_core::IdeError::invalid("Open a Unity project before attaching to the Editor")); + } + let command = ide_sdk::apply::tool_command(&project.root, &project.settings.effective(), "unity-debug") + .map(|p| p.to_string_lossy().into_owned()); + unity::editors(command, project.root.clone()).await +} + /// Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote /// JVM to connect to `host:port`; returns the loopback port java-debug attaches to. pub async fn debug_listen_for_jvm( @@ -664,6 +708,7 @@ pub(crate) fn register(d: &mut Dispatcher) { }); d.add("debug_attachable_processes", |c| async move { debug_attachable_processes(&c.host, &c.window).await }); d.add("debug_free_port", |c| async move { debug_free_port(&c.host, &c.window).await }); + d.add("debug_unity_processes", |c| async move { debug_unity_processes(&c.host, &c.window).await }); d.add("debug_listen_for_jvm", |c| async move { debug_listen_for_jvm(&c.host, &c.window, c.arg("request")?, c.arg("host")?, c.arg("port")?).await }); diff --git a/crates/ide-tools/src/archive.rs b/crates/ide-tools/src/archive.rs index dbd4fcefa..25d316c5a 100644 --- a/crates/ide-tools/src/archive.rs +++ b/crates/ide-tools/src/archive.rs @@ -338,6 +338,15 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, & } pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResult { + link_executable_with_runtime(bin_dir, command, target, None) +} + +pub fn link_executable_with_runtime( + bin_dir: &Path, + command: &str, + target: &Path, + runtime: Option<&str>, +) -> IdeResult { fs::create_dir_all(bin_dir)?; #[cfg(unix)] { @@ -347,7 +356,8 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul } let quoted = target.to_string_lossy().replace('\'', r"'\''"); // A Node script without a shebang (e.g. js-debug's dapDebugServer.js) runs through `node`. - let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" }; + let runner = runtime.or_else(|| target.extension().is_some_and(|e| e == "js").then_some("node")); + let runner = runner.map(|r| format!("{r} ")).unwrap_or_default(); fs::write(&link, format!("#!/bin/sh\nexec {runner}'{quoted}' \"$@\"\n"))?; make_executable(&link)?; make_executable(target)?; @@ -356,7 +366,8 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul #[cfg(not(unix))] { let link = bin_dir.join(format!("{command}.cmd")); - let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" }; + let runner = runtime.or_else(|| target.extension().is_some_and(|e| e == "js").then_some("node")); + let runner = runner.map(|r| format!("{r} ")).unwrap_or_default(); fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?; Ok(link) } @@ -510,6 +521,34 @@ mod tests { assert!(dest.join("ok.txt").exists()); } + #[test] + fn unity_vsix_wrapper_preserves_managed_assemblies_and_uses_mono_on_unix() { + let tmp = tempfile::tempdir().unwrap(); + let archive = tmp.path().join("unity.vsix"); + zip_file( + &archive, + &[ + ("extension/bin/UnityDebug.exe", b"adapter", 0o644), + ("extension/bin/UnityDebug.exe.config", b"runtime config", 0o644), + ("extension/bin/Mono.Debugger.Soft.dll", b"dependency", 0o644), + ], + ); + let dest = tmp.path().join("install with spaces"); + extract(&archive, ArchiveKind::Zip, &dest, "unity-debug", &CancellationToken::new()).unwrap(); + let target = locate(&dest, &["UnityDebug.exe".into()]).unwrap(); + let wrapper = + link_executable_with_runtime(&dest.join("bin"), "unity-debug", &target, cfg!(unix).then_some("mono")) + .unwrap(); + let script = fs::read_to_string(wrapper).unwrap(); + assert!(script.contains(&*target.to_string_lossy())); + #[cfg(unix)] + assert!(script.contains("exec mono '") && script.contains("\"$@\"")); + #[cfg(windows)] + assert!(script.contains("\" %*") && !script.contains("mono ")); + assert_eq!(fs::read(target.with_extension("exe.config")).unwrap(), b"runtime config"); + assert_eq!(fs::read(target.parent().unwrap().join("Mono.Debugger.Soft.dll")).unwrap(), b"dependency"); + } + #[test] fn zip_symlinks_are_confined_to_the_destination() { for target in ["../outside", "/tmp/outside", "a/../../outside"] { diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rs index 726898059..a19e78c78 100644 --- a/crates/ide-tools/src/lib.rs +++ b/crates/ide-tools/src/lib.rs @@ -1296,6 +1296,14 @@ impl Tools { cancel: &CancellationToken, ) -> IdeResult { match source { + ReleaseSource::Fixed { version, url, sha256 } => Ok(sources::Download { + version: version.into(), + name: url.rsplit('/').next().unwrap_or("download").into(), + url: url.into(), + size: None, + sha256: Some(sha256.into()), + checksum_url: None, + }), ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) { Ok(json) => sources::github_pick(&json, assets, self.platform), Err(e) if e.kind == ErrorKind::Cancelled => Err(e), @@ -1442,7 +1450,11 @@ impl Tools { } else { archive::make_executable(&target)?; if self.exe_in(&bin, main).as_deref() != Some(target.as_path()) { - archive::link_executable(&bin, main, &target)?; + if spec.name == "unity-debug" && cfg!(unix) { + archive::link_executable_with_runtime(&bin, main, &target, Some("mono"))?; + } else { + archive::link_executable(&bin, main, &target)?; + } } } self.write_manifest(spec.name, &Manifest { version: Some(dl.version.clone()), source: Some(dl.url.clone()) }) diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index 614ddc8d4..67f20c192 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -20,6 +20,8 @@ pub enum ToolKind { /// Where release archives come from. #[derive(Clone, Copy, Debug)] pub enum ReleaseSource { + /// One pinned archive, verified against its SHA-256 before extraction. + Fixed { version: &'static str, url: &'static str, sha256: &'static str }, /// Latest GitHub release of `owner/repo`; assets plus links in the release notes. GitHub { repo: &'static str }, /// `api.releases.hashicorp.com` product. @@ -80,6 +82,7 @@ impl Method { Method::Release { source: ReleaseSource::EclipseJdtls, .. } => "Eclipse download", Method::Release { source: ReleaseSource::OpenVsx { .. }, .. } => "Open VSX", Method::Release { source: ReleaseSource::MavenCentral { .. }, .. } => "Maven Central", + Method::Release { source: ReleaseSource::Fixed { .. }, .. } => "Verified download", Method::Release { .. } => "GitHub release", } } @@ -131,6 +134,29 @@ const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str] pub const TYPESCRIPT: &str = "typescript@6"; pub static TOOLS: &[ToolSpec] = &[ + ToolSpec { + name: "unity-debug", + display: "Unity Debugger", + kind: Debugger, + commands: &["unity-debug"], + method: Method::Release { + source: ReleaseSource::Fixed { + version: "3.0.1", + url: "https://github.com/Unity-Technologies/vscode-unity-debug/releases/download/Version-3.0.1/unity-debug-3.0.1.vsix", + sha256: "4fa00660e0b52b0413726f80962e7d3d6efd41ac6cfd4df39520cae4a8ba5bd0", + }, + assets: &[any_arch(Mac, "*.vsix"), any_arch(Linux, "*.vsix"), any_arch(Windows, "*.vsix")], + locate: &["UnityDebug.exe"], + }, + fallback: None, + version: V, + homepage: "https://github.com/Unity-Technologies/vscode-unity-debug", + needs: if cfg!(windows) { + &[] + } else { + &[("mono", "Mono is required to run the Unity debugger (https://www.mono-project.com)")] + }, + }, ToolSpec { name: "prettier", display: "Prettier", @@ -1164,6 +1190,8 @@ mod tests { fn registry_names_match_language_configs() { let langs = ide_language::LanguageRegistry::load(None).unwrap().all(); let mut known = std::collections::HashSet::new(); + // The Unity debugger comes with Unity projects, apart from the C# debugger. + known.insert(("unity-debug".to_owned(), "unity-debug".to_owned())); for l in &langs { for s in &l.language_servers { known.insert((s.name.clone(), s.command.clone())); diff --git a/crates/ide-tools/src/tests.rs b/crates/ide-tools/src/tests.rs index 474db79f4..8f7dbf687 100644 --- a/crates/ide-tools/src/tests.rs +++ b/crates/ide-tools/src/tests.rs @@ -49,6 +49,24 @@ fn find<'a>(list: &'a [ToolInfo], name: &str) -> &'a ToolInfo { list.iter().find(|t| t.name == name).unwrap_or_else(|| panic!("{name} not listed")) } +#[test] +fn unity_adapter_download_is_pinned_and_checksum_verified() { + let env = Env::new(); + let tools = env.tools(); + let spec = registry::find("unity-debug").unwrap(); + let Method::Release { source, assets, locate } = spec.method else { panic!("expected release") }; + // A fixed release resolves without a network request. + let curl = env.sys.join(if cfg!(windows) { "curl.exe" } else { "curl" }); + fs::write(&curl, b"unused").unwrap(); + archive::make_executable(&curl).unwrap(); + let http = Http::new(env.sys.as_os_str()).unwrap(); + let download = tools.resolve_release(&http, source, assets, &CancellationToken::new()).unwrap(); + assert_eq!(download.version, "3.0.1"); + assert!(download.url.starts_with("https://github.com/Unity-Technologies/vscode-unity-debug/releases/download/")); + assert_eq!(download.sha256.as_deref(), Some("4fa00660e0b52b0413726f80962e7d3d6efd41ac6cfd4df39520cae4a8ba5bd0")); + assert_eq!(locate, &["UnityDebug.exe"]); +} + #[test] fn bundled_lombok_replaces_legacy_installs_on_every_platform_without_downloads() { for os in [Os::Mac, Os::Linux, Os::Windows] { diff --git a/src-tauri/src/commands/debug.rs b/src-tauri/src/commands/debug.rs index c0630906d..e5bc07939 100644 --- a/src-tauri/src/commands/debug.rs +++ b/src-tauri/src/commands/debug.rs @@ -348,6 +348,15 @@ pub async fn debug_free_port(window: Window, state: State<'_, AppState>) -> IdeR ide_host::ops::debug::debug_free_port(&state.host, window.label()).await } +#[tauri::command] +#[specta::specta] +pub async fn debug_unity_processes( + window: tauri::Window, + state: State<'_, AppState>, +) -> IdeResult> { + ide_host::ops::debug::debug_unity_processes(&state.host, window.label()).await +} + /// Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote /// JVM to connect to `host:port`; returns the loopback port java-debug attaches to. #[tauri::command] diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index b2128d7c5..eff1b9708 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -553,6 +553,7 @@ pub fn builder() -> tauri_specta::Builder { debug::debug_data_breakpoint_info, debug::debug_attachable_processes, debug::debug_free_port, + debug::debug_unity_processes, debug::debug_listen_for_jvm, debug::debug_redefine_classes, debug::debug_jvm_memory_classes, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index ceb29f2a9..10c0e81a2 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -165,6 +165,7 @@ debug_step_in_target trusted project_host bin debug_step_in_targets trusted project_host bindings async debug_stop always project_host bindings async debug_threads trusted project_host bindings async +debug_unity_processes trusted project_host bindings async debug_variables trusted project_host bindings async dependency_versions trusted project_host bindings async deploy_compare trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 1c1f80a0b..efff8ac1c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1337,6 +1337,7 @@ export const commands = { debugAttachableProcesses: () => typedError(__TAURI_INVOKE("debug_attachable_processes")), /** A loopback port that is free right now, for a debug agent the launch line starts. */ debugFreePort: () => typedError(__TAURI_INVOKE("debug_free_port")), + debugUnityProcesses: () => typedError(__TAURI_INVOKE("debug_unity_processes")), /** * Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote * JVM to connect to `host:port`; returns the loopback port java-debug attaches to. @@ -2737,7 +2738,7 @@ export type AskpassKind = /** Yes / no (an unknown host key); answered with `yes` or `no`. */ "confirm"; -export type AttachKind = "java" | "node" | "python" | "dotnet" | "go" | "native"; +export type AttachKind = "unity" | "java" | "node" | "python" | "dotnet" | "go" | "native"; export type AttachableProcess = { pid: number, diff --git a/src/features/debugger/__tests__/attach.test.ts b/src/features/debugger/__tests__/attach.test.ts index c751e029a..cd6e07a6b 100644 --- a/src/features/debugger/__tests__/attach.test.ts +++ b/src/features/debugger/__tests__/attach.test.ts @@ -20,6 +20,7 @@ const proc = (p: Partial & Pick { + it("attaches the chosen Unity Editor by its exact ID without launching or using a native adapter", async () => { + const launch = await attachConfig(proc({ pid: 1234, kind: "unity", name: "Unity Editor" }), "/game"); + expect(launch).toMatchObject({ adapter: "unity", request: "attach", program: null, cwd: "/game" }); + expect(JSON.parse(launch.extraJson!)).toEqual({ + name: "Unity Editor (1234)", + __exceptionOptions: [], + }); + }); it("groups processes by debugger in IDEA's order with counts", () => { const rows = attachRows(list, ""); expect(rows.filter((r) => r.kind === "group").map((r) => r.kind === "group" && `${r.label}:${r.count}`)).toEqual([ diff --git a/src/features/debugger/__tests__/missingAdapter.test.ts b/src/features/debugger/__tests__/missingAdapter.test.ts index 43e930449..b5d102692 100644 --- a/src/features/debugger/__tests__/missingAdapter.test.ts +++ b/src/features/debugger/__tests__/missingAdapter.test.ts @@ -12,6 +12,7 @@ describe("missing debug adapters", () => { }); it("offers the managed install of a missing adapter binary", () => { + expect(missingAdapter("unity", unavailable("debug adapter `unity` not found"))?.tool).toBe("unity-debug"); const e = unavailable( "debug adapter `js-debug` not found (`js-debug-adapter` is neither installed by OpenIDEA nor on PATH)", ); diff --git a/src/features/debugger/__tests__/unityAttach.test.tsx b/src/features/debugger/__tests__/unityAttach.test.tsx new file mode 100644 index 000000000..5ec71b156 --- /dev/null +++ b/src/features/debugger/__tests__/unityAttach.test.tsx @@ -0,0 +1,142 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import type { AttachableProcess, ProjectInfo, RunConfig } from "@/platform/ipc"; + +const mocks = vi.hoisted(() => ({ discover: vi.fn(), generic: vi.fn(), start: vi.fn(), install: vi.fn() })); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + isTauri: () => true, + commands: { + ...real.commands, + debugUnityProcesses: mocks.discover, + debugAttachableProcesses: mocks.generic, + }, + }; +}); +vi.mock("../state", async (original) => ({ + ...(await original()), + startSession: mocks.start, +})); + +import { registerAction } from "@/platform/actions"; +import { useProject } from "@/platform/project"; +import { openAttachPopup, installAttachAdapter } from "../attachPopup"; +import { DebuggerOverlays } from "../ui/Overlays"; +import { useOverlays } from "../ui/popoverStore"; + +const editor: AttachableProcess = { + pid: 42, + name: "Unity Editor", + commandLine: "/game", + adapter: "unity", + kind: "unity", + host: null, + port: null, +}; +const ok = (data: AttachableProcess[]) => ({ status: "ok" as const, data }); +function deferred() { + let resolve!: (result: ReturnType) => void; + const promise = new Promise>((r) => { + resolve = r; + }); + return { promise, resolve }; +} +let dispose: () => void; +beforeEach(() => { + vi.clearAllMocks(); + useProject.setState({ project: { root: "/game" } as ProjectInfo }); + useOverlays.setState({ attach: null }); + mocks.discover.mockResolvedValue(ok([editor])); + mocks.start.mockResolvedValue(1); + mocks.install.mockResolvedValue(undefined); + dispose = registerAction({ id: "tools.install", title: "Install", run: mocks.install }); +}); +afterEach(() => { + cleanup(); + dispose(); + useOverlays.setState({ attach: null }); + useProject.setState({ project: null }); +}); + +it("selects the requested Unity process and starts a non-rerunnable attach session", async () => { + const otherEditor = { ...editor, pid: 84, commandLine: "/other-game" }; + mocks.discover.mockResolvedValueOnce(ok([otherEditor, editor])); + await openAttachPopup("unity"); + render(); + expect(screen.getByRole("dialog", { name: "Attach to Unity Process" })).toBeTruthy(); + expect(screen.getByText(/switch to Debug Mode/)).toBeTruthy(); + fireEvent.keyDown(screen.getByRole("textbox", { name: "Filter processes" }), { key: "ArrowDown" }); + fireEvent.click(screen.getByRole("button", { name: "Attach" })); + await waitFor(() => + expect(mocks.start).toHaveBeenCalledWith( + expect.objectContaining({ + request: "attach", + adapter: "unity", + cwd: "/game", + extraJson: expect.stringContaining("Unity Editor (42)"), + }), + { rerunnable: false }, + ), + ); + expect(mocks.generic).not.toHaveBeenCalled(); + expect(useOverlays.getState().attach).toBeNull(); +}); + +it("associates the selected run configuration after refreshing the picker", async () => { + const runConfig = { id: "unity-editor", name: "Unity Editor", kind: "unity-editor" } as RunConfig; + await openAttachPopup("unity", runConfig); + render(); + fireEvent.click(screen.getByRole("button", { name: "Refresh" })); + await waitFor(() => expect(useOverlays.getState().attach?.processes).toEqual([editor])); + fireEvent.click(screen.getByRole("button", { name: "Attach" })); + await waitFor(() => expect(mocks.start).toHaveBeenCalledWith(expect.anything(), { rerunnable: false, runConfig })); +}); + +it("offers installation for a missing adapter and retries discovery afterwards", async () => { + mocks.discover.mockResolvedValueOnce({ + status: "error", + error: { kind: "unavailable", message: "debug adapter `unity` not found" }, + }); + await openAttachPopup("unity"); + render(); + fireEvent.click(screen.getByRole("button", { name: "Install Unity Debugger" })); + await waitFor(() => expect(useOverlays.getState().attach?.processes).toEqual([editor])); + expect(mocks.install).toHaveBeenCalledWith(expect.objectContaining({ arg: "unity-debug" })); +}); + +it("does not replace a refreshed picker with an older discovery response", async () => { + const old = deferred(); + mocks.discover.mockReturnValueOnce(old.promise); + const first = openAttachPopup("unity"); + await openAttachPopup("unity"); + old.resolve(ok([])); + await first; + expect(useOverlays.getState().attach?.processes).toEqual([editor]); +}); + +it("does not reopen a cancelled picker when discovery finishes", async () => { + const pending = deferred(); + mocks.discover.mockReturnValueOnce(pending.promise); + const request = openAttachPopup("unity"); + useOverlays.setState({ attach: null }); + pending.resolve(ok([editor])); + await request; + expect(useOverlays.getState().attach).toBeNull(); +}); + +it("does not attach to an old project's process or retry installation after switching projects", async () => { + await openAttachPopup("unity"); + render(); + act(() => useProject.setState({ project: { root: "/other" } as ProjectInfo })); + fireEvent.click(screen.getByRole("button", { name: "Attach" })); + expect(mocks.start).not.toHaveBeenCalled(); + act(() => + useOverlays.setState({ + attach: { processes: [], error: "missing", mode: "unity", projectRoot: "/game", installTool: "unity-debug" }, + }), + ); + await installAttachAdapter(); + expect(mocks.discover).toHaveBeenCalledTimes(1); +}); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index ea763d648..ced351a3a 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -80,14 +80,10 @@ import { expressionAt, valueHint } from "./editor/valueTooltip"; import { mouseEvaluateTarget } from "./editor/quickEvaluate"; import { showHint } from "@/editor/lsp/hint"; import { pausedLineTargets, startInlineSmartStep } from "./editor/smartStep"; -import { - openBreakpointsDialog, - openConfigChooser, - openEvaluateDialog, - openSmartStepChooser, - useOverlays, -} from "./ui/popoverStore"; +import { openBreakpointsDialog, openConfigChooser, openEvaluateDialog, openSmartStepChooser } from "./ui/popoverStore"; import { tx } from "@/platform/i18n"; +import { openAttachPopup } from "./attachPopup"; +export { openAttachPopup } from "./attachPopup"; function isRunConfig(arg: unknown): arg is RunConfig { return !!arg && typeof arg === "object" && "command" in arg && "args" in arg && "debugAdapter" in arg; @@ -180,22 +176,6 @@ async function smartStepInto() { if (!startInlineSmartStep(t.s.id, t.thread, targets)) openSmartStepChooser(t.s.id, t.thread, targets); } -/** Opens the Attach to Process popup and loads the process list. */ -export async function openAttachPopup() { - if (!isTauri()) { - notifications().notify({ group: "run", level: "warning", title: "Attaching needs the desktop app" }); - return; - } - useOverlays.setState({ attach: { processes: null, error: null } }); - try { - const processes = await call(commands.debugAttachableProcesses()); - if (useOverlays.getState().attach) useOverlays.setState({ attach: { processes, error: null } }); - } catch (e) { - if (useOverlays.getState().attach) - useOverlays.setState({ attach: { processes: [], error: errorText(e) || "Cannot list processes" } }); - } -} - function cursor(): { path: string; line: number; selection: string } | null { const ed = activeEditor(); if (!ed) return null; @@ -891,6 +871,15 @@ export function registerDebugActions(): () => void { description: "Attach the debugger to a running Java, Node.js, Python, Go or native process", run: () => void openAttachPopup(), }, + { + id: "debug.attachUnity", + title: "Attach to Unity Process", + category: "Run", + icon: "debug", + hidden: true, + when: "projectOpen", + run: ({ arg }) => openAttachPopup("unity", arg as RunConfig | undefined), + }, { id: "debug.debugInBrowser", title: "Debug in Browser", diff --git a/src/features/debugger/attach.ts b/src/features/debugger/attach.ts index 65c2f29aa..04edf1e21 100644 --- a/src/features/debugger/attach.ts +++ b/src/features/debugger/attach.ts @@ -7,6 +7,7 @@ import type { AttachKind, AttachableProcess, LaunchConfig } from "@/platform/ipc import { javaAttachConfig } from "./java"; export const KIND_LABELS: Record = { + unity: "Unity Editor", java: "Java (JDWP)", node: "Node.js", python: "Python (debugpy)", @@ -15,7 +16,7 @@ export const KIND_LABELS: Record = { native: "Native (LLDB)", }; -const KIND_ORDER: AttachKind[] = ["java", "node", "python", "dotnet", "go", "native"]; +const KIND_ORDER: AttachKind[] = ["unity", "java", "node", "python", "dotnet", "go", "native"]; export type AttachRow = | { kind: "group"; key: string; label: string; count: number } @@ -64,6 +65,14 @@ function base(p: AttachableProcess, cwd: string, extra: Record) export async function attachConfig(p: AttachableProcess, root: string): Promise { const skip = workflowSettings().debugger.skipLibraryCode; switch (p.kind) { + case "unity": + return { + ...base(p, root, { + name: `Unity Editor (${p.pid})`, + __exceptionOptions: [], + }), + adapter: "unity", + }; case "java": return javaAttachConfig( { name: `${p.name} (${p.pid})`, module: "", hostName: p.host ?? "localhost", port: p.port! }, diff --git a/src/features/debugger/attachPopup.ts b/src/features/debugger/attachPopup.ts new file mode 100644 index 000000000..d2f6bc425 --- /dev/null +++ b/src/features/debugger/attachPopup.ts @@ -0,0 +1,44 @@ +import { executeAction } from "@/platform/actions"; +import { call, commands, isTauri, type RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { notifications } from "@/workbench/contributions"; +import { missingAdapter } from "./missingAdapter"; +import { useOverlays } from "./ui/popoverStore"; + +/** Applies only the latest request of the open popup; results for a closed or refreshed one are dropped. */ +export async function openAttachPopup(mode: "all" | "unity" = "all", runConfig?: RunConfig) { + if (!isTauri()) { + notifications().notify({ group: "run", level: "warning", title: "Attaching needs the desktop app" }); + return; + } + const projectRoot = useProject.getState().project?.root ?? null; + const pending = { processes: null, error: null, mode, projectRoot, runConfig }; + useOverlays.setState({ attach: pending }); + const current = () => + useOverlays.getState().attach === pending && (useProject.getState().project?.root ?? null) === projectRoot; + try { + const processes = await call( + mode === "unity" ? commands.debugUnityProcesses() : commands.debugAttachableProcesses(), + ); + if (current()) useOverlays.setState({ attach: { ...pending, processes } }); + } catch (e) { + if (current()) + useOverlays.setState({ + attach: { + ...pending, + processes: [], + error: e instanceof Error ? e.message : String(e), + installTool: mode === "unity" ? missingAdapter("unity", e)?.tool : undefined, + }, + }); + } +} + +export async function installAttachAdapter() { + const state = useOverlays.getState().attach; + if (!state?.installTool) return; + await executeAction("tools.install", state.installTool); + if (useOverlays.getState().attach === state && useProject.getState().project?.root === state.projectRoot) { + await openAttachPopup(state.mode, state.runConfig); + } +} diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index 38a40da7c..03713beca 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -145,6 +145,7 @@ export function activate(): () => void { useProject.subscribe((s, prev) => { const root = s.project?.root ?? null; if (root !== (prev.project?.root ?? null) || s.project?.trusted !== prev.project?.trusted) { + useOverlays.setState({ attach: null }); resetSessions(); loadWatches(root); loadBreakpoints(root); diff --git a/src/features/debugger/missingAdapter.ts b/src/features/debugger/missingAdapter.ts index 3aa30bb97..171d1f101 100644 --- a/src/features/debugger/missingAdapter.ts +++ b/src/features/debugger/missingAdapter.ts @@ -8,6 +8,7 @@ import { tx } from "@/platform/i18n"; /** Adapters the tools installer can provide (adapter id → tool name). */ const INSTALLABLE: Record = { + unity: { tool: "unity-debug", title: "Unity Debugger is not installed" }, "kotlin-debug-adapter": { tool: "kotlin-debug-adapter", title: "The Kotlin debugger is not installed" }, netcoredbg: { tool: "netcoredbg", title: "netcoredbg is not installed" }, debugpy: { tool: "debugpy", title: "debugpy is not installed" }, diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index 000866774..2bba4af2c 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -33,6 +33,7 @@ import { type SpecialBreakpoint, } from "../breakpoints/special"; import { attachConfig, attachDetail, attachRows, type AttachRow } from "../attach"; +import { openAttachPopup, installAttachAdapter } from "../attachPopup"; import { exceptionGroups, filterHint, @@ -915,6 +916,7 @@ function AttachPopup() { const root = useProject((s) => s.project?.root ?? null); const [filter, setFilter] = useState(""); const [active, setActive] = useState(0); + const [installing, setInstalling] = useState(false); const rows = useMemo(() => attachRows(state?.processes ?? [], filter), [state?.processes, filter]); const firstItem = rows.findIndex((r) => r.kind === "process"); const activeIndex = rows[active]?.kind === "process" ? active : firstItem; @@ -925,10 +927,11 @@ function AttachPopup() { useOverlays.setState({ attach: null }); }; const attach = async (p: AttachableProcess) => { + if (state.projectRoot !== undefined && state.projectRoot !== root) return close(); close(); if (!root) return; try { - await startSession(await attachConfig(p, root), { rerunnable: false }); + await startSession(await attachConfig(p, root), { rerunnable: false, runConfig: state.runConfig }); } catch (e) { notifications().notify({ group: "run", @@ -948,8 +951,44 @@ function AttachPopup() { } }; return ( - + { + setActive(0); + void openAttachPopup(state.mode, state.runConfig); + }, + }, + { label: "Cancel", role: "cancel", onClick: close }, + { + label: "Attach", + role: "default", + disabled: rows[activeIndex]?.kind !== "process" || installing, + onClick: () => { + const row = rows[activeIndex]; + if (row?.kind === "process") void attach(row.process); + }, + }, + ]} + >
+ {state.mode === "unity" && ( +

+ + Open the project in Unity Editor, enable Editor Attaching and switch to Debug Mode. Select its process + below. Stopping debugging disconnects without closing Unity. + +

+ )} { @@ -975,7 +1014,20 @@ function AttachPopup() { Loading processes…
) : state.error ? ( -
{state.error}
+
+
{state.error}
+ {state.installTool && ( + + )} +
) : ( items={rows} @@ -996,7 +1048,11 @@ function AttachPopup() { className={styles.attachList} empty={
- {filter ? tx`No attachable processes match the filter.` : tx`No attachable processes.`} + {filter + ? tx`No attachable processes match the filter.` + : state.mode === "unity" + ? tx`No Unity Editor processes found. Open Unity Editor, then refresh.` + : tx`No attachable processes.`}
} renderItem={(r) => diff --git a/src/features/debugger/ui/popoverStore.ts b/src/features/debugger/ui/popoverStore.ts index 3b5e1ff45..7de24b4b7 100644 --- a/src/features/debugger/ui/popoverStore.ts +++ b/src/features/debugger/ui/popoverStore.ts @@ -15,7 +15,14 @@ interface OverlayState { breakpoints: { path?: string; id?: string } | null; chooser: { configs: RunConfig[] } | null; /** Attach to Process popup; `processes` is null while loading. */ - attach: { processes: AttachableProcess[] | null; error: string | null } | null; + attach: { + processes: AttachableProcess[] | null; + error: string | null; + mode?: "all" | "unity"; + projectRoot?: string | null; + installTool?: string; + runConfig?: RunConfig; + } | null; /** * Smart Step Into: picked in the editor when `inline` is set (targets sorted * by position, `index` the selected one), else in the chooser dialog. diff --git a/src/features/run/RunWidget.test.tsx b/src/features/run/RunWidget.test.tsx index cab613355..985352e64 100644 --- a/src/features/run/RunWidget.test.tsx +++ b/src/features/run/RunWidget.test.tsx @@ -1,8 +1,8 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { executeAction, executeActionFrom, getAction, registerAction } from "@/platform/actions"; +import { executeAction, executeActionFrom, getAction, isActionEnabled, registerAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; -import type { RunConfig } from "@/platform/ipc"; +import type { ProjectInfo, RunConfig } from "@/platform/ipc"; import { registerMenuGroup, registerRunConfigType, @@ -10,6 +10,7 @@ import { type DebugRunSession, } from "@/workbench/contributions"; import { useContextMenuStore } from "@/ui"; +import { useProject } from "@/platform/project"; import { applicationConfig } from "./application"; import { activate } from "./index"; import { RunWidget } from "./RunWidget"; @@ -52,6 +53,7 @@ const debug = (c: RunConfig, startedAt = 2): DebugRunSession => ({ }); let dispose: () => void; beforeEach(() => { + useProject.setState({ project: null }); resetRuns(); useRun.setState({ configs: [app, npm], selectedId: app.id, loaded: true }); useDebugRunSessions.setState({ sessions: [] }); @@ -61,9 +63,51 @@ beforeEach(() => { afterEach(() => { cleanup(); dispose(); + useProject.setState({ project: null }); useDebugRunSessions.setState({ sessions: [] }); }); +function openUnity() { + useProject.setState({ + project: { + root: "/game", + name: "Game", + trusted: true, + isGit: false, + settings: {} as ProjectInfo["settings"], + unity: { editorVersion: "6000.0.1f1", projects: [], solutions: [] }, + }, + }); +} + +it("keeps other configurations available in a Unity project", () => { + openUnity(); + useRun.setState({ configs: [app, npm], selectedId: app.id, loaded: true }); + render(); + expect(screen.getByRole("button", { name: `Run '${app.name}'` })).toBeEnabled(); + expect(isActionEnabled(getAction("run.run")!)).toBe(true); + expect(isActionEnabled(getAction("run.chooseConfig")!)).toBe(true); +}); + +it("attaches when the Unity configuration is debugged", async () => { + openUnity(); + const unity = { ...config("unity-editor"), name: "Unity Editor", kind: "unity-editor", command: "" }; + useRun.setState({ configs: [unity, app], selectedId: unity.id, loaded: true }); + const attach = vi.fn(); + const unregister = registerAction({ id: "debug.attachUnity", title: "Attach", run: attach }); + try { + render(); + expect(screen.getByRole("button", { name: `'${unity.name}' can only be debugged` })).toBeDisabled(); + await act(async () => { + await executeAction("run.debug"); + }); + expect(attach).toHaveBeenCalledOnce(); + expect(useRun.getState().configs).toContain(app); + } finally { + unregister(); + } +}); + it("reruns and stops the selected configuration among several running sessions", () => { useRun.setState({ sessions: [run(app), run(npm, 3)] }); render(); diff --git a/src/features/run/chooserPinned.test.tsx b/src/features/run/chooserPinned.test.tsx index 847c3d37a..8cf9315e0 100644 --- a/src/features/run/chooserPinned.test.tsx +++ b/src/features/run/chooserPinned.test.tsx @@ -67,6 +67,32 @@ it("lists pinned configurations first, in pin order, and not again in their grou expect(names(buildRows(configs, "s", null, [], ["serve"]))).toEqual(["[Pinned]", "serve", "---", "edit"]); }); +it("adds and selects a Unity attach configuration without hiding other configurations", async () => { + useProject.setState({ project: { root: "/pinned", unity: {} } as never }); + await loadConfigs(); + expect(useRun.getState().configs.map((c) => c.id)).toEqual(["build", "serve", "App", "unity-editor"]); + expect(useRun.getState().selectedId).toBe("unity-editor"); + await loadConfigs(); + expect(useRun.getState().configs.filter((c) => c.kind === "unity-editor")).toHaveLength(1); +}); + +it("keeps a configuration whose id collides with the Unity default", async () => { + useProject.setState({ project: { root: "/pinned", unity: {} } as never }); + ipc.runConfigs.mockResolvedValue({ status: "ok", data: [config("unity-editor")] }); + await loadConfigs(); + expect(useRun.getState().configs.map((c) => c.id)).toEqual(["unity-editor", "unity-editor-attach"]); + expect(useRun.getState().selectedId).toBe("unity-editor-attach"); +}); + +it("retains a saved Unity configuration and selected configuration", async () => { + useProject.setState({ project: { root: "/pinned", unity: {} } as never }); + ipc.runConfigs.mockResolvedValue({ status: "ok", data: [...configs, config("my-unity", "unity-editor")] }); + useRun.setState({ selectedId: "serve" }); + await loadConfigs(); + expect(useRun.getState().configs.filter((c) => c.kind === "unity-editor")).toHaveLength(1); + expect(useRun.getState().selectedId).toBe("serve"); +}); + it("keeps pins per project across reloads", async () => { await loadConfigs(); togglePinned("serve"); diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 3f63fb02a..24e2d59c3 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -104,6 +104,7 @@ import { TEST_TREE_FOCUS, testTree } from "./testTree"; import { startAgentRun, trimAgentArchive, type AgentRunRequest } from "./agentRuns"; import { compoundTargets, selectedTarget } from "./sessionTargets"; import { tx } from "@/platform/i18n"; +import { UNITY_CONFIG_KIND, showUnityAttach } from "./unity"; function trackFailedTestSelection(): () => void { let signature = ""; @@ -171,6 +172,7 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho } if (remoteDebugBlocked(config)) return; if (!(await prepareLaunch(config, chain, show))) return; + if (config.kind === UNITY_CONFIG_KIND) return showUnityAttach(config); // Python on a Docker / Compose target: debugpy in the container, the debugger attaches. if (containerDebuggable(config) && getAction("debug.attach")) { await debugInContainer(config); @@ -488,6 +490,14 @@ export function activate(): () => void { when: "projectOpen", run: () => debugSelected(), }, + { + id: "run.attachUnity", + title: "Attach to Unity Process", + category: "Run", + icon: "debug", + when: "projectOpen", + run: () => showUnityAttach(), + }, { id: "run.runContext", title: "Run Context Configuration", diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 82e702d23..240018faa 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -65,6 +65,7 @@ import { tomcatBrowserUrl } from "./tomcat"; import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun"; import { openUrl } from "./navigate"; import { tx } from "@/platform/i18n"; +import { UNITY_CONFIG_KIND } from "./unity"; /** The permanent "Current File" pseudo-configuration of the chooser (runs the active file's context). */ export const CURRENT_FILE = "current-file"; @@ -240,11 +241,29 @@ export async function loadConfigs(): Promise { const temps = kept.length ? await call(commands.runApplySettings(kept)).catch(() => kept) : kept; if (useProject.getState().project?.root !== root) return; const configs = [...saved, ...temps]; + if (useProject.getState().project?.unity && !configs.some((config) => config.kind === UNITY_CONFIG_KIND)) { + let id = "unity-editor"; + while (configs.some((config) => config.id === id)) id += "-attach"; + configs.push({ + id, + name: "Unity Editor", + kind: UNITY_CONFIG_KIND, + command: "", + args: [], + cwd: null, + env: {}, + detected: true, + isTest: false, + debugAdapter: null, + }); + } const stored = useRun.getState().selectedId ?? readSelected(root); const selectedId = stored === CURRENT_FILE || configs.some((c) => c.id === stored) ? stored - : (defaultSelection(saved)?.id ?? CURRENT_FILE); + : (configs.find((config) => config.kind === UNITY_CONFIG_KIND)?.id ?? + defaultSelection(saved)?.id ?? + CURRENT_FILE); useRun.setState({ configs, temporary: temps.map((t) => t.id), diff --git a/src/features/run/types.ts b/src/features/run/types.ts index dae11c708..4daa58e38 100644 --- a/src/features/run/types.ts +++ b/src/features/run/types.ts @@ -28,6 +28,7 @@ import { dotnetProjectType, dotnetTestType } from "./dotnetTypes"; import { rakeType, rspecType, rubyScriptType } from "./rubyTypes"; import { djangoTestType } from "./djangoTypes"; import { phpunitType } from "./phpunitTypes"; +import { UNITY_CONFIG_KIND } from "./unity"; export const COMPOUND = "compound"; @@ -475,6 +476,14 @@ const pytest: RunConfigTypeContribution = { }; export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [ + { + id: UNITY_CONFIG_KIND, + label: "Unity Editor", + icon: "attach-to-process", + debugOnly: true, + fields: [], + commandLine: () => null, + }, shell, program, npm, diff --git a/src/features/run/unity.ts b/src/features/run/unity.ts new file mode 100644 index 000000000..5f6625a1d --- /dev/null +++ b/src/features/run/unity.ts @@ -0,0 +1,13 @@ +import { executeAction, getAction } from "@/platform/actions"; +import type { RunConfig } from "@/platform/ipc"; +import { notifications } from "@/workbench/contributions"; + +export const UNITY_CONFIG_KIND = "unity-editor"; + +export async function showUnityAttach(config?: RunConfig): Promise { + if (!getAction("debug.attachUnity")) { + notifications().notify({ group: "run", level: "warning", title: "Debugger is not available" }); + return; + } + await executeAction("debug.attachUnity", config); +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e16515758..6991b7d83 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,4 +1,13 @@ { + "Unity Editor": "Unity Editor", + "Attach to Unity Process": "Attach to Unity Process", + "Open the project in Unity Editor, enable Editor Attaching and switch to Debug Mode. Select its process below. Stopping debugging disconnects without closing Unity.": "Open the project in Unity Editor, enable Editor Attaching and switch to Debug Mode. Select its process below. Stopping debugging disconnects without closing Unity.", + "No Unity Editor processes found. Open Unity Editor, then refresh.": "No Unity Editor processes found. Open Unity Editor, then refresh.", + "Install Unity Debugger": "Install Unity Debugger", + "Unity Debugger is not installed": "Unity Debugger is not installed", + "Debugger is not available": "Debugger is not available", + "Attach": "Attach", + "Installing…": "Installing…", "moved from {oldPath}": "moved from {oldPath}", "Symbolic link": "Symbolic link", "Copy as TSV": "Copy as TSV", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 84c3226dc..99a527eab 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,4 +1,12 @@ { + "Unity Editor": "Unity 编辑器", + "Attach to Unity Process": "附加到 Unity 进程", + "Open the project in Unity Editor, enable Editor Attaching and switch to Debug Mode. Select its process below. Stopping debugging disconnects without closing Unity.": "在 Unity 编辑器中打开项目,启用 Editor Attaching 并切换到 Debug Mode,然后在下方选择对应进程。停止调试会断开连接,Unity 编辑器会继续运行。", + "No Unity Editor processes found. Open Unity Editor, then refresh.": "未找到 Unity 编辑器进程。打开 Unity 编辑器后刷新。", + "Install Unity Debugger": "安装 Unity 调试器", + "Unity Debugger is not installed": "尚未安装 Unity 调试器", + "Attach": "附加", + "Installing…": "正在安装…", "Symbolic link": "符号链接", "Copy as TSV": "复制为 TSV", "Copy as CSV": "复制为 CSV",