Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions host/simax/simax_actions.m
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import <objc/message.h>
#include <math.h>
#include <unistd.h>

// from simax.m
Expand Down Expand Up @@ -105,9 +106,113 @@ static id kv(id o, NSString* k) {
return d;
}

// ---------------------------------------------------------------------------------------------------------------------
// audio_state & audio_interrupt (public AVAudioSession + MPNowPlayingInfoCenter, zero extra framework link deps)
static NSDictionary* audio_state_info(void) {
NSMutableDictionary* d = [NSMutableDictionary dictionary];
d[@"ok"] = @YES;
d[@"pid"] = @(getpid());

Class avCls = NSClassFromString(@"AVAudioSession");
id session = avCls ? ((id (*)(id, SEL))objc_msgSend)((id)avCls, @selector(sharedInstance)) : nil;
if (session) {
NSMutableDictionary* av = [NSMutableDictionary dictionary];
NSString* cat = s_(kv(session, @"category"));
if (cat) av[@"category"] = cat;
NSString* mode = s_(kv(session, @"mode"));
if (mode) av[@"mode"] = mode;
if ([session respondsToSelector:@selector(sampleRate)]) {
double rate = ((double (*)(id, SEL))objc_msgSend)(session, @selector(sampleRate));
if (isfinite(rate) && rate >= 0.0) av[@"sample_rate"] = @(rate);
}
if ([session respondsToSelector:@selector(outputNumberOfChannels)]) {
NSInteger ch = ((NSInteger (*)(id, SEL))objc_msgSend)(session, @selector(outputNumberOfChannels));
if (ch >= 0) av[@"output_channels"] = @(ch);
}
id route = [session respondsToSelector:@selector(currentRoute)]
? ((id (*)(id, SEL))objc_msgSend)(session, @selector(currentRoute))
: nil;
id outs = route ? kv(route, @"outputs") : nil;
if ([outs isKindOfClass:[NSArray class]]) {
NSMutableArray* ports = [NSMutableArray array];
for (id port in (NSArray*)outs) {
NSMutableDictionary* pd = [NSMutableDictionary dictionary];
NSString* pt = s_(kv(port, @"portType"));
NSString* pn = s_(kv(port, @"portName"));
if (pt) pd[@"port_type"] = pt;
if (pn) pd[@"port_name"] = pn;
if (pd.count) [ports addObject:pd];
}
av[@"outputs"] = ports;
}
d[@"audio_session"] = av;
}

Class npCls = NSClassFromString(@"MPNowPlayingInfoCenter");
id center = npCls ? ((id (*)(id, SEL))objc_msgSend)((id)npCls, @selector(defaultCenter)) : nil;
if (center) {
NSMutableDictionary* np = [NSMutableDictionary dictionary];
if ([center respondsToSelector:@selector(playbackState)]) {
NSUInteger st = ((NSUInteger (*)(id, SEL))objc_msgSend)(center, @selector(playbackState));
np[@"playback_state"] = @(st);
}
id info = kv(center, @"nowPlayingInfo");
if ([info isKindOfClass:[NSDictionary class]]) {
NSDictionary* map = (NSDictionary*)info;
NSDictionary* strKeys = @{
@"title": @"title",
@"artist": @"artist",
@"albumTitle": @"album",
};
for (NSString* k in strKeys) {
id v = map[k];
if ([v isKindOfClass:[NSString class]]) np[strKeys[k]] = v;
}
NSDictionary* numKeys = @{
@"playbackDuration": @"duration_s",
@"MPNowPlayingInfoPropertyElapsedPlaybackTime": @"elapsed_s",
@"MPNowPlayingInfoPropertyPlaybackRate": @"playback_rate",
};
for (NSString* k in numKeys) {
id v = map[k];
if ([v isKindOfClass:[NSNumber class]]) {
double x = [(NSNumber*)v doubleValue];
if (isfinite(x)) np[numKeys[k]] = @(x);
}
}
}
d[@"now_playing"] = np;
}
return d;
}

