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
52 changes: 52 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 <dlfcn.h>
#include <math.h>
#include <unistd.h>

Expand Down Expand Up @@ -183,9 +184,59 @@ static id kv(id o, NSString* k) {
}
d[@"now_playing"] = np;
}

Class rcCls = NSClassFromString(@"MPRemoteCommandCenter");
id rcCenter = rcCls ? ((id (*)(id, SEL))objc_msgSend)((id)rcCls, @selector(sharedCommandCenter)) : nil;
if (rcCenter) {
NSMutableDictionary* rc = [NSMutableDictionary dictionary];
NSDictionary* cmds = @{
@"playCommand": @"play",
@"pauseCommand": @"pause",
@"togglePlayPauseCommand": @"toggle_play_pause",
@"nextTrackCommand": @"next",
@"previousTrackCommand": @"previous",
@"changePlaybackPositionCommand": @"seek",
};
for (NSString* prop in cmds) {
id cmdObj = kv(rcCenter, prop);
if (cmdObj && [cmdObj respondsToSelector:@selector(isEnabled)]) {
BOOL en = ((BOOL (*)(id, SEL))objc_msgSend)(cmdObj, @selector(isEnabled));
rc[cmds[prop]] = @(en);
}
}
d[@"remote_commands"] = rc;
}
return d;
}

static NSDictionary* remote_command_deliver(NSDictionary* req) {
NSString* cmd = [req[@"command"] isKindOfClass:[NSString class]] ? req[@"command"] : nil;
uint32_t mrCmd = 0;
if ([cmd isEqualToString:@"play"]) mrCmd = 0;
else if ([cmd isEqualToString:@"pause"]) mrCmd = 1;
else if ([cmd isEqualToString:@"toggle_play_pause"]) mrCmd = 2;
else if ([cmd isEqualToString:@"next"]) mrCmd = 4;
else if ([cmd isEqualToString:@"previous"]) mrCmd = 5;
else return @{ @"ok": @NO, @"error": @"invalid_command" };

typedef Boolean (*MRSendFn)(uint32_t, CFDictionaryRef);
static MRSendFn sendFn = NULL;
static BOOL triedLoad = NO;
if (!triedLoad) {
triedLoad = YES;
void* h = dlopen("/System/Library/PrivateFrameworks/MediaRemote.framework/MediaRemote", RTLD_LAZY);
if (h) sendFn = (MRSendFn)dlsym(h, "MRMediaRemoteSendCommand");
}
if (!sendFn) {
return @{ @"ok": @NO, @"error": @"media_remote_unavailable" };
}
Boolean sent = sendFn(mrCmd, NULL);
if (!sent) {
return @{ @"ok": @NO, @"error": @"media_remote_send_failed", @"command": cmd };
}
return @{ @"ok": @YES, @"pid": @(getpid()), @"command": cmd, @"via": @"MediaRemote" };
}

static NSDictionary* audio_interrupt_deliver(NSDictionary* req) {
NSString* phase = [req[@"phase"] isKindOfClass:[NSString class]] ? req[@"phase"] : nil;
BOOL began = [phase isEqualToString:@"began"];
Expand Down Expand Up @@ -214,5 +265,6 @@ BOOL simax_actions_handle(NSString* op, NSDictionary* req, void (^reply)(NSDicti
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; }
if ([op isEqualToString:@"remote_command"]) { reply(remote_command_deliver(req)); return YES; }
return simax_controls_handle(op, req, reply); // control, setvalue (simax_controls.m)
}
48 changes: 46 additions & 2 deletions tools/launcher/core/src/axact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,34 @@ pub fn audio_interrupt(inst: &Instance, phase: &str, should_resume: bool, bundle
audio_interrupt_pid(inst, pid, phase, should_resume)
}

fn normalize_remote_command(cmd: &str) -> Result<&'static str> {
match cmd {
"play" => Ok("play"),
"pause" => Ok("pause"),
"toggle-play-pause" | "toggle_play_pause" => Ok("toggle_play_pause"),
"next" => Ok("next"),
"previous" | "prev" => Ok("previous"),
_ => bail!("remote-command must be play|pause|toggle-play-pause|next|previous, not {cmd:?}"),
}
}

/// Deliver a MediaRemote command ("play" | "pause" | "toggle_play_pause" | "next" | "previous") via libsimax.
pub fn remote_command_pid(inst: &Instance, pid: u32, command: &str) -> Result<Value> {
let norm = normalize_remote_command(command)?;
let req = json!({"op": "remote_command", "command": norm});
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("remote_command failed"));
}
Ok(with_pid(v, pid))
}

pub fn remote_command(inst: &Instance, command: &str, bundle: Option<&str>) -> Result<Value> {
let norm = normalize_remote_command(command)?;
let pid = resolve_audio_pid(inst, bundle)?;
remote_command_pid(inst, pid, norm)
}

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 @@ -1579,7 +1607,7 @@ mod tests {
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 {
for _ in 0..5 {
let (mut s, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&s).read_line(&mut line).unwrap();
Expand All @@ -1589,14 +1617,21 @@ mod tests {
"ok": true,
"pid": 777,
"audio_session": {"category": "AVAudioSessionCategoryPlayback", "sample_rate": 48000.0},
"now_playing": {"title": "Fixture Track", "playback_rate": 1.0}
"now_playing": {"title": "Fixture Track", "playback_rate": 1.0},
"remote_commands": {"play": true, "pause": true, "toggle_play_pause": true}
}),
"audio_interrupt" => json!({
"ok": true,
"pid": 777,
"phase": req["phase"],
"should_resume": req["should_resume"]
}),
"remote_command" => json!({
"ok": true,
"pid": 777,
"command": req["command"],
"via": "MediaRemote"
}),
_ => json!({"ok": false, "error": "unknown_op"}),
};
writeln!(s, "{reply}").unwrap();
Expand All @@ -1607,6 +1642,7 @@ mod tests {
assert_eq!(st["pid"], 777);
assert_eq!(st["audio_session"]["category"], "AVAudioSessionCategoryPlayback");
assert_eq!(st["now_playing"]["title"], "Fixture Track");
assert_eq!(st["remote_commands"]["play"], true);

let b = audio_interrupt_pid(&inst, 777, "began", true).unwrap();
assert_eq!(b["phase"], "began");
Expand All @@ -1616,7 +1652,15 @@ mod tests {
assert_eq!(e["phase"], "ended");
assert_eq!(e["should_resume"], true);

let rc1 = remote_command_pid(&inst, 777, "toggle-play-pause").unwrap();
assert_eq!(rc1["command"], "toggle_play_pause");
assert_eq!(rc1["via"], "MediaRemote");

let rc2 = remote_command_pid(&inst, 777, "pause").unwrap();
assert_eq!(rc2["command"], "pause");

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

server.join().unwrap();
let _ = std::fs::remove_dir_all(&dir);
Expand Down
5 changes: 5 additions & 0 deletions tools/launcher/core/src/bin/ax_parts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,11 @@ fn run(mut args: Vec<String>) -> Result<()> {
let v = x86sim_core::axact::audio_interrupt(&inst, phase, resume, bundle.as_deref())?;
println!("{}", serde_json::to_string_pretty(&v)?);
}
"remote-command" => {
let cmd = args.first().map(|s| s.as_str()).ok_or_else(|| anyhow!("remote-command play|pause|toggle-play-pause|next|previous [--bundle BID]"))?;
let v = x86sim_core::axact::remote_command(&inst, cmd, 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", "audio-state", "audio-interrupt", "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", "remote-command", "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