feat(flutter): start emulators and simulators from the device chooser (#5783)

The Flutter device chooser lists emulators that aren't running (Open iOS Simulator, Open Android Emulator: <name>), from the project's flutter daemon (emulator.getEmulators, asked on connect and whenever the chooser opens; one a device already runs on is left out). Choosing one shows Starting <name>… and selects its device once it connects; a failed launch shows what the tool printed. AVDs are started by ide-android in their own process group so they outlive the daemon and the IDE; the iOS Simulator goes through emulator.launch.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-25 14:09:37 +08:00
1 джерело ad8958901b
коміт 1e4388490c
13 files changed
+428 -22

No files matched your search

Створено
+1
Переглянути файл
@@ -4189,6 +4189,7 @@ dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
+3
Переглянути файл
@@ -10,3 +10,6 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
+74 -2
Переглянути файл
@@ -12,11 +12,12 @@ mod process;
pub use model::*;
use ide_core::process::{own_group, prepare};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use std::time::Duration;
use std::time::{Duration, Instant};
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
const DEVICES: Duration = Duration::from_secs(20);
@@ -28,6 +29,8 @@ const TAIL_LINES: u32 = 200;
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
@@ -91,6 +94,51 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The SDK's `emulator` executable, which starts AVDs.
pub fn emulator_executable() -> Option<PathBuf> {
let name = exe("emulator");
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
}
/// Starts AVD `avd` in its own process group, so it
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
/// the emulator exits within its first seconds, with what it printed.
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
let emulator = emulator_executable().ok_or_else(|| {
IdeError::unavailable(
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
)
})?;
start_emulator(&emulator, avd)
}
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
let log = std::fs::File::create(&log_path)?;
let mut cmd = Command::new(emulator);
cmd.arg("-avd").arg(avd);
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
let mut child = prepare(own_group(&mut cmd)).spawn()?;
let deadline = Instant::now() + EMULATOR_STARTUP;
while Instant::now() < deadline {
if let Some(status) = child.try_wait()? {
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
return Err(IdeError::unavailable(if tail.is_empty() {
format!("the emulator exited ({status})")
} else {
tail
}));
}
std::thread::sleep(Duration::from_millis(100));
}
// Reaps it whenever it ends.
std::thread::spawn(move || child.wait());
Ok(())
}
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
@@ -206,6 +254,30 @@ mod tests {
}
}
#[cfg(unix)]
#[test]
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let script = |name: &str, body: &str| {
let path = dir.path().join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
let args = dir.path().join("args");
let running =
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
start_emulator(&running, "Pixel_9").unwrap();
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
}
#[test]
fn executable_is_absolute_when_found() {
if let Some(adb) = adb_executable() {
+18
Переглянути файл
@@ -264,6 +264,20 @@ pub struct FlutterDevice {
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option<String>,
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
#[serde(default)]
#[specta(optional)]
pub emulator_id: Option<String>,
}
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterEmulator {
pub id: String,
pub name: String,
/// `android` or `ios`.
pub platform_type: Option<String>,
}
/// See [`FlutterDeviceList`].
@@ -289,6 +303,10 @@ pub enum FlutterDaemonStatus {
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec<FlutterDevice>,
/// The emulators that no listed device runs on.
#[serde(default)]
#[specta(optional)]
pub emulators: Vec<FlutterEmulator>,
}
/// See [`IdeEvent::Direnv`].
+174 -13
Переглянути файл
@@ -3,6 +3,7 @@
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
//! `emulator.getEmulators` lists what can be started, then and whenever the chooser opens.
//!
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
@@ -13,21 +14,25 @@ mod devtools;
pub use devtools::DevToolsServer;
use ide_android::AndroidDevice;
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList};
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeMap, VecDeque};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
const ENABLE: u64 = 1;
const GET_DEVICES: u64 = 2;
const GET_EMULATORS: u64 = 3;
/// `emulator.launch` waits for `xcrun simctl` or similar; past this the daemon is stuck.
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
/// How long the daemon gets to exit on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(200);
/// Lines of unrecognised output kept to explain a failure.
@@ -39,6 +44,9 @@ enum Message {
Added(FlutterDevice),
Removed(String),
Devices(Vec<FlutterDevice>),
Emulators(Vec<FlutterEmulator>),
/// The answer to a request of ours other than the ones above.
Response(u64, Result<(), String>),
Other,
}
@@ -51,9 +59,15 @@ fn device(value: &Value) -> Option<FlutterDevice> {
category: text("category"),
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
unavailable: None,
emulator_id: text("emulatorId"),
})
}
fn emulator(value: &Value) -> Option<FlutterEmulator> {
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
Some(FlutterEmulator { id: text("id")?, name: text("name")?, platform_type: text("platformType") })
}
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
/// chatter, such as waiting for the startup lock).
fn parse_line(line: &str) -> Option<Vec<Message>> {
@@ -74,11 +88,23 @@ fn parse_message(message: &Value) -> Message {
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
}
Some(_) => Message::Other,
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
let result = message.get("result").and_then(Value::as_array);
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
None => {
let result = message.get("result").and_then(Value::as_array).into_iter().flatten();
match message.get("id").and_then(Value::as_u64) {
Some(ENABLE) | None => Message::Other,
Some(GET_DEVICES) => Message::Devices(result.filter_map(device).collect()),
// A failure (no Android SDK, no Xcode) lists none.
Some(GET_EMULATORS) => Message::Emulators(result.filter_map(emulator).collect()),
Some(id) => Message::Response(
id,
match message.get("error") {
None | Some(Value::Null) => Ok(()),
Some(Value::String(error)) => Err(error.clone()),
Some(error) => Err(error.to_string()),
},
),
}
}
None => Message::Other,
}
}
@@ -86,6 +112,12 @@ fn request(id: u64, method: &str) -> String {
format!("{}\n", json!([{ "id": id, "method": method }]))
}
/// The emulators no device runs on.
fn idle_emulators(emulators: &[FlutterEmulator], devices: &BTreeMap<String, FlutterDevice>) -> Vec<FlutterEmulator> {
let running = |e: &FlutterEmulator| devices.values().any(|d| d.emulator_id.as_ref() == Some(&e.id));
emulators.iter().filter(|e| !running(e)).cloned().collect()
}
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
/// are usable. A daemon Android device's id is its adb serial.
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
@@ -97,6 +129,7 @@ fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Ve
category: Some("mobile".into()),
emulator: d.serial.starts_with("emulator-"),
unavailable: Some(d.state.clone()),
emulator_id: None,
}));
let rank = |d: &FlutterDevice| match d.category.as_deref() {
Some("mobile") => 0,
@@ -121,15 +154,30 @@ struct State {
status: FlutterDaemonStatus,
devices: BTreeMap<String, FlutterDevice>,
adb: Vec<AndroidDevice>,
emulators: Vec<FlutterEmulator>,
/// Requests awaiting their answer; dropped with the daemon, which fails them.
pending: HashMap<u64, mpsc::Sender<Result<(), String>>>,
next_id: u64,
}
impl State {
fn list(&self) -> FlutterDeviceList {
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
FlutterDeviceList {
status: self.status.clone(),
devices: merged(&self.devices, &self.adb),
emulators: idle_emulators(&self.emulators, &self.devices),
}
}
/// Writes `requests` to the daemon; false without one.
fn send(&mut self, requests: &str) -> bool {
let Some(stdin) = self.running.as_mut().and_then(|r| r.stdin.as_mut()) else { return false };
stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush()).is_ok()
}
fn shut_down(&mut self) {
self.generation += 1;
self.pending.clear();
if let Some(Running { mut child, stdin }) = self.running.take() {
drop(stdin);
// Off the caller's thread: closing a window must not wait for the grace period.
@@ -181,12 +229,48 @@ impl FlutterDaemon {
state.list()
}
/// Reads adb again: a device awaiting authorization changes no daemon event.
/// Reads adb again (a device awaiting authorization changes no daemon event) and asks the
/// daemon for its emulators again (one may have been created since).
pub fn refresh(&self) {
let generation = self.0.state.lock().generation;
let mut state = self.0.state.lock();
if state.status == FlutterDaemonStatus::Ready {
state.send(&request(GET_EMULATORS, "emulator.getEmulators"));
}
let generation = state.generation;
drop(state);
refresh_adb(&self.0, generation);
}
/// Starts an emulator the list offers; it shows up as a device once booted. Blocks until the
/// launch is under way. An AVD is started by `ide-android` rather than the daemon, which
/// would make it a child of its process group and end it with the daemon.
pub fn launch_emulator(&self, id: &str) -> Result<(), String> {
let mut state = self.0.state.lock();
let android = state.emulators.iter().any(|e| e.id == id && e.platform_type.as_deref() == Some("android"));
if android {
drop(state);
return ide_android::launch_emulator(id).map_err(|e| e.message);
}
state.next_id = state.next_id.max(GET_EMULATORS) + 1;
let request_id = state.next_id;
let (tx, rx) = mpsc::channel();
state.pending.insert(request_id, tx);
let params = json!({ "emulatorId": id });
let line = format!("{}\n", json!([{ "id": request_id, "method": "emulator.launch", "params": params }]));
if !state.send(&line) {
state.pending.remove(&request_id);
return Err("the Flutter daemon is not running".into());
}
drop(state);
let answer = rx.recv_timeout(LAUNCH_TIMEOUT);
self.0.state.lock().pending.remove(&request_id);
match answer {
Ok(result) => result,
Err(mpsc::RecvTimeoutError::Timeout) => Err("the Flutter daemon did not answer".into()),
Err(mpsc::RecvTimeoutError::Disconnected) => Err("the Flutter daemon exited".into()),
}
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
@@ -194,6 +278,7 @@ impl FlutterDaemon {
state.status = FlutterDaemonStatus::Stopped;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
}
/// Ends the daemon before returning, for a process about to exit.
@@ -211,6 +296,7 @@ fn start(shared: &Arc<Shared>, state: &mut State) {
state.status = FlutterDaemonStatus::Starting;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
@@ -265,6 +351,7 @@ fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
return;
}
let running = state.running.take();
state.pending.clear();
state.status = status;
let list = state.list();
drop(state);
@@ -358,12 +445,25 @@ fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
match message {
Message::Other => return true,
Message::Connected => {
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
state.send(
&(request(ENABLE, "device.enable")
+ &request(GET_DEVICES, "device.getDevices")
+ &request(GET_EMULATORS, "emulator.getEmulators")),
);
return true;
}
Message::Response(id, result) => {
if let Some(tx) = state.pending.remove(&id) {
let _ = tx.send(result);
}
return true;
}
Message::Emulators(emulators) => {
if state.emulators == emulators {
return true;
}
state.emulators = emulators;
}
Message::Added(device) => {
state.devices.insert(device.id.clone(), device);
}
@@ -395,6 +495,7 @@ mod tests {
category: Some(category.into()),
emulator,
unavailable: None,
emulator_id: None,
}
}
@@ -433,6 +534,33 @@ mod tests {
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
let emulators = parse_line(
r#"[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]"#,
);
let Some([Message::Emulators(emulators)]) = emulators.as_deref() else { panic!("{emulators:?}") };
assert_eq!(
(emulators[0].id.as_str(), emulators[0].platform_type.as_deref()),
("apple_ios_simulator", Some("ios"))
);
assert_eq!(
parse_line(r#"[{"id":3,"error":"Unable to find Android SDK","trace":""}]"#),
Some(vec![Message::Emulators(vec![])])
);
assert_eq!(parse_line(r#"[{"id":7,"result":null}]"#), Some(vec![Message::Response(7, Ok(()))]));
assert_eq!(
parse_line(r#"[{"id":7,"error":"emulator 'x' not found","trace":"..."}]"#),
Some(vec![Message::Response(7, Err("emulator 'x' not found".into()))])
);
}
#[test]
fn offers_only_the_emulators_no_device_runs_on() {
let emulator = |id: &str| FlutterEmulator { id: id.into(), name: id.into(), platform_type: None };
let mut pixel = dev("emulator-5554", "Pixel", "mobile", true);
pixel.emulator_id = Some("Pixel_9".into());
let devices: BTreeMap<_, _> = [(pixel.id.clone(), pixel)].into_iter().collect();
let idle = idle_emulators(&[emulator("Pixel_9"), emulator("apple_ios_simulator")], &devices);
assert_eq!(idle, [emulator("apple_ios_simulator")]);
}
#[test]
@@ -498,8 +626,9 @@ mod tests {
echo $$ > pid
echo 'Waiting for another flutter command to release the startup lock...'
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; echo "$enable$get" > requests
read enable; read get; read emulators; echo "$enable$get$emulators" > requests
echo '[{"id":1,"result":null}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]'
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
@@ -518,6 +647,8 @@ cat > /dev/null
});
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
assert!(requests.contains("emulator.getEmulators"), "{requests}");
assert_eq!(daemon.devices().emulators[0].name, "iOS Simulator");
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
@@ -529,6 +660,36 @@ cat > /dev/null
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
}
#[test]
fn launches_an_emulator_through_the_daemon_and_reports_its_error() {
let dir = tempfile::tempdir().unwrap();
let script = r#"
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; read emulators
echo '[{"id":2,"result":[]}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","platformType":"ios"}]}]'
read launch; echo "$launch" > launch
echo '[{"id":4,"result":null}]'
read launch
echo '[{"id":5,"error":"Unable to run Simulator: xcrun not found","trace":""}]'
cat > /dev/null
"#;
let (daemon, _lists) = daemon(dir.path(), script);
daemon.devices();
wait_for("the emulators", || !daemon.devices().emulators.is_empty());
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Ok(()));
let launch = std::fs::read_to_string(dir.path().join("launch")).unwrap();
let launch: Value = serde_json::from_str(&launch).unwrap();
assert_eq!(launch[0]["method"], "emulator.launch");
assert_eq!(launch[0]["params"], json!({ "emulatorId": "apple_ios_simulator" }));
assert_eq!(
daemon.launch_emulator("apple_ios_simulator"),
Err("Unable to run Simulator: xcrun not found".into())
);
daemon.stop();
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Err("the Flutter daemon is not running".into()));
}
#[test]
fn the_daemon_does_not_outlive_the_ide() {
let dir = tempfile::tempdir().unwrap();
+12 -1
Переглянути файл
@@ -25,6 +25,16 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDev
Ok(host.project(window)?.flutter.restart())
}
/// Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`.
#[command(trust = trusted)]
pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> IdeResult<()> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.flutter.launch_emulator(&id))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
/// 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.
#[command(trust = trusted)]
@@ -36,4 +46,5 @@ pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String
.map_err(IdeError::unavailable)
}
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_devtools_url);
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
flutter_devtools_url);
+38 -2
Переглянути файл
@@ -17,7 +17,7 @@ const MACOS = device("macos", "macOS", "desktop");
const CHROME = device("chrome", "Chrome", "web");
const UNAUTHORIZED = device("R5C", "R5C", "mobile", "unauthorized");
async function stubFlutter(page: Page, status: unknown = { kind: "ready" }) {
async function stubFlutter(page: Page, status: unknown = { kind: "ready" }, emulators: unknown[] = []) {
await stubDesktop(page);
await page.evaluate(
async ({ list }) => {
@@ -38,13 +38,14 @@ async function stubFlutter(page: Page, status: unknown = { kind: "ready" }) {
h.run_apply_settings = (args) => args.configs;
h.flutter_devices = () => list;
h.flutter_devices_refresh = () => null;
h.flutter_emulator_launch = () => null;
h.run_start = () => ({ id: 3, configId: config.id, name: config.name, pid: 42, running: true, pty: false });
const runModule = "/src/features/run/store.ts";
const { loadConfigs, selectConfig } = await import(/* @vite-ignore */ runModule);
await loadConfigs();
selectConfig(config.id);
},
{ list: { status, devices: [MACOS, CHROME, UNAUTHORIZED] } },
{ list: { status, devices: [MACOS, CHROME, UNAUTHORIZED], emulators } },
);
}
@@ -79,3 +80,38 @@ test("says when the Flutter SDK is missing", async ({ workbench: page }) => {
await stubFlutter(page, { kind: "notInstalled" });
await expect(chooser(page)).toContainText("Flutter SDK not found");
});
test("starts an emulator and selects its device once it connects", async ({ workbench: page }) => {
const pixel = { id: "Pixel_9", name: "Pixel 9", platformType: "android" };
const simulator = { id: "apple_ios_simulator", name: "iOS Simulator", platformType: "ios" };
await stubFlutter(page, { kind: "ready" }, [pixel, simulator]);
await chooser(page).click();
await expect(page.getByRole("menuitem", { name: "Open iOS Simulator" })).toBeVisible();
await page.getByRole("menuitem", { name: "Open Android Emulator: Pixel 9" }).click();
await expect.poll(async () => ipcCalls(page, "flutter_emulator_launch")).toEqual([{ id: "Pixel_9" }]);
await expect(chooser(page)).toContainText("Starting Pixel 9…");
const booted = { ...device("emulator-5554", "sdk gphone64 arm64", "mobile"), emulator: true, emulatorId: "Pixel_9" };
await page.evaluate((list) => window.__ipc.emit({ type: "flutterDevices", list }), {
status: { kind: "ready" },
devices: [MACOS, booted],
emulators: [simulator],
});
await expect(chooser(page)).toContainText("sdk gphone64 arm64");
});
test("says why an emulator could not start", async ({ workbench: page }) => {
await stubFlutter(page, { kind: "ready" }, [
{ id: "apple_ios_simulator", name: "iOS Simulator", platformType: "ios" },
]);
await page.evaluate(() => {
window.__ipc.handlers.flutter_emulator_launch = () => {
throw { kind: "unavailable", message: "Unable to find Xcode" };
};
});
await chooser(page).click();
await page.getByRole("menuitem", { name: "Open iOS Simulator" }).click();
await expect(page.getByText("Could not start iOS Simulator")).toBeVisible();
await expect(page.getByText("Unable to find Xcode")).toBeVisible();
await expect(chooser(page)).toContainText("macOS");
});
+1
Переглянути файл
@@ -277,6 +277,7 @@ flutter_daemon_restart trusted project_host bin
flutter_devices trusted project_host bindings sync
flutter_devices_refresh trusted project_host bindings sync
flutter_devtools_url trusted project_host bindings async
flutter_emulator_launch 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
+14
Переглянути файл
@@ -695,6 +695,8 @@ export const commands = {
* exited is only started again by the next request.
*/
flutterDevtoolsUrl: () => typedError<string, IdeError>(__TAURI_INVOKE("flutter_devtools_url")),
/** Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`. */
flutterEmulatorLaunch: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("flutter_emulator_launch", { id })),
fsCompareDirectories: (left: string, right: string, mode: DirectoryCompareMode, request: RequestId, onProgress: Channel<DirectoryCompareProgress>) => typedError<DirectoryCompareEntry[], IdeError>(__TAURI_INVOKE("fs_compare_directories", { left, right, mode, request, onProgress })),
fsCopy: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy", { from, to })),
fsCopyMerge: (sourceRoot: string, destinationRoot: string, path: string, overwrite: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy_merge", { sourceRoot, destinationRoot, path, overwrite })),
@@ -7220,12 +7222,24 @@ export type FlutterDevice = {
emulator: boolean,
/** The adb state keeping it from being used (`unauthorized`, `offline`, …). */
unavailable: string | null,
/** The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`. */
emulatorId?: string | null,
};
/** The project's Flutter devices, best default first. */
export type FlutterDeviceList = {
status: FlutterDaemonStatus,
devices: FlutterDevice[],
/** The emulators that no listed device runs on. */
emulators?: FlutterEmulator[],
};
/** An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start. */
export type FlutterEmulator = {
id: string,
name: string,
/** `android` or `ios`. */
platformType: string | null,
};
export type FocusedEditor = {
+13 -2
Переглянути файл
@@ -5,7 +5,9 @@ import { useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import {
currentFlutterDevice,
flutterEmulatorLabel,
isFlutterConfig,
launchFlutterEmulator,
matchFlutterDevice,
pinnedFlutterDevice,
useFlutterDevices,
@@ -29,7 +31,7 @@ function Chooser({ root }: { root: string }) {
const selected = useRun((s) => s.configs.find((c) => c.id === s.selectedId));
useEffect(() => watchFlutterDevices(root), [root]);
const { list, chooserOpen } = state;
const { list, chooserOpen, launching } = state;
const status = list?.status;
const usable = usableFlutterDevices(list);
const current = currentFlutterDevice(state);
@@ -46,7 +48,9 @@ function Chooser({ root }: { root: string }) {
? tx("Flutter SDK not found")
: status?.kind === "failed"
? tx("Flutter devices unavailable")
: (current?.name ?? (status?.kind === "ready" ? tx("No devices") : tx("Finding devices…")));
: launching
? tx`Starting ${launching.name}…`
: (current?.name ?? (status?.kind === "ready" ? tx("No devices") : tx("Finding devices…")));
const items: MenuItem[] = [
...(pinned ? [{ kind: "header", label: tx`Pinned by “${selected?.name ?? ""}”` } as const] : []),
@@ -65,6 +69,13 @@ function Chooser({ root }: { root: string }) {
? [{ label: tx("Install Flutter or add it to PATH, then restart the daemon"), disabled: true }]
: []),
...(status?.kind === "failed" ? [{ label: status.message, verbatim: true, disabled: true }] : []),
...(list?.emulators?.length ? [{ kind: "separator" } as const] : []),
...(list?.emulators ?? []).map((e): MenuItem => ({
id: `emulator:${e.id}`,
label: launching?.id === e.id ? tx`Starting ${e.name}…` : flutterEmulatorLabel(e),
disabled: !!launching,
run: () => void launchFlutterEmulator(e),
})),
{ kind: "separator" },
{ kind: "action", action: "run.flutterRestartDaemon" },
];
+6
Переглянути файл
@@ -3434,6 +3434,12 @@
"No devices": "No devices",
"Finding devices…": "Finding devices…",
"No devices connected": "No devices connected",
"Open iOS Simulator": "Open iOS Simulator",
"Open Android Emulator: {name}": "Open Android Emulator: {name}",
"Starting {name}…": "Starting {name}…",
"Could not start {name}": "Could not start {name}",
"{name} did not connect": "{name} did not connect",
"It may still be starting: it appears in the device list once Flutter sees it.": "It may still be starting: it appears in the device list once Flutter sees it.",
"Install Flutter or add it to PATH, then restart the daemon": "Install Flutter or add it to PATH, then restart the daemon",
"Flutter Device": "Flutter Device",
"Flutter device: {name}": "Flutter device: {name}",
+6
Переглянути файл
@@ -9773,6 +9773,12 @@
"Flutter devices unavailable": "Flutter 设备不可用",
"Finding devices…": "正在查找设备…",
"No devices connected": "没有已连接的设备",
"Open iOS Simulator": "打开 iOS 模拟器",
"Open Android Emulator: {name}": "打开 Android 模拟器:{name}",
"Starting {name}…": "正在启动 {name}…",
"Could not start {name}": "无法启动 {name}",
"{name} did not connect": "{name} 没有连接上",
"It may still be starting: it appears in the device list once Flutter sees it.": "它可能仍在启动:Flutter 识别到后会出现在设备列表中。",
"Install Flutter or add it to PATH, then restart the daemon": "请安装 Flutter 或将其加入 PATH,然后重启守护进程",
"Flutter Device": "Flutter 设备",
"Flutter device: {name}": "Flutter 设备:{name}",
+68 -2
Переглянути файл
@@ -5,10 +5,20 @@
import { create } from "zustand";
import { setContext } from "@/platform/context";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent, type FlutterDevice, type FlutterDeviceList, type RunConfig } from "@/platform/ipc";
import {
call,
commands,
onIdeEvent,
type FlutterDevice,
type FlutterDeviceList,
type FlutterEmulator,
type RunConfig,
} from "@/platform/ipc";
import { notifications } from "./contributions";
const SELECTED_KEY = "openidea.flutter.device:";
/** A cold boot of a large AVD can take minutes; past this the launch is taken to have failed. */
const BOOT_TIMEOUT_MS = 180_000;
interface FlutterDevicesState {
list: FlutterDeviceList | null;
@@ -16,6 +26,8 @@ interface FlutterDevicesState {
preferred: string | null;
root: string | null;
chooserOpen: boolean;
/** The emulator started from the chooser, until its device connects. */
launching: FlutterEmulator | null;
}
export const useFlutterDevices = create<FlutterDevicesState>(() => ({
@@ -23,6 +35,7 @@ export const useFlutterDevices = create<FlutterDevicesState>(() => ({
preferred: null,
root: null,
chooserOpen: false,
launching: null,
}));
function storedDevice(root: string): string | null {
@@ -131,7 +144,7 @@ export function watchFlutterDevices(root: string): () => void {
offDevices();
offTrust();
setContext("flutterProject", false);
useFlutterDevices.setState({ list: null, root: null, chooserOpen: false });
useFlutterDevices.setState({ list: null, root: null, chooserOpen: false, launching: null });
};
}
@@ -148,3 +161,56 @@ export function selectFlutterDevice(id: string) {
export async function restartFlutterDaemon() {
useFlutterDevices.setState({ list: await call(commands.flutterDaemonRestart()) });
}
/** The chooser's label for starting `e`, as the Flutter plugin words it. */
export function flutterEmulatorLabel(e: FlutterEmulator): string {
return e.platformType === "ios" ? tx("Open iOS Simulator") : tx`Open Android Emulator: ${e.name}`;
}
/** Starts `e` and selects its device once it connects. */
export async function launchFlutterEmulator(e: FlutterEmulator) {
useFlutterDevices.setState({ launching: e });
const booted = (list: FlutterDeviceList | null) => usableFlutterDevices(list).find((d) => d.emulatorId === e.id);
let stop = () => {};
const done = new Promise<FlutterDevice | null>((resolve) => {
const timer = setTimeout(() => resolve(null), BOOT_TIMEOUT_MS);
const off = useFlutterDevices.subscribe((s) => {
const device = booted(s.list);
if (device) resolve(device);
else if (s.launching !== e) resolve(null);
});
stop = () => {
clearTimeout(timer);
off();
resolve(null);
};
});
try {
await call(commands.flutterEmulatorLaunch(e.id));
} catch (err) {
stop();
if (useFlutterDevices.getState().launching === e) useFlutterDevices.setState({ launching: null });
notifications().notify({
group: "run",
level: "error",
key: "flutter.emulator",
title: tx`Could not start ${e.name}`,
body: err instanceof Error ? err.message : String(err),
});
return;
}
const device = await done;
stop();
// Replaced by another launch, or the project closed.
if (useFlutterDevices.getState().launching !== e) return;
useFlutterDevices.setState({ launching: null });
if (device) selectFlutterDevice(device.id);
else
notifications().notify({
group: "run",
level: "warning",
key: "flutter.emulator",
title: tx`${e.name} did not connect`,
body: tx("It may still be starting: it appears in the device list once Flutter sees it."),
});
}