дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
On macOS the Logcat device picker also lists booted iOS Simulators (simctl list devices booted). Selecting one follows simctl spawn <udid> log stream --style ndjson --level debug, mapping each log event to a Logcat line (timestamp, pid, thread, a process (subsystem:category) tag, message type to level), so simulator logs get the same level filter, colors, filter language, pause/follow and history as Android. The stream ends normally when the simulator shuts down, the list is empty off macOS or without Xcode, and a missing adb is only reported when there are no simulators either. Closes #6801 Co-authored-by: wildcatDownstairs <[email protected]>
200 рядки
7.8 KiB
Rust
200 рядки
7.8 KiB
Rust
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
|
|
//!
|
|
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
|
|
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
|
|
//! window shows both with one level filter and one filter language.
|
|
|
|
use crate::model::{LogcatLevel, LogcatLine};
|
|
use crate::process;
|
|
use ide_core::{CancellationToken, IdeError, IdeResult};
|
|
use serde::{Deserialize, Serialize};
|
|
use specta::Type;
|
|
use std::process::Command;
|
|
use std::time::Duration;
|
|
|
|
const LIST: Duration = Duration::from_secs(20);
|
|
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
|
const BATCH_MAX: usize = 300;
|
|
|
|
/// A booted simulator, as `simctl list devices booted -j` reports it.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct BootedSimulator {
|
|
pub udid: String,
|
|
pub name: String,
|
|
/// e.g. `iOS 27.0`.
|
|
pub runtime: String,
|
|
}
|
|
|
|
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
|
|
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
|
|
if !cfg!(target_os = "macos") {
|
|
return Ok(Vec::new());
|
|
}
|
|
let mut cmd = Command::new("xcrun");
|
|
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
|
|
match process::run(cmd, LIST, None) {
|
|
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
|
|
// No Xcode (only the Command Line Tools, or none): there are no simulators.
|
|
_ => Ok(Vec::new()),
|
|
}
|
|
}
|
|
|
|
/// Parses `simctl list devices -j`, keeping booted devices.
|
|
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
|
|
#[derive(Deserialize)]
|
|
struct List {
|
|
devices: std::collections::BTreeMap<String, Vec<Device>>,
|
|
}
|
|
#[derive(Deserialize)]
|
|
struct Device {
|
|
udid: String,
|
|
name: String,
|
|
state: String,
|
|
}
|
|
let Ok(list) = serde_json::from_str::<List>(json) else {
|
|
return Vec::new();
|
|
};
|
|
let mut out = Vec::new();
|
|
for (runtime, devices) in list.devices {
|
|
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
|
|
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
|
|
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
|
|
for d in devices.into_iter().filter(|d| d.state == "Booted") {
|
|
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Message type of the unified log → the logcat level the window filters and colors by.
|
|
fn level(message_type: &str) -> LogcatLevel {
|
|
match message_type {
|
|
"Debug" => LogcatLevel::Debug,
|
|
"Info" | "Default" => LogcatLevel::Info,
|
|
"Error" => LogcatLevel::Error,
|
|
"Fault" => LogcatLevel::Fatal,
|
|
_ => LogcatLevel::Verbose,
|
|
}
|
|
}
|
|
|
|
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
|
|
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
|
|
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct Entry {
|
|
event_type: String,
|
|
#[serde(default)]
|
|
message_type: String,
|
|
#[serde(default)]
|
|
timestamp: String,
|
|
#[serde(default)]
|
|
process_image_path: String,
|
|
#[serde(rename = "processID", default)]
|
|
pid: i64,
|
|
#[serde(rename = "threadID", default)]
|
|
tid: i64,
|
|
#[serde(default)]
|
|
subsystem: String,
|
|
#[serde(default)]
|
|
category: String,
|
|
#[serde(default)]
|
|
event_message: String,
|
|
}
|
|
let e: Entry = serde_json::from_str(line).ok()?;
|
|
if e.event_type != "logEvent" {
|
|
return None;
|
|
}
|
|
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
|
|
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
|
|
(true, _) => process.to_owned(),
|
|
(false, true) => format!("{process} ({})", e.subsystem),
|
|
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
|
|
};
|
|
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
|
|
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
|
|
Some(LogcatLine {
|
|
time,
|
|
pid: e.pid as i32,
|
|
tid: e.tid as i32,
|
|
level: level(&e.message_type),
|
|
tag,
|
|
message: e.event_message,
|
|
})
|
|
}
|
|
|
|
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
|
|
pub fn simulator_log(
|
|
udid: &str,
|
|
cancel: &CancellationToken,
|
|
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
|
|
) -> IdeResult<()> {
|
|
let mut cmd = Command::new("xcrun");
|
|
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
|
|
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
|
|
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
|
|
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
|
|
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
|
|
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
|
|
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
|
|
Err(e) => Err(e),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
|
|
|
|
#[test]
|
|
fn parses_an_entry_and_ignores_unknown_fields() {
|
|
let line = parse_ndjson(ENTRY).unwrap();
|
|
assert_eq!(line.time, "11-29 14:39:31.696");
|
|
assert_eq!(line.pid, 64339);
|
|
assert_eq!(line.tid, 90176044);
|
|
assert_eq!(line.level, LogcatLevel::Error);
|
|
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
|
|
assert_eq!(line.message, "endpoint has nothing to cleanup");
|
|
}
|
|
|
|
#[test]
|
|
fn keeps_a_multi_line_message_whole() {
|
|
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
|
|
let line = parse_ndjson(entry).unwrap();
|
|
assert_eq!(line.message, "first\nsecond");
|
|
assert_eq!(line.tag, "MyApp");
|
|
assert_eq!(line.level, LogcatLevel::Info);
|
|
}
|
|
|
|
#[test]
|
|
fn skips_what_is_not_a_log_message() {
|
|
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
|
|
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
|
|
assert!(parse_ndjson("").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn maps_message_types_to_levels() {
|
|
assert_eq!(level("Debug"), LogcatLevel::Debug);
|
|
assert_eq!(level("Info"), LogcatLevel::Info);
|
|
assert_eq!(level("Default"), LogcatLevel::Info);
|
|
assert_eq!(level("Error"), LogcatLevel::Error);
|
|
assert_eq!(level("Fault"), LogcatLevel::Fatal);
|
|
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
|
|
}
|
|
|
|
#[test]
|
|
fn reads_booted_simulators() {
|
|
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
|
|
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
|
|
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
|
|
assert_eq!(
|
|
parse_simulators(json),
|
|
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
|
|
);
|
|
assert!(parse_simulators("not json").is_empty());
|
|
}
|
|
}
|