From 2129efd1968599a58f6deb723294bcba01afc261 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Thu, 19 Nov 2026 18:23:30 +0900 Subject: [PATCH] feat(debugger): add Flutter DevTools tool windows (#4422) Flutter projects get four tool windows on the right, as in the Flutter plugin: Flutter Inspector (one tab per app started with Debug, selecting a widget jumps to its source), Flutter DevTools, Flutter Deep Links and Flutter DevTools Extensions. They embed one dart devtools --machine server per trusted project (stopped on close, trust revoke or quit); the VM Service URI comes from the Dart debug adapter's dart.debuggerUris. Links in embedded pages that open a new window go to the system browser. Icons from flutter-intellij (BSD-3-Clause, THIRD_PARTY_LICENSES.md). Refs #4096 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- THIRD_PARTY_LICENSES.md | 34 ++ crates/ide-core/src/event.rs | 12 + crates/ide-dap/src/lib.rs | 16 + crates/ide-dap/src/session.rs | 18 ++ crates/ide-dap/src/tests.rs | 35 ++ crates/ide-flutter/Cargo.toml | 2 +- crates/ide-flutter/src/devtools.rs | 299 ++++++++++++++++++ crates/ide-flutter/src/lib.rs | 28 +- crates/ide-host/src/lib.rs | 3 + crates/ide-host/src/ops/flutter.rs | 15 +- crates/ide-host/src/project.rs | 4 + crates/ide-host/src/trust.rs | 1 + src-tauri/src/windows.rs | 16 +- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 11 + .../__tests__/flutterDevTools.test.ts | 93 ++++++ .../__tests__/flutterDevToolsWindows.test.tsx | 153 +++++++++ src/features/debugger/actions.ts | 41 +++ src/features/debugger/flutter/devTools.ts | 148 +++++++++ src/features/debugger/index.ts | 2 + src/features/debugger/state.ts | 16 + src/features/debugger/ui/DebugToolWindow.tsx | 1 + .../debugger/ui/FlutterDevTools.module.css | 30 ++ src/features/debugger/ui/FlutterDevTools.tsx | 159 ++++++++++ src/platform/i18n.test.ts | 1 + src/platform/locales/text/en.json | 14 + src/platform/locales/text/zh.json | 14 + src/ui/expui/flutter/deepLinks.svg | 8 + src/ui/expui/flutter/deepLinks@20x20.svg | 8 + src/ui/expui/flutter/deepLinks@20x20_dark.svg | 8 + src/ui/expui/flutter/deepLinks_dark.svg | 8 + src/ui/expui/flutter/devTools.svg | 7 + src/ui/expui/flutter/devTools@20x20.svg | 14 + src/ui/expui/flutter/devTools@20x20_dark.svg | 14 + src/ui/expui/flutter/devTools_dark.svg | 7 + src/ui/expui/flutter/extensions.svg | 17 + src/ui/expui/flutter/extensions@20x20.svg | 13 + .../expui/flutter/extensions@20x20_dark.svg | 13 + src/ui/expui/flutter/extensions_dark.svg | 10 + src/ui/expui/flutter/inspector.svg | 8 + src/ui/expui/flutter/inspector@20x20.svg | 15 + src/ui/expui/flutter/inspector@20x20_dark.svg | 15 + src/ui/expui/flutter/inspector_dark.svg | 8 + src/ui/icons.tsx | 7 +- 44 files changed, 1331 insertions(+), 16 deletions(-) create mode 100644 crates/ide-flutter/src/devtools.rs create mode 100644 src/features/debugger/__tests__/flutterDevTools.test.ts create mode 100644 src/features/debugger/__tests__/flutterDevToolsWindows.test.tsx create mode 100644 src/features/debugger/flutter/devTools.ts create mode 100644 src/features/debugger/ui/FlutterDevTools.module.css create mode 100644 src/features/debugger/ui/FlutterDevTools.tsx create mode 100644 src/ui/expui/flutter/deepLinks.svg create mode 100644 src/ui/expui/flutter/deepLinks@20x20.svg create mode 100644 src/ui/expui/flutter/deepLinks@20x20_dark.svg create mode 100644 src/ui/expui/flutter/deepLinks_dark.svg create mode 100644 src/ui/expui/flutter/devTools.svg create mode 100644 src/ui/expui/flutter/devTools@20x20.svg create mode 100644 src/ui/expui/flutter/devTools@20x20_dark.svg create mode 100644 src/ui/expui/flutter/devTools_dark.svg create mode 100644 src/ui/expui/flutter/extensions.svg create mode 100644 src/ui/expui/flutter/extensions@20x20.svg create mode 100644 src/ui/expui/flutter/extensions@20x20_dark.svg create mode 100644 src/ui/expui/flutter/extensions_dark.svg create mode 100644 src/ui/expui/flutter/inspector.svg create mode 100644 src/ui/expui/flutter/inspector@20x20.svg create mode 100644 src/ui/expui/flutter/inspector@20x20_dark.svg create mode 100644 src/ui/expui/flutter/inspector_dark.svg diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index d6946e034..cbd2ccaaf 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -60,6 +60,40 @@ Their original copyright headers and Apache-2.0 licensing are retained. At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`. +## Flutter plugin icons + +`src/ui/expui/flutter/*.svg` are the DevTools tool window icons of +[flutter-intellij](https://github.com/flutter/flutter-intellij), copied unmodified from +`resources/icons/expui/` (commit `d02813ad5890`) under the BSD 3-Clause License: + +```text +Copyright 2016 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + ## JetBrains IntelliJ Platform VCS log graph algorithms `crates/ide-vcs/src/bek.rs` and `src/features/vcs/graph.ts` adapt the Bek ordering, diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index 32a2741aa..ab2ebe5d5 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -370,6 +370,18 @@ pub enum DebugEvent { /// `flutter debug_adapter`'s `flutter.appStarted` event (launch and attach): the session is /// a Flutter app that can take a hot reload now. The plain Dart adapter never sends it. FlutterAppStarted, + /// The VM Service of a Flutter session's app, which DevTools connects to. + FlutterVmService { + uri: String, + /// The Flutter device the app runs on. + device: Option, + }, + /// Flutter's inspector selected a widget: its source, 0-based. + FlutterNavigate { + path: crate::IpcPath, + line: u32, + column: u32, + }, /// The session's capabilities changed after it started: fetch them again. Capabilities, /// The adapter's `invalidated` event: what it shows for `areas` (`all`, `stacks`, `threads`, diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 19c18a191..3916ddae3 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -420,6 +420,22 @@ fn add_flutter_device(arguments: &mut Value, device: Value) { } } +/// The source a `navigate` tool event points at (1-based there). A `package:` location comes +/// with the file the adapter resolved it to. +fn flutter_navigation(body: &Value) -> Option { + if body.get("kind")?.as_str()? != "navigate" { + return None; + } + let data = body.get("data")?; + let uri = data.get("resolvedFileUri").or_else(|| data.get("fileUri"))?.as_str()?; + let position = |key| data.get(key)?.as_u64().map(|n| n.saturating_sub(1) as u32); + Some(ide_core::event::DebugEvent::FlutterNavigate { + path: kotlin_lsp::source_path(uri)?.into(), + line: position("line")?, + column: position("column").unwrap_or(0), + }) +} + fn no_session(s: DebugSessionId) -> IdeError { IdeError::not_found(format!("no debug session {}", s.0)) } diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index 88550fde0..807c71963 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -99,6 +99,9 @@ pub(crate) struct Session { pub js_overrides: tokio::sync::Mutex>>>, /// The file js-debug records the page's CPU profile into, while one is being recorded. pub js_profile: parking_lot::Mutex>, + /// The device of the app `flutter debug_adapter` announced, once it did: the Dart adapter + /// sends the same `dart.*` events. + pub flutter_app: std::sync::OnceLock>, pub jvm_inspector: parking_lot::Mutex>>, /// One inspector request per session at a time. pub inspect_lock: tokio::sync::Mutex<()>, @@ -274,6 +277,7 @@ impl Session { launch_type: std::sync::OnceLock::new(), js_overrides: tokio::sync::Mutex::new(None), js_profile: parking_lot::Mutex::new(None), + flutter_app: std::sync::OnceLock::new(), jvm_inspector: parking_lot::Mutex::new(None), inspect_lock: tokio::sync::Mutex::default(), ended: ide_core::CancellationToken::new(), @@ -898,6 +902,20 @@ async fn on_event(mgr: &Arc, s: &Arc, event: &str, mut bo "profileStarted" => { *s.js_profile.lock() = str_("file").map(std::path::PathBuf::from); } + // Sent before `dart.debuggerUris`, for `launch` and `attach` alike. + "flutter.appStart" => { + let _ = s.flutter_app.set(str_("deviceId")); + } + "dart.debuggerUris" => { + if let (Some(device), Some(uri)) = (s.flutter_app.get(), str_("vmServiceUri")) { + s.emit(DebugEvent::FlutterVmService { uri, device: device.clone() }); + } + } + "dart.toolEvent" if s.flutter_app.get().is_some() => { + if let Some(event) = crate::flutter_navigation(&body) { + s.emit(event); + } + } _ => tracing::trace!("dap: ignored event {event}"), } } diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index b3b10cf93..a7f912e39 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -572,6 +572,20 @@ async fn fake_adapter(stream json!({"type": "event", "event": "hotcodereplace", "body": {"changeType": 3, "message": "Build completed"}}) ); } + "hotRestart" => { + ok!(msg, Value::Null); + let uris = json!({"vmServiceUri": "ws://127.0.0.1:1/t=/ws"}); + let navigate = + |file: &str| json!({"kind": "navigate", "data": {"fileUri": file, "line": 3, "column": 5}}); + // Not Flutter's yet: a plain Dart session sends these too. + send!(json!({"type": "event", "event": "dart.debuggerUris", "body": uris})); + send!(json!({"type": "event", "event": "dart.toolEvent", "body": navigate("file:///early.dart")})); + send!(json!({"type": "event", "event": "flutter.appStart", "body": {"deviceId": "d1"}})); + send!(json!({"type": "event", "event": "dart.debuggerUris", "body": uris})); + send!(json!({"type": "event", "event": "dart.toolEvent", "body": {"kind": "other", "data": {}}})); + send!(json!({"type": "event", "event": "dart.toolEvent", "body": navigate("package:a/a.dart")})); + send!(json!({"type": "event", "event": "dart.toolEvent", "body": navigate("file:///a%20b/main.dart")})); + } "terminate" => { ok!(msg, Value::Null); send!(json!({"type": "event", "event": "terminated"})); @@ -1906,6 +1920,27 @@ async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() { h.wait_event(|e| matches!(e, DebugEvent::FlutterAppStarted)).await; } +#[tokio::test] +async fn flutter_events_need_a_flutter_app() { + let h = harness(Script::default()); + let id = h.start(config()).await.unwrap(); + h.manager.hot_restart(id).await.unwrap(); + let navigate = h.wait_event(|e| matches!(e, DebugEvent::FlutterNavigate { .. })).await; + let DebugEvent::FlutterNavigate { path, line, column } = navigate else { unreachable!() }; + assert_eq!((path.as_ref(), line, column), (Path::new("/a b/main.dart"), 2, 4)); + let events = h.events.lock(); + let count = |want: fn(&DebugEvent) -> bool| { + events.iter().filter(|e| matches!(e, IdeEvent::Debug { event, .. } if want(event))).count() + }; + assert_eq!( + count( + |e| matches!(e, DebugEvent::FlutterVmService { uri, device } if uri == "ws://127.0.0.1:1/t=/ws" && device.as_deref() == Some("d1")) + ), + 1 + ); + assert_eq!(count(|e| matches!(e, DebugEvent::FlutterNavigate { .. })), 1); +} + #[tokio::test] async fn hot_swap_only_for_java_debug() { let h = harness(Script::default()); diff --git a/crates/ide-flutter/Cargo.toml b/crates/ide-flutter/Cargo.toml index b831ae7a3..79e30505a 100644 --- a/crates/ide-flutter/Cargo.toml +++ b/crates/ide-flutter/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ide-flutter" -description = "Flutter devices, kept current by the `flutter daemon` protocol" +description = "Flutter devices from the `flutter daemon` protocol, and the project's DevTools server" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ide-flutter/src/devtools.rs b/crates/ide-flutter/src/devtools.rs new file mode 100644 index 000000000..292e97a97 --- /dev/null +++ b/crates/ide-flutter/src/devtools.rs @@ -0,0 +1,299 @@ +//! One `dart devtools` server per project window, started when first asked for. In `--machine` +//! mode it reports its port as a `server.started` line on stdout. A server that fails or exits +//! is not restarted on its own: the next request starts a new one. + +use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched}; +use ide_core::process::{kill_tree, terminate_tree}; +use ide_core::tool_path::{find_command, search_path_in}; +use parking_lot::{Condvar, Mutex}; +use serde_json::Value; +use std::collections::VecDeque; +use std::path::{Path, PathBuf}; +use std::process::Child; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const START_TIMEOUT: Duration = Duration::from_secs(60); +/// The address embedded pages are allowed to come from, so never `localhost`. +const HOST: &str = "127.0.0.1"; +const ARGS: [&str; 7] = ["devtools", "--machine", "--allow-embedding", "--host", HOST, "--port", "0"]; + +fn started_port(line: &str) -> Option { + let message: Value = serde_json::from_str(line.trim()).ok()?; + if message.get("event")?.as_str()? != "server.started" { + return None; + } + u16::try_from(message.get("params")?.get("port")?.as_u64()?).ok() +} + +/// The `dart` of the SDK `flutter` belongs to, so that DevTools matches the debugged app. +fn dart_executable(root: &Path) -> Option { + let path = search_path_in(root); + find_command("flutter", &path, root) + .and_then(|flutter| { + // On the search path `flutter` is often a link into the SDK. + let flutter = if cfg!(unix) { std::fs::canonicalize(&flutter).unwrap_or(flutter) } else { flutter }; + let dart = flutter.with_file_name(if cfg!(windows) { "dart.bat" } else { "dart" }); + dart.is_file().then_some(dart) + }) + .or_else(|| find_command("dart", &path, root)) +} + +#[derive(Default)] +enum Status { + #[default] + Stopped, + Starting, + Ready(String), + Failed(String), +} + +#[derive(Default)] +struct State { + /// Bumped by every start and stop: a reader of an older process no longer has a say. + generation: u64, + child: Option, + status: Status, +} + +impl State { + fn shut_down(&mut self) { + self.generation += 1; + if let Some(mut child) = self.child.take() { + std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE)); + } + } +} + +struct Shared { + root: PathBuf, + /// Replaces the lookup on the search path (tests). + executable: Option, + timeout: Duration, + state: Mutex, + changed: Condvar, +} + +impl Shared { + /// Applies `status` unless this process was replaced or stopped; false if it was. + fn set(&self, generation: u64, status: Status) -> bool { + let mut state = self.state.lock(); + if state.generation != generation { + return false; + } + state.status = status; + self.changed.notify_all(); + true + } +} + +pub struct DevToolsServer(Arc); + +impl DevToolsServer { + pub fn new(root: PathBuf) -> Self { + Self::with_executable(root, None, START_TIMEOUT) + } + + fn with_executable(root: PathBuf, executable: Option, timeout: Duration) -> Self { + Self(Arc::new(Shared { root, executable, timeout, state: Mutex::default(), changed: Condvar::new() })) + } + + /// The server's address, starting it if none runs. Blocks until it is known. + pub fn url(&self) -> Result { + let shared = &self.0; + let deadline = Instant::now() + shared.timeout; + let mut state = shared.state.lock(); + if matches!(state.status, Status::Stopped | Status::Failed(_)) { + state.generation += 1; + state.status = Status::Starting; + let (shared, generation) = (shared.clone(), state.generation); + std::thread::spawn(move || run(&shared, generation)); + } + loop { + match &state.status { + Status::Ready(url) => return Ok(url.clone()), + Status::Failed(message) => return Err(message.clone()), + Status::Stopped => return Err("Flutter DevTools was stopped".into()), + Status::Starting => {} + } + if shared.changed.wait_until(&mut state, deadline).timed_out() { + state.shut_down(); + let message = "Flutter DevTools did not start in time".to_owned(); + state.status = Status::Failed(message.clone()); + shared.changed.notify_all(); + return Err(message); + } + } + } + + /// Ends the server (project closed, or no longer trusted). + pub fn stop(&self) { + let mut state = self.0.state.lock(); + state.shut_down(); + state.status = Status::Stopped; + self.0.changed.notify_all(); + } + + /// Ends the server before returning, for a process about to exit. + pub fn kill(&self) { + let mut state = self.0.state.lock(); + state.generation += 1; + state.status = Status::Stopped; + if let Some(mut child) = state.child.take() { + kill_tree(&mut child); + } + self.0.changed.notify_all(); + } +} + +/// One server's whole life, on its own thread. +fn run(shared: &Arc, generation: u64) { + let fail = |message: String| { + shared.set(generation, Status::Failed(message)); + }; + let Some(executable) = shared.executable.clone().or_else(|| dart_executable(&shared.root)) else { + return fail("Dart SDK not found: install Flutter or add it to PATH".into()); + }; + let mut child = match spawn_watched(&executable, &ARGS, &shared.root) { + Ok(child) => child, + Err(e) => return fail(format!("could not run {}: {e}", executable.display())), + }; + let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else { + terminate_tree(&mut child, Duration::ZERO); + return fail("no output pipe".into()); + }; + { + let mut state = shared.state.lock(); + if state.generation != generation { + drop(state); + terminate_tree(&mut child, KILL_GRACE); + return; + } + state.child = Some(child); + } + let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL))); + let errors = { + let tail = tail.clone(); + std::thread::spawn(move || { + read_lines(stderr, |line| { + keep_output(&tail, line); + true + }); + }) + }; + read_lines(stdout, |line| match started_port(line) { + Some(port) => shared.set(generation, Status::Ready(format!("http://{HOST}:{port}"))), + None => { + keep_output(&tail, line); + true + } + }); + let _ = errors.join(); + + let mut state = shared.state.lock(); + if state.generation != generation { + return; + } + let child = state.child.take(); + state.status = if matches!(state.status, Status::Ready(_)) { + Status::Stopped + } else { + let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n"); + Status::Failed(if message.is_empty() { "dart devtools exited".into() } else { message }) + }; + shared.changed.notify_all(); + drop(state); + if let Some(mut child) = child { + std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_server_started_gives_a_port() { + let line = + r#"{"event":"server.started","method":"server.started","params":{"host":"127.0.0.1","port":9100,"pid":1}}"#; + assert_eq!(started_port(line), Some(9100)); + assert_eq!(started_port(r#"{"event":"server.dtdStarted","params":{"uri":"ws://x"}}"#), None); + assert_eq!(started_port("Serving DevTools"), None); + } + + #[cfg(unix)] + mod process { + use super::*; + use std::os::unix::fs::PermissionsExt; + + const STARTED: &str = r#"echo '{"event":"server.started","params":{"port":4242}}'"#; + + fn server(dir: &Path, script: &str, timeout: Duration) -> DevToolsServer { + let path = dir.join("dart"); + std::fs::write(&path, format!("#!/bin/sh\necho run >> runs\n{script}")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + DevToolsServer::with_executable(dir.to_owned(), Some(path), timeout) + } + + fn runs(dir: &Path) -> usize { + std::fs::read_to_string(dir.join("runs")).map_or(0, |s| s.lines().count()) + } + + fn wait_for(what: &str, done: impl Fn() -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !done() { + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(10)); + } + } + + #[test] + fn a_running_server_is_shared_and_stop_ends_it() { + let dir = tempfile::tempdir().unwrap(); + let script = format!("echo \"$*\" > args\necho $$ > pid\n{STARTED}\nexec sleep 30"); + let devtools = server(dir.path(), &script, Duration::from_secs(10)); + assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242"); + assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242"); + assert_eq!(runs(dir.path()), 1); + let args = std::fs::read_to_string(dir.path().join("args")).unwrap(); + assert_eq!(args.trim(), ARGS.join(" ")); + + let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap(); + devtools.stop(); + let alive = || { + let mut probe = std::process::Command::new("kill"); + probe.args(["-0", pid.trim()]).stderr(std::process::Stdio::null()).status().unwrap().success() + }; + wait_for("the server to end", || !alive()); + } + + #[test] + fn a_failure_is_reported_and_only_a_new_request_retries() { + let dir = tempfile::tempdir().unwrap(); + let devtools = server(dir.path(), "echo boom >&2\nexit 3", Duration::from_secs(10)); + assert_eq!(devtools.url().unwrap_err(), "boom"); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(runs(dir.path()), 1); + assert_eq!(devtools.url().unwrap_err(), "boom"); + assert_eq!(runs(dir.path()), 2); + } + + #[test] + fn a_server_that_exits_is_not_restarted_until_asked() { + let dir = tempfile::tempdir().unwrap(); + let devtools = server(dir.path(), STARTED, Duration::from_secs(10)); + devtools.url().unwrap(); + wait_for("the exit to be noticed", || matches!(devtools.0.state.lock().status, Status::Stopped)); + assert_eq!(runs(dir.path()), 1); + devtools.url().unwrap(); + assert_eq!(runs(dir.path()), 2); + } + + #[test] + fn a_server_that_never_reports_times_out() { + let dir = tempfile::tempdir().unwrap(); + let devtools = server(dir.path(), "exec sleep 30", Duration::from_millis(200)); + assert_eq!(devtools.url().unwrap_err(), "Flutter DevTools did not start in time"); + } + } +} diff --git a/crates/ide-flutter/src/lib.rs b/crates/ide-flutter/src/lib.rs index 88500200a..df64b044f 100644 --- a/crates/ide-flutter/src/lib.rs +++ b/crates/ide-flutter/src/lib.rs @@ -8,6 +8,10 @@ //! a watcher in its process group ends the group once the IDE is gone, even after a crash. A //! daemon that fails stays failed until the user restarts it. +mod devtools; + +pub use devtools::DevToolsServer; + use ide_android::AndroidDevice; use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList}; use ide_core::process::{kill_tree, own_group, prepare, terminate_tree}; @@ -227,26 +231,28 @@ fn refresh_adb(shared: &Arc, generation: u64) { }); } -/// `flutter daemon`, ended with its whole process group when process `parent` is gone. +/// A tool that does not end with its stdin, ended with its whole process group when process +/// `parent` is gone. #[cfg(unix)] -fn daemon_command(executable: &Path, parent: u32) -> Command { +fn watched_command(executable: &Path, args: &[&str], parent: u32) -> Command { const WATCHED: &str = r#"(while kill -0 "$1" 2>/dev/null; do sleep 5; done; kill -KILL 0) /dev/null 2>&1 & -exec "$2" daemon"#; +shift +exec "$@""#; let mut cmd = Command::new("/bin/sh"); - cmd.args(["-c", WATCHED, "sh"]).arg(parent.to_string()).arg(executable); + cmd.args(["-c", WATCHED, "sh"]).arg(parent.to_string()).arg(executable).args(args); cmd } -// No watcher on Windows, so a crashed IDE leaves the daemon; a Job Object would cover it. +// No watcher on Windows, so a crashed IDE leaves the tool; a Job Object would cover it. #[cfg(not(unix))] -fn daemon_command(executable: &Path, _parent: u32) -> Command { +fn watched_command(executable: &Path, args: &[&str], _parent: u32) -> Command { let mut cmd = Command::new(executable); - cmd.arg("daemon"); + cmd.args(args); cmd } -fn spawn_daemon(executable: &Path, root: &Path) -> std::io::Result { - let mut cmd = daemon_command(executable, std::process::id()); +fn spawn_watched(executable: &Path, args: &[&str], root: &Path) -> std::io::Result { + let mut cmd = watched_command(executable, args, std::process::id()); cmd.current_dir(root).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); prepare(own_group(&mut cmd)); cmd.spawn() @@ -299,7 +305,7 @@ fn run(shared: &Arc, generation: u64) { let Some(executable) = executable else { return finish(shared, generation, FlutterDaemonStatus::NotInstalled); }; - let mut child = match spawn_daemon(&executable, &shared.root) { + let mut child = match spawn_watched(&executable, &["daemon"], &shared.root) { Ok(child) => child, Err(e) => { let message = format!("could not run {}: {e}", executable.display()); @@ -530,7 +536,7 @@ cat > /dev/null std::fs::write(&flutter, "#!/bin/sh\necho $$ > pid\nexec sleep 60\n").unwrap(); std::fs::set_permissions(&flutter, std::fs::Permissions::from_mode(0o755)).unwrap(); let mut ide = Command::new("sleep").arg("60").spawn().unwrap(); - let mut cmd = daemon_command(&flutter, ide.id()); + let mut cmd = watched_command(&flutter, &["daemon"], ide.id()); cmd.current_dir(dir.path()).stdin(Stdio::piped()); let mut daemon = own_group(&mut cmd).spawn().unwrap(); wait_for("the daemon", || dir.path().join("pid").is_file()); diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index d4a495612..4fc6cfc8f 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -344,6 +344,7 @@ impl Host { project.documents.clear_workspace_edit_history(); project.agents.shutdown(); project.flutter.stop(); + project.devtools.stop(); project.notebooks.stop_admission(); // What the closing window started goes with it — the builds and searches it // asked for, its runs, its shells and its debug sessions — and its language @@ -464,6 +465,7 @@ impl Host { self.terminals.kill_all(); for project in self.projects() { project.flutter.kill(); + project.devtools.kill(); } } @@ -487,6 +489,7 @@ impl Host { for project in &projects { project.files_events_active.store(false, std::sync::atomic::Ordering::Release); project.flutter.kill(); + project.devtools.kill(); } for project in &projects { project.plugin_diagnostics.close(); diff --git a/crates/ide-host/src/ops/flutter.rs b/crates/ide-host/src/ops/flutter.rs index 28c32ebb0..8529780a2 100644 --- a/crates/ide-host/src/ops/flutter.rs +++ b/crates/ide-host/src/ops/flutter.rs @@ -2,8 +2,8 @@ //! adapter run too, so a remote project lists the devices of its remote machine. use crate::Host; use ide_command::command; -use ide_core::IdeResult; use ide_core::event::FlutterDeviceList; +use ide_core::{IdeError, IdeResult}; /// The project's Flutter devices, starting its `flutter daemon` on first use. Changes arrive as /// `IdeEvent::FlutterDevices`. @@ -25,4 +25,15 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult IdeResult { + let project = host.project(window)?; + tokio::task::spawn_blocking(move || project.devtools.url()) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + .map_err(IdeError::unavailable) +} + +ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_devtools_url); diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 8a21912b6..b892a65e7 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -63,6 +63,8 @@ pub struct Project { pub notebooks: Arc, /// Flutter's devices; its daemon starts when the UI first asks for them. pub(crate) flutter: ide_flutter::FlutterDaemon, + /// Flutter DevTools; its server starts when the UI first asks for it. + pub(crate) devtools: ide_flutter::DevToolsServer, pub(crate) kotlin_bridge: Option>, pub(crate) phpstan: Option>, pub(crate) watcher: Arc, @@ -605,6 +607,7 @@ impl Host { plugin_diagnostics, trusted, flutter: ide_flutter::FlutterDaemon::new(root.clone(), sink.clone()), + devtools: ide_flutter::DevToolsServer::new(root.clone()), root, sink, languages, @@ -818,6 +821,7 @@ impl Host { plugin_diagnostics, trusted: Arc::new(AtomicBool::new(false)), flutter: ide_flutter::FlutterDaemon::new(dir.clone(), sink.clone()), + devtools: ide_flutter::DevToolsServer::new(dir.clone()), sink, languages, settings, diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index a7e0c28d5..b70f087c1 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -283,6 +283,7 @@ impl crate::Host { self.environment.direnv_closed(&project.root); project.agents.shutdown(); project.flutter.stop(); + project.devtools.stop(); self.processes.kill_project(&project.root); project.notebooks.restrict().await; let windows: Vec<_> = self diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 1e07982ba..4c45a1e95 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -749,7 +749,7 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult< #[cfg(target_os = "linux")] let show_after_build = crate::linux_window_state::prepare(app, &mut config); let window = WebviewWindowBuilder::from_config(app, &config) - .and_then(|b| dev_font_preferences(b).build()) + .and_then(|b| dev_font_preferences(b).on_new_window(open_popup_in_browser).build()) .map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?; #[cfg(target_os = "linux")] decorate_csd(&window); @@ -2080,6 +2080,20 @@ fn centered(px: f64, py: f64, pw: f64, ph: f64, w: f64, h: f64) -> (f64, f64) { (px + (pw - w) / 2.0, py + ((ph - h) / 2.0).max(0.0)) } +/// A link in an embedded page that asks for a new window (Flutter DevTools' documentation links) +/// opens in the system browser; the IDE itself never needs such a window. +fn open_popup_in_browser( + url: tauri::Url, + _features: tauri::webview::NewWindowFeatures, +) -> tauri::webview::NewWindowResponse { + if matches!(url.scheme(), "http" | "https") + && let Err(e) = tauri_plugin_opener::open_url(url.as_str(), None::<&str>) + { + tracing::warn!("cannot open {url}: {e}"); + } + tauri::webview::NewWindowResponse::Deny +} + /// Reproduce WKWebView's user-font restriction before WKWebView creation. The /// private selector and environment override are absent from release builds. #[cfg(all(debug_assertions, target_os = "macos"))] diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 5c979afbe..3c7a72c43 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -251,6 +251,7 @@ find_symbols_named always project_host bin flutter_daemon_restart trusted project_host bindings sync flutter_devices trusted project_host bindings sync flutter_devices_refresh trusted project_host bindings sync +flutter_devtools_url trusted project_host bindings async fs_compare_directories always project_host bindings async fs_copy always project_host bindings async fs_copy_merge always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 060dce2b5..7efe3bcc1 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -616,6 +616,11 @@ export const commands = { flutterDevices: () => typedError(__TAURI_INVOKE("flutter_devices")), /** Looks at adb again, for Android devices Flutter doesn't report (awaiting authorization, offline). */ flutterDevicesRefresh: () => typedError(__TAURI_INVOKE("flutter_devices_refresh")), + /** + * The address of the project's DevTools server, started on first use. A server that failed or + * exited is only started again by the next request. + */ + flutterDevtoolsUrl: () => typedError(__TAURI_INVOKE("flutter_devtools_url")), fsCompareDirectories: (left: string, right: string, request: RequestId, onProgress: Channel) => typedError(__TAURI_INVOKE("fs_compare_directories", { left, right, request, onProgress })), fsCopy: (from: string, to: string) => typedError(__TAURI_INVOKE("fs_copy", { from, to })), fsCopyMerge: (sourceRoot: string, destinationRoot: string, path: string, overwrite: boolean) => typedError(__TAURI_INVOKE("fs_copy_merge", { sourceRoot, destinationRoot, path, overwrite })), @@ -4784,6 +4789,12 @@ export type DebugEvent = * a Flutter app that can take a hot reload now. The plain Dart adapter never sends it. */ { kind: "flutterAppStarted" } | +/** The VM Service of a Flutter session's app, which DevTools connects to. */ +{ kind: "flutterVmService"; uri: string; +/** The Flutter device the app runs on. */ +device: string | null } | +/** Flutter's inspector selected a widget: its source, 0-based. */ +{ kind: "flutterNavigate"; path: IpcPath; line: number; column: number } | /** The session's capabilities changed after it started: fetch them again. */ { kind: "capabilities" } | /** diff --git a/src/features/debugger/__tests__/flutterDevTools.test.ts b/src/features/debugger/__tests__/flutterDevTools.test.ts new file mode 100644 index 000000000..870665518 --- /dev/null +++ b/src/features/debugger/__tests__/flutterDevTools.test.ts @@ -0,0 +1,93 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const openUrl = vi.hoisted(() => vi.fn(async (_url: string) => {})); +vi.mock("@/platform/openUrl", () => ({ openExternalUrl: openUrl })); +const remote = vi.hoisted(() => ({ on: false })); +vi.mock("@/platform/remote", async (importOriginal) => ({ + ...(await importOriginal()), + isRemoteWindow: () => remote.on, +})); +const devtoolsUrl = vi.hoisted(() => vi.fn()); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, commands: { ...real.commands, flutterDevtoolsUrl: devtoolsUrl } }; +}); +const openFile = vi.hoisted(() => vi.fn(async () => {})); +const notes = vi.hoisted(() => [] as Array<{ title: string; body?: unknown }>); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + maybeEditorService: () => ({ openFile }), + notifications: () => ({ notify: (n: (typeof notes)[number]) => void notes.push(n) }), +})); + +import { executeAction } from "@/platform/actions"; +import { getContext } from "@/platform/context"; +import type { DebugSessionId } from "@/platform/ipc"; +import { registerDebugActions } from "../actions"; +import { handleDebugEvent, publishContext, useDebug, type DebugSession } from "../state"; + +const id = 7 as DebugSessionId; +const uri = "ws://127.0.0.1:5/a=/ws"; + +describe("Flutter DevTools", () => { + let dispose = () => {}; + + beforeEach(() => { + dispose(); + dispose = registerDebugActions(); + vi.clearAllMocks(); + notes.length = 0; + remote.on = false; + devtoolsUrl.mockResolvedValue({ status: "ok", data: "http://127.0.0.1:9100" }); + const session = { id, name: "app", adapter: "dart", parent: null, status: "running" } as unknown as DebugSession; + useDebug.setState({ sessions: { [id]: session }, active: id }); + publishContext(); + }); + + it("offers DevTools once the session reports its VM Service", () => { + expect(getContext().debugHasVmService).toBe(false); + handleDebugEvent(id, { kind: "flutterVmService", uri, device: null }); + publishContext(); + expect(useDebug.getState().sessions[id]?.vmServiceUri).toBe(uri); + expect(getContext().debugHasVmService).toBe(true); + }); + + it("opens the inspector of the session's app in the browser", async () => { + handleDebugEvent(id, { kind: "flutterVmService", uri, device: null }); + publishContext(); + await executeAction("debug.openDevTools"); + await vi.waitFor(() => expect(openUrl).toHaveBeenCalledOnce()); + const url = new URL(openUrl.mock.calls[0]![0]); + expect(url.origin + url.pathname).toBe("http://127.0.0.1:9100/inspector"); + expect(url.searchParams.get("uri")).toBe(uri); + }); + + it("reports a server that could not start", async () => { + devtoolsUrl.mockResolvedValue({ status: "error", error: { kind: "unavailable", message: "boom" } }); + handleDebugEvent(id, { kind: "flutterVmService", uri, device: null }); + publishContext(); + await executeAction("debug.openDevTools"); + await vi.waitFor(() => expect(notes).toHaveLength(1)); + expect(notes[0]).toMatchObject({ title: "Couldn't open Flutter DevTools", body: "boom" }); + expect(openUrl).not.toHaveBeenCalled(); + }); + + it("explains that a remote project has no DevTools", async () => { + remote.on = true; + handleDebugEvent(id, { kind: "flutterVmService", uri, device: null }); + publishContext(); + await executeAction("debug.openDevTools"); + await vi.waitFor(() => expect(notes).toHaveLength(1)); + expect(devtoolsUrl).not.toHaveBeenCalled(); + expect(openUrl).not.toHaveBeenCalled(); + }); + + it("shows the widget's source without taking the focus", () => { + handleDebugEvent(id, { kind: "flutterNavigate", path: "/app/lib/main.dart", line: 2, column: 4 }); + expect(openFile).toHaveBeenCalledWith("/app/lib/main.dart", { + selection: { line: 2, col: 4 }, + preview: true, + focus: false, + }); + }); +}); diff --git a/src/features/debugger/__tests__/flutterDevToolsWindows.test.tsx b/src/features/debugger/__tests__/flutterDevToolsWindows.test.tsx new file mode 100644 index 000000000..6a5109dac --- /dev/null +++ b/src/features/debugger/__tests__/flutterDevToolsWindows.test.tsx @@ -0,0 +1,153 @@ +import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const devtoolsUrl = vi.hoisted(() => vi.fn()); +const readText = vi.hoisted(() => vi.fn()); +const remote = vi.hoisted(() => ({ on: false })); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, commands: { ...real.commands, flutterDevtoolsUrl: devtoolsUrl, fsReadText: readText } }; +}); +vi.mock("@/platform/remote", async (importOriginal) => ({ + ...(await importOriginal()), + isRemoteWindow: () => remote.on, +})); + +import { emitLocalIdeEvent } from "@/platform/ipc"; +import { getContext } from "@/platform/context"; +import { useProject } from "@/platform/project"; +import { useContributions } from "@/workbench/contributions"; +import { useFlutterDevices } from "@/workbench/flutterDevices"; +import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools, registerDevToolsWindows } from "../flutter/devTools"; +import { useDebug, type DebugSession } from "../state"; +import { FlutterDevToolsTabs, FlutterDevToolsView } from "../ui/FlutterDevTools"; + +const server = "http://127.0.0.1:9100"; +const look = { theme: "dark" as const, background: "1e1f22" }; +const windowOf = (id: string) => DEVTOOLS_WINDOWS.find((w) => w.id === id)!; + +function session(id: number, extra: Partial): DebugSession { + return { id, name: `s${id}`, adapter: "dart", parent: null, status: "running", ...extra } as unknown as DebugSession; +} + +function setSessions(...list: DebugSession[]) { + act(() => + useDebug.setState({ sessions: Object.fromEntries(list.map((s) => [s.id, s])) as Record }), + ); +} + +const frames = () => [...document.querySelectorAll("iframe")]; +const uriOf = (f: HTMLIFrameElement) => new URL(f.src).searchParams.get("uri"); + +describe("Flutter DevTools windows", () => { + beforeEach(() => { + devtoolsUrl.mockReset(); + devtoolsUrl.mockResolvedValue({ status: "ok", data: server }); + useDebug.setState({ sessions: {}, active: null }); + remote.on = false; + }); + afterEach(cleanup); + + it("asks for the pages Android Studio shows", () => { + const query = (id: string) => { + const url = new URL(devToolsUrl(server, windowOf(id), { uri: "ws://a", embedded: look })); + return [url.pathname, url.searchParams.get("embedMode"), url.searchParams.get("hide")]; + }; + expect(query("flutter-inspector")).toEqual(["/inspector", "one", null]); + expect(query("flutter-deep-links")).toEqual(["/deep-links", "one", null]); + expect(query("flutter-devtools")).toEqual(["/", "many", "home,inspector,deep-links,extensions,debugger"]); + expect(query("flutter-devtools-extensions")).toEqual(["/", "many", "all-except-extensions"]); + const url = new URL(devToolsUrl(server, windowOf("flutter-inspector"), { embedded: look })); + expect(url.searchParams.get("theme")).toBe("dark"); + expect(url.searchParams.get("backgroundColor")).toBe("1e1f22"); + expect(url.searchParams.has("uri")).toBe(false); + }); + + it("exists in Flutter projects, run configurations or not", async () => { + const ids = () => [...useContributions.getState().toolWindows.keys()]; + const pubspecs: Record = { + "/app/pubspec.yaml": "name: app\ndependencies:\n flutter:\n sdk: flutter\n", + "/tool/pubspec.yaml": "name: tool\ndependencies:\n args: ^2.0.0\n", + }; + readText.mockImplementation(async (path: string) => + path in pubspecs ? { status: "ok", data: pubspecs[path] } : { status: "error", error: { kind: "notFound" } }, + ); + useProject.setState({ project: { root: "/app" } as never }); + const dispose = registerDevToolsWindows(); + await waitFor(() => expect(ids()).toEqual(expect.arrayContaining(DEVTOOLS_WINDOWS.map((w) => w.id)))); + expect(getContext().flutterDevTools).toBe(true); + + useProject.setState({ project: { root: "/tool" } as never }); + await waitFor(() => expect(ids()).not.toContain("flutter-inspector")); + expect(getContext().flutterDevTools).toBe(false); + + // Adding the SDK dependency later brings the windows. + pubspecs["/tool/pubspec.yaml"] += " flutter:\n sdk: flutter\n"; + act(() => emitLocalIdeEvent({ type: "fsChanged", created: [], modified: ["/tool/pubspec.yaml"], removed: [] })); + await waitFor(() => expect(ids()).toContain("flutter-inspector")); + + useProject.setState({ project: { root: "/empty" } as never }); + await waitFor(() => expect(ids()).not.toContain("flutter-inspector")); + dispose(); + useProject.setState({ project: null }); + }); + + it("starts no server for a remote window", async () => { + remote.on = true; + render(); + await screen.findByText("Flutter DevTools isn't available in a remote project yet"); + expect(devtoolsUrl).not.toHaveBeenCalled(); + }); + + it("gives the Inspector one page per running app", async () => { + render( + <> + + + , + ); + await screen.findByText("No running applications"); + expect(frames()).toHaveLength(0); + + useFlutterDevices.setState({ + list: { status: { kind: "ready" }, devices: [{ id: "d1", name: "Pixel" }] } as never, + }); + const first = session(1, { vmServiceUri: "ws://one", flutterDevice: "d1" }); + const second = session(2, { vmServiceUri: "ws://two", flutterDevice: "macos" }); + setSessions(first, second, session(3, {})); + await waitFor(() => expect(frames()).toHaveLength(2)); + expect(frames().map(uriOf)).toEqual(["ws://one", "ws://two"]); + expect(frames().map((f) => f.hidden)).toEqual([true, false]); + expect(screen.getByText("Pixel")).toBeTruthy(); + expect(screen.getByText("macos")).toBeTruthy(); + + setSessions( + { ...first, status: "terminated" } as DebugSession, + { ...second, status: "terminated" } as DebugSession, + ); + await screen.findByText("No running applications"); + }); + + it("keeps the other pages on the latest app and loads them without one", async () => { + render(); + await waitFor(() => expect(frames()).toHaveLength(1)); + expect(uriOf(frames()[0]!)).toBeNull(); + setSessions( + session(1, { vmServiceUri: "ws://one" }), + session(2, { vmServiceUri: "ws://two", status: "terminated" } as never), + ); + await waitFor(() => expect(uriOf(frames()[0]!)).toBe("ws://two")); + }); + + it("shows why the server is missing and asks again only on Refresh", async () => { + devtoolsUrl.mockResolvedValue({ status: "error", error: { kind: "unavailable", message: "boom" } }); + render(); + await screen.findByText(/boom/); + expect(devtoolsUrl).toHaveBeenCalledTimes(1); + devtoolsUrl.mockResolvedValue({ status: "ok", data: server }); + act(() => refreshDevTools("flutter-deep-links")); + await waitFor(() => expect(frames()).toHaveLength(1)); + expect(devtoolsUrl).toHaveBeenCalledTimes(2); + expect(new URL(frames()[0]!.src).pathname).toBe("/deep-links"); + }); +}); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index 3cb9e460d..566686f6c 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -15,6 +15,7 @@ import { import { downloadJdkActions } from "@/platform/jdk"; import { useProject } from "@/platform/project"; import { isRemoteWindow } from "@/platform/remote"; +import { openExternalUrl } from "@/platform/openUrl"; import { activeEditor } from "@/editor/api"; import type { EditorView } from "@codemirror/view"; import { maybeEditorService, notifications, showStatusInfo, toolWindowService } from "@/workbench/contributions"; @@ -49,6 +50,7 @@ import { startPageProfile, stopPageProfile } from "./js/profile"; import { activeCapturedSnapshot, openHeapDump, saveHeapDump } from "./heap/heapDumpFiles"; import { browserLaunch, browserLaunchConfig, browserUrl, installedDebugBrowser, isBrowserConfig } from "./browser"; import { warnPinnedFlutterDevice } from "@/workbench/flutterDevices"; +import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools } from "./flutter/devTools"; import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "./launch"; import { attachConfig } from "./attach"; import { @@ -284,6 +286,20 @@ function browserUnavailable(name: string): boolean { return true; } +/** The browser opens on this desktop, which can't reach a server on a remote project's machine. */ +async function openDevTools(vmServiceUri: string) { + if (isRemoteWindow()) { + notifications().notify({ + group: "run", + level: "warning", + title: "Flutter DevTools isn't available in a remote project yet", + }); + return; + } + const server = await call(commands.flutterDevtoolsUrl()); + await openExternalUrl(devToolsUrl(server, { page: "inspector" }, { uri: vmServiceUri })); +} + async function startBrowser(config: RunConfig, root: string, show?: boolean) { if (browserUnavailable(config.name)) return; const launch = browserLaunchConfig(config, root); @@ -773,6 +789,31 @@ export function registerDebugActions(): () => void { if (s) void report("Hot Restart failed", call(commands.debugHotRestart(s.id))); }, }, + { + id: "debug.openDevTools", + title: "Open Flutter DevTools in Browser", + category: "Debug", + icon: "external-link", + description: "Flutter: inspect the running app in the browser", + when: "debugHasVmService", + run: () => { + const s = activeSession(); + const uri = s && rootOf(s).vmServiceUri; + if (uri) void report("Couldn't open Flutter DevTools", openDevTools(uri)); + }, + }, + { + id: "debug.refreshDevTools", + title: "Refresh Flutter DevTools", + category: "Debug", + icon: "refresh", + description: "Flutter: load the DevTools page again", + when: "flutterDevTools", + run: (c) => { + const id = c.arg; + for (const w of DEVTOOLS_WINDOWS) if (!id || id === w.id) refreshDevTools(w.id); + }, + }, step("debug.stepOver", "Step Over", "over", "step-over"), step("debug.stepInto", "Step Into", "into", "step-into"), step("debug.stepOut", "Step Out", "out", "step-out"), diff --git a/src/features/debugger/flutter/devTools.ts b/src/features/debugger/flutter/devTools.ts new file mode 100644 index 000000000..04f1db882 --- /dev/null +++ b/src/features/debugger/flutter/devTools.ts @@ -0,0 +1,148 @@ +/** + * Flutter DevTools as tool windows, one per Android Studio window: the same pages, with the same + * parameters, of the project's DevTools server. + */ +import { create } from "zustand"; +import { setContext } from "@/platform/context"; +import { call, commands, onIdeEvent } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { lazyComponent } from "@/ui"; +import { registerToolWindow } from "@/workbench/contributions"; + +export interface DevToolsWindow { + id: string; + title: string; + icon: string; + /** Path of the page; empty for DevTools' own navigation. */ + page: string; + /** Screens left out of that navigation. */ + hide?: string; + /** Which app the page connects to: one page per app, the latest app, or none. */ + app: "each" | "latest" | "none"; +} + +// In Android Studio's stripe order. +export const DEVTOOLS_WINDOWS: readonly DevToolsWindow[] = [ + { + id: "flutter-deep-links", + title: "Flutter Deep Links", + icon: "toolwindow-flutter-deep-links", + page: "deep-links", + app: "none", + }, + { + id: "flutter-devtools", + title: "Flutter DevTools", + icon: "toolwindow-flutter-devtools", + page: "", + hide: "home,inspector,deep-links,extensions,debugger", + app: "latest", + }, + { + id: "flutter-devtools-extensions", + title: "Flutter DevTools Extensions", + icon: "toolwindow-flutter-extensions", + page: "", + hide: "all-except-extensions", + app: "latest", + }, + { + id: "flutter-inspector", + title: "Flutter Inspector", + icon: "toolwindow-flutter-inspector", + page: "inspector", + app: "each", + }, +]; + +export interface DevToolsLook { + theme: "light" | "dark"; + /** Hex digits, without `#`. */ + background?: string; +} + +/** The IDE's look, for a page about to load. Like Android Studio, a loaded page keeps its own. */ +export function currentDevToolsLook(root = document.documentElement): DevToolsLook { + const background = /^#([0-9a-f]{6})$/i.exec(getComputedStyle(root).getPropertyValue("--bg-editor").trim())?.[1]; + return { theme: root.dataset.theme === "light" ? "light" : "dark", ...(background ? { background } : {}) }; +} + +/** A DevTools page; with `embedded`, the form for a tool window. */ +export function devToolsUrl( + server: string, + window: Pick, + { uri, embedded }: { uri?: string; embedded?: DevToolsLook }, +): string { + const query = new URLSearchParams({ ide: "OpenIDEA" }); + if (embedded) { + query.set("embedMode", window.hide ? "many" : "one"); + if (window.hide) query.set("hide", window.hide); + query.set("theme", embedded.theme); + if (embedded.background) query.set("backgroundColor", embedded.background); + } + if (uri) query.set("uri", uri); + return `${server}/${window.page}?${query}`; +} + +/** Bumped by Refresh, per window: the page loads again, on a server started anew if it is gone. */ +export const useDevToolsRefresh = create>(() => ({})); + +export function refreshDevTools(id: string) { + useDevToolsRefresh.setState((s) => ({ [id]: (s[id] ?? 0) + 1 })); +} + +const view = (name: "FlutterDevToolsView" | "FlutterDevToolsTabs" | "FlutterDevToolsRefresh") => + lazyComponent(() => import("../ui/FlutterDevTools").then((m) => m[name])); + +/** A Flutter project's `pubspec.yaml`, by the rule the run and debug backends use. */ +export const isFlutterPubspec = (text: string) => text.includes("sdk: flutter"); + +/** Keeps the tool windows registered while the project's root `pubspec.yaml` depends on Flutter. */ +export function registerDevToolsWindows(): () => void { + let dispose: (() => void)[] | null = null; + const sync = (flutter: boolean) => { + setContext("flutterDevTools", flutter); + if (!flutter) { + dispose?.forEach((d) => d()); + dispose = null; + return; + } + dispose ??= DEVTOOLS_WINDOWS.map((w, i) => + registerToolWindow({ + id: w.id, + title: w.title, + icon: w.icon, + anchor: "right", + order: 40 + i, + component: view("FlutterDevToolsView"), + headerActions: view("FlutterDevToolsRefresh"), + ...(w.app === "each" ? { headerContent: view("FlutterDevToolsTabs") } : {}), + }), + ); + }; + let pubspec: string | null = null; + let check = 0; + const load = () => { + const root = useProject.getState().project?.root; + const seq = ++check; + pubspec = root ? `${root}/pubspec.yaml` : null; + if (!pubspec) return sync(false); + call(commands.fsReadText(pubspec)).then( + (text) => seq === check && sync(isFlutterPubspec(text)), + () => seq === check && sync(false), + ); + }; + load(); + const offProject = useProject.subscribe((s, prev) => { + if (s.project?.root !== prev.project?.root) load(); + }); + const offFs = onIdeEvent("fsChanged", (e) => { + if (pubspec && [...e.created, ...e.modified, ...e.removed].includes(pubspec)) load(); + }); + return () => { + offProject(); + offFs(); + check++; + sync(false); + }; +} diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index 1648f30fa..49ef13a78 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -18,6 +18,7 @@ import { useDebugRunSessions, } from "@/workbench/contributions"; import { registerDebugActions } from "./actions"; +import { registerDevToolsWindows } from "./flutter/devTools"; import { registerDebugTabActions } from "./tabActions"; import { loadBreakpoints } from "./breakpoints/store"; import { loadExceptionBreakpoints } from "./breakpoints/exceptions"; @@ -90,6 +91,7 @@ export function activate(): () => void { () => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }), registerDebugActions(), registerDebugTabActions(), + registerDevToolsWindows(), // Remote JVM Debug, Go Remote, …: Run/Debug Configurations › Add New Configuration. ...REMOTE_TYPES.map(registerRunConfigType), registerRunConfigType(jsBrowserType), diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 7702d076e..9014a529f 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -94,6 +94,10 @@ export interface DebugSession { caps: DebugCapabilities | null; /** State of the backend that reads a JVM's objects; absent until the backend reports one. */ jvmBackend?: JvmBackendState; + /** Flutter: the app's VM Service, which DevTools connects to. */ + vmServiceUri?: string; + /** Flutter: the device the app runs on. */ + flutterDevice?: string | null; /** A cancelled JDT build may have lost class-file deltas needed by this session. */ hotSwapNeedsRestart?: boolean; /** `flutter debug_adapter` reported the app as started: it can take a hot reload. */ @@ -410,6 +414,7 @@ export function publishContext() { "debugCanHotSwap", Object.values(useDebug.getState().sessions).some((x) => isLive(x) && !!x.caps?.hotCodeReplace), ); + setContext("debugHasVmService", !!s && isLive(s) && !!rootOf(s).vmServiceUri); // Refresh Memory View acts on the selected session only. setContext("debugHasJvmMemory", !!s && isLive(s) && sessionSupports("jvmMemory", s)); setContext("debugHasJsPage", !!s && isLive(s) && sessionSupports("jsPage", s)); @@ -1397,6 +1402,17 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) { case "jsNetwork": queueNetworkEvent(id, event.event); break; + case "flutterVmService": + patch(id, { vmServiceUri: event.uri, flutterDevice: event.device }); + break; + case "flutterNavigate": + // Focus stays in the inspector, where the next widget gets picked. + void maybeEditorService()?.openFile(event.path, { + selection: { line: event.line, col: event.column }, + preview: true, + focus: false, + }); + break; case "jsNetworkUnavailable": setRefused(id, "network", ""); break; diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index d7a2aa416..f180cf1d3 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -233,6 +233,7 @@ export function DebugToolWindow() { <> + {rootOf(active).vmServiceUri && } )} diff --git a/src/features/debugger/ui/FlutterDevTools.module.css b/src/features/debugger/ui/FlutterDevTools.module.css new file mode 100644 index 000000000..e368815af --- /dev/null +++ b/src/features/debugger/ui/FlutterDevTools.module.css @@ -0,0 +1,30 @@ +.pane { + position: relative; + width: 100%; + height: 100%; + min-height: 0; + background: var(--bg-editor, var(--bg-app)); +} + +.frame { + display: block; + width: 100%; + height: 100%; + border: 0; + background: var(--bg-editor, var(--bg-app)); +} + +.frame[hidden] { + display: none; +} + +.message { + display: flex; + align-items: center; + justify-content: center; + height: 100%; + padding: 16px; + color: var(--fg-muted); + font-family: var(--font-ui); + text-align: center; +} diff --git a/src/features/debugger/ui/FlutterDevTools.tsx b/src/features/debugger/ui/FlutterDevTools.tsx new file mode 100644 index 000000000..ede89ff92 --- /dev/null +++ b/src/features/debugger/ui/FlutterDevTools.tsx @@ -0,0 +1,159 @@ +/** The content of the Flutter DevTools tool windows: a page of the project's DevTools server. */ +import { useEffect, useMemo, useState } from "react"; +import { create } from "zustand"; +import { useTx } from "@/platform/i18n"; +import { call, commands, type DebugSessionId } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { isRemoteWindow } from "@/platform/remote"; +import { IconButton, Tabs, type TabItem } from "@/ui"; +import { useFlutterDevices } from "@/workbench/flutterDevices"; +import { + currentDevToolsLook, + DEVTOOLS_WINDOWS, + devToolsUrl, + useDevToolsRefresh, + type DevToolsWindow, +} from "../flutter/devTools"; +import { isLive, useDebug, type DebugSession } from "../state"; +import styles from "./FlutterDevTools.module.css"; + +const SANDBOX = "allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"; + +/** The Inspector tab chosen by hand; a new or remaining app is shown otherwise. */ +const useInspectorTab = create<{ session: DebugSessionId | null }>(() => ({ session: null })); + +const hasApp = (s: DebugSession) => !!s.vmServiceUri; + +function useRunningApps(): DebugSession[] { + const sessions = useDebug((s) => s.sessions); + return useMemo(() => Object.values(sessions).filter((s) => hasApp(s) && isLive(s)), [sessions]); +} + +function shownApp(apps: DebugSession[], chosen: DebugSessionId | null) { + return apps.find((s) => s.id === chosen) ?? apps.at(-1); +} + +type Server = { url: string } | { error: string }; + +/** The server's address; asks again on Refresh and when the project's trust changes. */ +function useDevToolsServer(refresh: number): Server | null { + const trusted = useProject((s) => s.project?.trusted); + const request = `${refresh}/${trusted}`; + const [answer, setAnswer] = useState<{ request: string; server: Server } | null>(null); + useEffect(() => { + let live = true; + call(commands.flutterDevtoolsUrl()).then( + (url) => live && setAnswer({ request, server: { url } }), + (e: unknown) => live && setAnswer({ request, server: { error: e instanceof Error ? e.message : String(e) } }), + ); + return () => { + live = false; + }; + }, [request]); + return answer?.request === request ? answer.server : null; +} + +function Frame({ + server, + window, + uri, + hidden, +}: { + server: string; + window: DevToolsWindow; + uri?: string; + hidden?: boolean; +}) { + const tx = useTx(); + const [look] = useState(() => currentDevToolsLook()); + return ( +