static NSDictionary* audio_interrupt_deliver(NSDictionary* req) {
NSString* phase = [req[@"phase"] isKindOfClass:[NSString class]] ? req[@"phase"] : nil;
BOOL began = [phase isEqualToString:@"began"];
BOOL ended = [phase isEqualToString:@"ended"];
if (!began && !ended) {
return @{ @"ok": @NO, @"error": @"invalid_phase" };
}
Class avCls = NSClassFromString(@"AVAudioSession");
id session = avCls ? ((id (*)(id, SEL))objc_msgSend)((id)avCls, @selector(sharedInstance)) : nil;
if (!session) {
return @{ @"ok": @NO, @"error": @"av_audio_session_unavailable" };
}
BOOL shouldResume = ended && [req[@"should_resume"] isKindOfClass:[NSNumber class]] && [req[@"should_resume"] boolValue];
NSDictionary* userInfo = began
? @{ @"AVAudioSessionInterruptionTypeKey": @(1), @"AVAudioSessionInterruptionReasonKey": @(0) }
: @{ @"AVAudioSessionInterruptionTypeKey": @(0), @"AVAudioSessionInterruptionOptionKey": @(shouldResume ? 1 : 0) };
[[NSNotificationCenter defaultCenter] postNotificationName:@"AVAudioSessionInterruptionNotification"
object:session
userInfo:userInfo];
return @{ @"ok": @YES, @"pid": @(getpid()), @"phase": phase, @"should_resume": @(shouldResume) };
}

BOOL simax_controls_handle(NSString* op, NSDictionary* req, void (^reply)(NSDictionary*));

BOOL simax_actions_handle(NSString* op, NSDictionary* req, void (^reply)(NSDictionary*)) {
if ([op isEqualToString:@"focus"]) { reply(focus_info(req[@"expected_oid"])); return YES; }
if ([op isEqualToString:@"audio_state"]) { reply(audio_state_info()); return YES; }
if ([op isEqualToString:@"audio_interrupt"]) { reply(audio_interrupt_deliver(req)); return YES; }
return simax_controls_handle(op, req, reply); // control, setvalue (simax_controls.m)
}
128 changes: 128 additions & 0 deletions tools/launcher/core/src/axact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,53 @@ pub fn focus_of(inst: &Instance, pid: u32) -> Option<Value> {
(v["focused"].as_bool() == Some(true)).then(|| with_pid(v, pid))
}

fn resolve_audio_pid(inst: &Instance, bundle: Option<&str>) -> Result<u32> {
if let Some(b) = bundle {
let states = crate::appstate::app_state(inst, Some(b))?;
let pid = states.into_iter().flat_map(|s| s.processes).map(|p| p.pid).find(|&p| p > 0);
return pid.ok_or_else(|| anyhow::anyhow!("app {b} is not running"));
}
let sb = ax::last(inst).and_then(|s| s.elements.iter().find(|e| e.app == "com.apple.springboard").map(|e| e.pid));
let mut pids: Vec<u32> = ax::endpoints(inst).into_iter().filter(|e| e.fg).map(|e| ax::pid_of_sock(&e.sock)).filter(|&p| p > 0).collect();
pids.sort_by_key(|&p| Some(p) == sb);
pids.into_iter().next().ok_or_else(|| anyhow::anyhow!("no foreground app endpoint available (pass --bundle)"))
}

/// Inspect a running app's public AVAudioSession and MPNowPlayingInfoCenter state through libsimax.
pub fn audio_state_pid(inst: &Instance, pid: u32) -> Result<Value> {
let v = ax::ask_pid(inst, pid, &json!({"op": "audio_state"}), Duration::from_secs(3))?;
if v["ok"].as_bool() != Some(true) {
bail!("{}", v["error"].as_str().unwrap_or("audio_state failed"));
}
Ok(with_pid(v, pid))
}

pub fn audio_state(inst: &Instance, bundle: Option<&str>) -> Result<Value> {
let pid = resolve_audio_pid(inst, bundle)?;
audio_state_pid(inst, pid)
}

/// Deliver Apple's public AVAudioSessionInterruptionNotification ("began" | "ended") into one running app.
pub fn audio_interrupt_pid(inst: &Instance, pid: u32, phase: &str, should_resume: bool) -> Result<Value> {
if !matches!(phase, "began" | "ended") {
bail!("audio-interrupt phase must be 'began' or 'ended', not {phase:?}");
}
let req = json!({"op": "audio_interrupt", "phase": phase, "should_resume": phase == "ended" && should_resume});
let v = ax::ask_pid(inst, pid, &req, Duration::from_secs(3))?;
if v["ok"].as_bool() != Some(true) {
bail!("{}", v["error"].as_str().unwrap_or("audio_interrupt failed"));
}
Ok(with_pid(v, pid))
}

pub fn audio_interrupt(inst: &Instance, phase: &str, should_resume: bool, bundle: Option<&str>) -> Result<Value> {
if !matches!(phase, "began" | "ended") {
bail!("audio-interrupt phase must be 'began' or 'ended', not {phase:?}");
}
let pid = resolve_audio_pid(inst, bundle)?;
audio_interrupt_pid(inst, pid, phase, should_resume)
}

fn focus_for(inst: &Instance, e: &El) -> Option<Value> {
if engine_field(e) && e.focused && e.role == "textfield" {
return Some(json!({"kind":"engine", "expected_oid":e.oid, "pid":e.pid}));
Expand Down Expand Up @@ -1493,4 +1540,85 @@ mod tests {
assert_eq!(tap_focus_reason(&anyhow::anyhow!("could not confirm focus on textfield \"SecretLabel\" after 2.0 s; observed CMPTextInputView in pid 99 miss=not_unique_common")), "miss_not_unique_common");
assert_eq!(tap_focus_reason(&anyhow::anyhow!("could not confirm focus on textfield \"SecretLabel\" after 2.0 s; observed CMPTextInputView in pid 99")), "mismatch");
}

#[test]
fn audio_state_and_interrupt_wire_protocol() {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixListener;

let dir = std::env::temp_dir().join(format!("x86sim-axact-audio-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let inst = Instance {
id: "fixture-audio".into(),
dir: dir.clone(),
name: "test".into(),
model: String::new(),
model_id: String::new(),
runtime_dir: String::new(),
runtime_root: dir.clone(),
runtime_present: true,
unavailable: None,
ios: String::new(),
platform: "ios".into(),
build: String::new(),
screen: (390, 844),
scale: 3.0,
corner: 0.0,
ring: dir.join("ring"),
inner: None,
sock: dir.join("simhid.sock"),
state_dir: dir.clone(),
prefix: dir.clone(),
log_dir: dir.clone(),
is_default: false,
udid: "TEST-AUDIO-UDID".into(),
created: 0,
};

let sock = dir.join("x86sim-ax-TEST-AUDIO-UDID-777.sock");
let listener = UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
for _ in 0..3 {
let (mut s, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&s).read_line(&mut line).unwrap();
let req: Value = serde_json::from_str(&line).unwrap();
let reply = match req["op"].as_str().unwrap_or("") {
"audio_state" => json!({
"ok": true,
"pid": 777,
"audio_session": {"category": "AVAudioSessionCategoryPlayback", "sample_rate": 48000.0},
"now_playing": {"title": "Fixture Track", "playback_rate": 1.0}
}),
"audio_interrupt" => json!({
"ok": true,
"pid": 777,
"phase": req["phase"],
"should_resume": req["should_resume"]
}),
_ => json!({"ok": false, "error": "unknown_op"}),
};
writeln!(s, "{reply}").unwrap();
}
});

let st = audio_state_pid(&inst, 777).unwrap();
assert_eq!(st["pid"], 777);
assert_eq!(st["audio_session"]["category"], "AVAudioSessionCategoryPlayback");
assert_eq!(st["now_playing"]["title"], "Fixture Track");

let b = audio_interrupt_pid(&inst, 777, "began", true).unwrap();
assert_eq!(b["phase"], "began");
assert_eq!(b["should_resume"], false);

let e = audio_interrupt_pid(&inst, 777, "ended", true).unwrap();
assert_eq!(e["phase"], "ended");
assert_eq!(e["should_resume"], true);

assert!(audio_interrupt_pid(&inst, 777, "bogus", false).is_err());

server.join().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
}
17 changes: 17 additions & 0 deletions tools/launcher/core/src/bin/ax_parts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ fn run(mut args: Vec<String>) -> Result<()> {
let keys = flag("--keys");
let append = flag("--append");
let kill = flag("--kill");
let should_resume = flag("--should-resume");
let no_resume = flag("--no-resume");
let tri = |on: bool, off: bool| {
if on {
Some(true)
Expand Down Expand Up @@ -106,6 +108,7 @@ fn run(mut args: Vec<String>) -> Result<()> {
let into = opt("--into");
let submit_tap = opt("--submit-tap");
let hold = opt("--hold");
let bundle = opt("--bundle");
let (xlabel, xvalue, xcontains, xcount) = (opt("--label"), opt("--value"), opt("--contains"), opt("--count"));
// --marks [actionable]: the value is optional (after every opt(): the closure borrows args)
let marks = match args.iter().position(|a| a == "--marks") {
Expand Down Expand Up @@ -331,6 +334,20 @@ fn run(mut args: Vec<String>) -> Result<()> {
}
}
}
"audio-state" => {
let b = bundle.as_deref().or_else(|| args.first().map(|s| s.as_str()));
let v = x86sim_core::axact::audio_state(&inst, b)?;
println!("{}", serde_json::to_string_pretty(&v)?);
}
"audio-interrupt" => {
if should_resume && no_resume {
bail!("audio-interrupt: --should-resume and --no-resume are mutually exclusive");
}
let phase = args.first().map(|s| s.as_str()).ok_or_else(|| anyhow!("audio-interrupt began|ended [--should-resume|--no-resume] [--bundle BID]"))?;
let resume = if phase == "ended" { !no_resume } else { false };
let v = x86sim_core::axact::audio_interrupt(&inst, phase, resume, bundle.as_deref())?;
println!("{}", serde_json::to_string_pretty(&v)?);
}
"screenshot" | "shot" => {
let div = scale.and_then(|s| s.parse().ok()).unwrap_or(inst.scale.round().max(1.0) as u32);
let mut listing = String::new();
Expand Down
2 changes: 1 addition & 1 deletion tools/launcher/core/src/bin/x86sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const SETTINGS: &[&str] = &["ui", "status_bar", "statusbar", "pbcopy", "pbpaste"
// input through the SimulatorHID stand-in, in device pixels (x86sim ctl simtouch)
const SIMTOUCH: &[&str] = &["pinch", "pan2", "home", "lock", "crown", "openurl", "app", "dismiss", "raw", "button", "shake", "rotate", "orientation", "biometric", "gamepad", "memwarn", "pointer", "gesture", "appswitcher", "standby", "trackpad"];
// the agent commands, in points (ax)
const AX: &[&str] = &["snapshot", "snap", "find", "long-press", "scroll", "scroll-to", "wait-for", "press", "fill", "drag", "set-value", "expect", "app-state", "ps", "type", "keyboard", "gpu", "translator", "capture", "compare", "documents", "docs", "net", "record"];
const AX: &[&str] = &["snapshot", "snap", "find", "long-press", "scroll", "scroll-to", "wait-for", "press", "fill", "drag", "set-value", "expect", "app-state", "audio-state", "audio-interrupt", "ps", "type", "keyboard", "gpu", "translator", "capture", "compare", "documents", "docs", "net", "record"];

fn main() -> ExitCode {
// `x86sim tool NAME`: programs other programs run by name (xcrun runs thousands of times a build): before anything
Expand Down
Loading