diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 86782deb..9be9c456 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -1,11 +1,14 @@ name: macOS -# Builds the macOS app bundle for each architecture, signs it ad hoc with the -# release's hardened runtime and entitlements, packs it into a disk image, and -# checks the app in the image launches and lists devices. Pull requests that -# change the packaging run it; nightly runs it against main. release.yml calls -# it with `sign`, which signs and notarizes the app as the Developer ID, then -# the disk image holding it, checks them again, and ships the images. +# Builds the macOS app bundle for each architecture, with CEF for browser +# sources, signs it ad hoc with the release's hardened runtime and +# entitlements, runs the browser-source tests against it on Apple silicon, +# packs it into a disk image, and checks the app in the image launches and +# lists devices. Pull requests that change the packaging run it; nightly runs +# it against main. +# release.yml calls it with `sign`, which signs and notarizes the app as the +# Developer ID, then the disk image holding it, checks them again, and ships +# the images. permissions: contents: read @@ -55,6 +58,13 @@ jobs: persist-credentials: false submodules: true + # cef-dll-sys builds CEF's C++ wrapper with CMake, which the image has, + # and Ninja, which it may lack. + - name: Install Ninja + env: + HOMEBREW_NO_AUTO_UPDATE: "1" + run: command -v ninja || brew install ninja + # The image's rustup installs the toolchain rust-toolchain.toml names, and # Xcode's own linker and SDK keep the binary free of Nix store paths. - name: Build @@ -63,6 +73,23 @@ jobs: - name: Sign ad hoc run: packaging/macos/sign.sh "kixel.live Studio.app" - + # Browser sources against the signed bundle, the only place CEF runs + # from on macOS: drawn on the GPU, played, clicked, typed into, copied, + # kept logged in, and crashing alone. One at a time, since a test finds + # its helper among the processes this one started. The harness builds in + # the dev profile: only the bundle it drives needs release, and a second + # fat-LTO build of the studio would add an hour. Apple silicon only: the + # Intel runners' paravirtual GPU passes for Metal to the studio, but + # Chromium's GPU process cannot start ANGLE on it and the browser exits. + - name: Browser sources + if: matrix.arch == 'arm64' + env: + MOQ_STUDIO_APP: ${{ github.workspace }}/kixel.live Studio.app + MACOSX_DEPLOYMENT_TARGET: "13.0" + run: >- + cargo test --locked -p moq-studio --features cef --test browser -- + --include-ignored --test-threads=1 + # dmg.sh's builder needs a newer Python than macOS ships. - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/Cargo.lock b/Cargo.lock index 7afb2f29..9c8be92d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4747,12 +4747,18 @@ dependencies = [ "humantime-serde", "image", "kio", + "mach2", "moq-audio", "moq-json", "moq-mux", "moq-net", "moq-video", "notosans", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-io-surface", "parley", "percent-encoding", "postcard", diff --git a/README.md b/README.md index e8f74353..93d852a0 100644 --- a/README.md +++ b/README.md @@ -73,9 +73,12 @@ cargo run --release -p moq-studio --features capture,openh264 encoder. - `release` is what the packages build: `capture`, `openh264`, and the hardware codecs. The Flatpak adds `pipewire`. -- `cef` adds browser sources, on Linux only for now. The build takes CEF from - `CEF_PATH`, which the dev shell sets, or else downloads it, and the binary - loads `libcef.so` from beside itself or from that `CEF_PATH`. +- `cef` adds browser sources, on Linux and macOS. The build takes CEF from + `CEF_PATH`, which the dev shell sets on Linux, or else downloads it. On + Linux the binary loads `libcef.so` from beside itself or from that + `CEF_PATH`. On macOS browser sources run only from the app bundle, which + holds CEF's framework and its helper apps: build it with + `packaging/macos/bundle.sh`, which the macOS packages ship with `cef`. - On Linux, display and window sources capture X11 and XWayland by id. With `pipewire`, a display or window can also be picked in the desktop's screen-sharing picker, the only way to share a Wayland screen; see @@ -914,17 +917,19 @@ A browser source renders a web page, such as an overlay, alert box, or chat widget, at the canvas frame rate (CEF caps it at 60) over a transparent background, and its sound joins the audio scenes that hold it. Every page shares one browser profile, kept in `$XDG_DATA_HOME/moq-studio/browser` -(`~/.local/share/moq-studio/browser` by default) rather than beside the scene -file, so cookies and logins, such as an alert service's, survive a reload and -a restart of the studio. They are not encrypted with the desktop's keyring, -so a locked keyring never holds a page back, and anything that can read your -home directory can read them. One studio at a time can use the profile: a +(`~/.local/share/moq-studio/browser` by default) on Linux and in +`~/Library/Application Support/moq-studio/browser` on macOS, rather than +beside the scene file, so cookies and logins, such as an alert service's, +survive a reload and a restart of the studio. They are not encrypted with the +desktop's keyring or keychain, so a locked keyring never holds a page back and +no keychain prompt interrupts one, and anything that can read your home +directory can read them. One studio at a time can use the profile: a second one's browser sources fail saying so. Each page renders in a process of its own, so a page that crashes fails only its own source, with the reason, while the stream carries on. A crash of the browser itself fails every browser source. -Either shows at once, since the browser's processes dump no core. On Linux, -pages run without Chromium's sandbox, as in OBS, so a page that exploits a -browser bug can do anything you can: add only pages you trust. +Either shows at once, since the browser's processes dump no core. Pages run +without Chromium's sandbox, as in OBS, so a page that exploits a browser bug +can do anything you can: add only pages you trust. The browser requests only what its pages load, never asking Google for updates, the time, or autofill suggestions on its own, so pages are not spellchecked, which would need a dictionary from Google. Nor does it run @@ -933,9 +938,9 @@ browser extensions, even ones your distribution installs for every Chromium. lists, such as a ``'s list, arrive the same way apart from the page, and the studio //! draws them over it. A page's sound joins the program bus at the bus's rate. //! -//! Linux only for now, and only with the `cef` feature: elsewhere a browser -//! source reports that it is unsupported. +//! On macOS the helper is still the studio's executable, but only inside its +//! app bundle, which holds CEF's framework and the helper apps CEF's +//! subprocesses run from (the `moq-browser-helper` binary), and a page's +//! shared texture is an IOSurface sent ahead of its message as a Mach port. +//! +//! Linux and macOS only for now, and only with the `cef` feature: elsewhere a +//! browser source reports that it is unsupported. use std::path::PathBuf; use std::process::ExitCode; @@ -25,23 +30,25 @@ use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] mod layers; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] mod outbox; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] mod protocol; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] mod run; -#[cfg(all(target_os = "linux", feature = "cef"))] +#[cfg(all(any(target_os = "linux", target_os = "macos"), feature = "cef"))] mod host; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] mod import; +#[cfg(target_os = "macos")] +mod mach; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] pub(crate) use protocol::Open; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] pub(crate) use run::run; /// The longest side of a page, in pixels: room for a 4K canvas. @@ -49,8 +56,8 @@ pub(crate) const MAX_SIDE: u32 = 4096; /// The argument that starts the studio's executable as a helper. #[cfg_attr( - not(target_os = "linux"), - expect(dead_code, reason = "browser sources are Linux-only") + not(any(target_os = "linux", target_os = "macos")), + expect(dead_code, reason = "browser sources run on Linux and macOS") )] const ARG: &str = "--moq-browser-helper"; @@ -60,7 +67,7 @@ const ARG: &str = "--moq-browser-helper"; /// A binary that offers browser sources calls this before anything else in /// `main`, and exits with the code it returns. pub fn child() -> Option { - #[cfg(all(target_os = "linux", feature = "cef"))] + #[cfg(all(any(target_os = "linux", target_os = "macos"), feature = "cef"))] { if std::env::args_os().nth(1).is_some_and(|arg| arg == ARG) { return Some(host::run()); @@ -77,8 +84,8 @@ pub fn child() -> Option { /// copied to. Clones share one helper. #[derive(Clone)] #[cfg_attr( - not(target_os = "linux"), - expect(dead_code, reason = "browser sources are Linux-only") + not(any(target_os = "linux", target_os = "macos")), + expect(dead_code, reason = "browser sources run on Linux and macOS") )] pub struct Helper { program: PathBuf, @@ -86,14 +93,17 @@ pub struct Helper { device: wgpu::Device, queue: wgpu::Queue, /// Where pages paint. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] raster: protocol::Raster, /// Why a page that paints into memory does. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] fallback: Arc, /// The helper, once a page has started it. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] running: Arc>>>, + /// Where every helper sends its pages' IOSurfaces, on the GPU path. + #[cfg(target_os = "macos")] + surfaces: Option>, } impl Helper { @@ -112,10 +122,17 @@ impl Helper { device: &wgpu::Device, queue: &wgpu::Queue, ) -> Self { - #[cfg(not(target_os = "linux"))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] let _ = adapter; #[cfg(target_os = "linux")] - let (raster, fallback) = match gpu(adapter, device) { + let gpu = gpu(adapter, device); + #[cfg(target_os = "macos")] + let (gpu, surfaces) = match gpu(adapter) { + Ok((raster, receiver)) => (Ok(raster), Some(Arc::new(receiver))), + Err(why) => (Err(why), None), + }; + #[cfg(any(target_os = "linux", target_os = "macos"))] + let (raster, fallback) = match gpu { Ok(raster) => (raster, "its GPU process cannot share textures".into()), Err(why) => (protocol::Raster::Cpu, why.into()), }; @@ -124,32 +141,35 @@ impl Helper { profile: profile.into(), device: device.clone(), queue: queue.clone(), - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] raster, - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] fallback, - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] running: Default::default(), + #[cfg(target_os = "macos")] + surfaces, } } /// Take what a page last copied or cut, once, for the desktop's - /// clipboard, which CEF reaches itself only through an X display. - #[cfg(target_os = "linux")] + /// clipboard, which CEF reaches itself only on macOS and through an X + /// display. + #[cfg(any(target_os = "linux", target_os = "macos"))] pub fn copied(&self) -> Option { let running = self.running.lock().unwrap(); running.as_ref()?.copied() } /// Take what a page last copied or cut: nothing, without browser sources. - #[cfg(not(target_os = "linux"))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] pub fn copied(&self) -> Option { None } /// Whether a page's Copy and Cut come back through [`Helper::copied`], - /// rather than reaching the X clipboard through CEF itself. - #[cfg(target_os = "linux")] + /// rather than reaching the desktop's clipboard through CEF itself. + #[cfg(any(target_os = "linux", target_os = "macos"))] pub fn relays_copies(&self) -> bool { !self.raster.native_copy() } @@ -158,7 +178,7 @@ impl Helper { /// profile is saved and free for the next studio. The next page to start /// starts a new helper. pub fn stop(&self) { - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] { // Held throughout, so no page starts another helper on the profile // until this one has exited. @@ -219,6 +239,31 @@ fn gpu(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Result Result<(protocol::Raster, mach::Receiver), String> { + if !cfg!(feature = "cef") { + return Err("this build cannot share textures".into()); + } + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu { + return Err(format!("the studio's GPU, {}, renders in software", info.name)); + } + // An IOSurface becomes a texture only through Metal. + if info.backend != wgpu::Backend::Metal { + return Err(format!( + "the studio's GPU, {}, draws with {}, not Metal, so it cannot import shared textures", + info.name, info.backend + )); + } + let receiver = mach::Receiver::new()?; + let raster = protocol::Raster::Gpu { + service: receiver.name().to_string(), + }; + Ok((raster, receiver)) +} + /// Check that the Wayland display in `$WAYLAND_DISPLAY` advertises an output, /// which Chromium's Wayland platform waits for before CEF's `initialize` /// returns. @@ -333,24 +378,24 @@ pub struct Page { #[derive(Default)] struct PageState { /// The queue to the helper's socket, while the page is open. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] commands: Option, /// The page's number in the helper. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] id: protocol::Id, /// Whether input is being dropped because the backlog is full. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] backlogged: bool, /// The canvas's frame rate, which the page paints at. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] framerate: u32, /// Whether the helper has yet to hear `framerate`. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] retime: bool, paint: Option, } -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "macos"))] impl PageState { /// Queue `input`, which past the backlog drops, a release aside. fn send(&mut self, input: Input) { @@ -399,7 +444,7 @@ impl Page { /// Paint at `rate`, the canvas's frame rate, from now on, without waiting on /// the helper. One that is behind hears it once it catches up. pub(crate) fn set_framerate(&self, rate: u32) { - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] { let mut state = self.state.lock().unwrap(); if state.framerate != rate { @@ -408,7 +453,7 @@ impl Page { state.flush(); } } - #[cfg(not(target_os = "linux"))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] let _ = rate; } @@ -418,9 +463,9 @@ impl Page { /// more, as a hung window's would be, except that a release is delivered /// once the helper catches up. pub fn send(&self, input: Input) { - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] self.state.lock().unwrap().send(input); - #[cfg(not(target_os = "linux"))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] let _ = input; } } @@ -494,8 +539,8 @@ pub struct Modifiers { /// The texture a page's pixels are uploaded to: premultiplied BGRA, as CEF /// paints, and a copy source for drawing a popup over the page. #[cfg_attr( - not(target_os = "linux"), - expect(dead_code, reason = "browser sources are Linux-only") + not(any(target_os = "linux", target_os = "macos")), + expect(dead_code, reason = "browser sources run on Linux and macOS") )] fn upload( device: &wgpu::Device, @@ -541,7 +586,7 @@ fn upload( Ok(texture) } -#[cfg(all(test, target_os = "linux"))] +#[cfg(all(test, any(target_os = "linux", target_os = "macos")))] mod tests { use super::*; diff --git a/rs/moq-scene/src/browser/protocol.rs b/rs/moq-scene/src/browser/protocol.rs index 619c0e69..aa0932ee 100644 --- a/rs/moq-scene/src/browser/protocol.rs +++ b/rs/moq-scene/src/browser/protocol.rs @@ -1,9 +1,11 @@ //! What a browser source says to its helper process, and back. //! //! One Unix stream socket carries both directions, each message a -//! little-endian `u32` length and that many bytes of postcard. A shared -//! texture's DMA-BUF descriptors ride with the first byte of its message as -//! `SCM_RIGHTS`, so they arrive with the message that describes them. +//! little-endian `u32` length and that many bytes of postcard. On Linux, a +//! shared texture's DMA-BUF descriptors ride with the first byte of its +//! message as `SCM_RIGHTS`, so they arrive with the message that describes +//! them. On macOS its IOSurface goes ahead of the message as a Mach port +//! (`super::mach`), which no socket carries. use std::io::{self, IoSlice, IoSliceMut, Read, Write}; use std::mem::MaybeUninit; @@ -27,6 +29,20 @@ pub(crate) const MAX_PLANES: usize = 4; /// the other allocate. pub(crate) const MAX_MESSAGE: usize = (super::MAX_SIDE * super::MAX_SIDE * 4) as usize + 1024; +/// How every message is sent: never raising `SIGPIPE` on a closed socket. +/// macOS has no such flag, and Rust ignores the signal there anyway. +#[cfg(target_os = "linux")] +const SEND: SendFlags = SendFlags::NOSIGNAL; +#[cfg(not(target_os = "linux"))] +const SEND: SendFlags = SendFlags::empty(); + +/// How every message is received: descriptors closed on exec, so no helper +/// inherits another's. macOS has no such flag, and sends none. +#[cfg(target_os = "linux")] +const RECV: RecvFlags = RecvFlags::CMSG_CLOEXEC; +#[cfg(not(target_os = "linux"))] +const RECV: RecvFlags = RecvFlags::empty(); + /// A page's number, unique among those one helper opens. pub(crate) type Id = u64; @@ -63,12 +79,19 @@ pub(crate) struct Start { /// Where a helper's pages paint. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub(crate) enum Raster { - /// On the GPU, into shared textures the studio imports: on the DRM render - /// node named, the studio's GPU, or else on the one CEF picks. CEF's GPU - /// process needs `display` to allocate them. + /// On the GPU, into shared textures the studio imports. Gpu { + /// The DRM render node to paint on, the studio's GPU, or else the one + /// CEF picks. + #[cfg(target_os = "linux")] render_node: Option, + /// What CEF's GPU process allocates the textures through. + #[cfg(target_os = "linux")] display: Display, + /// The studio's bootstrap service, which takes each texture's + /// IOSurface. + #[cfg(target_os = "macos")] + service: String, }, /// In software, into memory the studio uploads, with no display opened. /// Startup never waits on a GPU process CEF cannot start, and WebGL runs @@ -78,20 +101,25 @@ pub(crate) enum Raster { } impl Raster { - /// Whether CEF's own copy reaches the desktop's clipboard: only through an - /// X display. + /// Whether CEF's own copy reaches the desktop's clipboard: on macOS + /// always, the pasteboard being a system service, and on Linux only + /// through an X display. pub(crate) fn native_copy(&self) -> bool { - matches!( + #[cfg(target_os = "linux")] + return matches!( self, Raster::Gpu { display: Display::X11, .. } - ) + ); + #[cfg(not(target_os = "linux"))] + true } } /// The display server the GPU path connects to, the one the studio runs on. +#[cfg(target_os = "linux")] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub(crate) enum Display { /// `$WAYLAND_DISPLAY`, preferred: CEF paints there on the studio's GPU. @@ -167,14 +195,16 @@ pub(crate) struct Area { } /// A shared texture's layout, CEF's `cef_accelerated_paint_info_t` minus the -/// descriptors. +/// handles: DMA-BUF descriptors on Linux, an IOSurface on macOS. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub(crate) struct Texture { pub width: u32, pub height: u32, pub format: Format, /// The DRM format modifier: how the planes are tiled. + #[cfg(target_os = "linux")] pub modifier: u64, + #[cfg(target_os = "linux")] pub planes: Vec, } @@ -186,6 +216,7 @@ pub(crate) enum Format { } /// One plane of a shared texture. +#[cfg(target_os = "linux")] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct Plane { pub stride: u32, @@ -231,7 +262,7 @@ impl Channel { } // The descriptors go with the first byte sent; a short send leaves the // rest for a plain write. - let sent = rustix::net::sendmsg(&self.socket, &[IoSlice::new(&bytes)], &mut control, SendFlags::NOSIGNAL)?; + let sent = rustix::net::sendmsg(&self.socket, &[IoSlice::new(&bytes)], &mut control, SEND)?; (&self.socket).write_all(&bytes[sent..]) } @@ -248,7 +279,7 @@ impl Channel { &self.socket, &mut [IoSliceMut::new(&mut length[read..])], &mut control, - RecvFlags::CMSG_CLOEXEC, + RECV, )?; for message in control.drain() { if let RecvAncillaryMessage::ScmRights(received) = message { @@ -298,6 +329,7 @@ mod tests { /// Descriptors arrive with the message they were sent with, not the one /// before or after, however the stream splits. #[test] + #[cfg(target_os = "linux")] fn descriptors_ride_with_their_message() { let (studio, helper) = pair(); let texture = Texture { diff --git a/rs/moq-scene/src/browser/run.rs b/rs/moq-scene/src/browser/run.rs index f5138d3f..faffcd55 100644 --- a/rs/moq-scene/src/browser/run.rs +++ b/rs/moq-scene/src/browser/run.rs @@ -16,7 +16,7 @@ use moq_audio::bus::Live as Sound; use super::layers::{Gpu, Layers}; use super::outbox::Commands; -use super::protocol::{Area, Channel, Command, Event, Id, Layer, Open, Raster, Start}; +use super::protocol::{Area, Channel, Command, Event, Id, Layer, Open, Start}; use super::{ARG, Helper, Page, Paint}; use crate::Error; use crate::source::{Mailbox, Picture, Status}; @@ -221,9 +221,24 @@ impl Instance { // once every other owner is gone. let gpu = Gpu::new(&helper.device, &helper.queue); let (reading, routes) = (commands.clone(), routes.clone()); + #[cfg(target_os = "macos")] + let surfaces = Surfaces { + receiver: helper.surfaces.clone(), + pid: process.child.id(), + }; let spawned = std::thread::Builder::new() .name("browser-events".into()) - .spawn(move || read(&gpu, process, &events, &reading, &routes)); + .spawn(move || { + read( + &gpu, + process, + &events, + &reading, + &routes, + #[cfg(target_os = "macos")] + &surfaces, + ) + }); // The writer ends with it; the helper, dropped with the closure, is // killed. spawned.map_err(|err| { @@ -391,7 +406,13 @@ fn spawn(helper: &Helper) -> std::io::Result<(Process, Channel)> { // compressed layout with a second, auxiliary plane, and Chromium's frame // capturer drops multi-plane buffers: the page never paints. Without // compression, the texture is a single plane. - if let Raster::Gpu { .. } = helper.raster { + // Chromium's allocator needs macOS's nano malloc zone off, which Chrome's + // and CEF's own app bundles ask of Launch Services. The helper is started + // directly, so it asks here, for itself and every process CEF starts. + #[cfg(target_os = "macos")] + command.env("MallocNanoZone", "0"); + #[cfg(target_os = "linux")] + if let super::protocol::Raster::Gpu { .. } = helper.raster { let mut debug = std::env::var_os("INTEL_DEBUG").unwrap_or_default(); if !debug.is_empty() { debug.push(","); @@ -403,10 +424,45 @@ fn spawn(helper: &Helper) -> std::io::Result<(Process, Channel)> { Ok((Process { child, exit: None }, Channel::new(ours))) } +/// Where a helper's shared textures come from on macOS: the IOSurfaces it +/// sends the studio's service, which only it, process `pid`, may hand over. +#[cfg(target_os = "macos")] +struct Surfaces { + /// The service, on the GPU path. + receiver: Option>, + pid: u32, +} + +#[cfg(target_os = "macos")] +impl Surfaces { + /// The surface sent ahead of the texture message just read. + fn take(&self) -> Result, String> { + let receiver = self + .receiver + .as_ref() + .ok_or("the browser process sent a shared texture, though its pages paint into memory")?; + receiver.surface(self.pid) + } +} + /// Deliver the helper's events until it exits or breaks the protocol, then /// stop it and every page still open, saying why. -fn read(gpu: &Gpu, mut process: Process, events: &Channel, commands: &Commands, routes: &Mutex) { - let reason = match deliver(gpu, events, commands, routes) { +fn read( + gpu: &Gpu, + mut process: Process, + events: &Channel, + commands: &Commands, + routes: &Mutex, + #[cfg(target_os = "macos")] surfaces: &Surfaces, +) { + let reason = match deliver( + gpu, + events, + commands, + routes, + #[cfg(target_os = "macos")] + surfaces, + ) { // Gone, or exiting: wait for it, so the next helper finds the profile // free. Ok(()) => match process.exited() { @@ -429,7 +485,13 @@ fn read(gpu: &Gpu, mut process: Process, events: &Channel, commands: &Commands, /// Route the helper's events to their pages until it closes the socket, or /// fail with why it cannot go on. -fn deliver(gpu: &Gpu, events: &Channel, commands: &Commands, routes: &Mutex) -> Result<(), String> { +fn deliver( + gpu: &Gpu, + events: &Channel, + commands: &Commands, + routes: &Mutex, + #[cfg(target_os = "macos")] surfaces: &Surfaces, +) -> Result<(), String> { use std::io::ErrorKind::*; let Gpu { device, queue, .. } = gpu; @@ -443,12 +505,18 @@ fn deliver(gpu: &Gpu, events: &Channel, commands: &Commands, routes: &Mutex return Err(format!("the browser process's socket: {err}")), }; let (id, layer, texture, paint) = match event { - Event::Texture(id, layer, texture) => ( - id, - layer, - super::import::texture(device, queue, &texture, fds), - Paint::Gpu, - ), + Event::Texture(id, layer, texture) => { + #[cfg(target_os = "linux")] + let imported = super::import::texture(device, queue, &texture, fds); + #[cfg(target_os = "macos")] + let imported = { + drop(fds); + surfaces + .take() + .and_then(|surface| super::import::texture(device, queue, &texture, &surface)) + }; + (id, layer, imported, Paint::Gpu) + } Event::Pixels { page, layer, diff --git a/rs/moq-scene/src/source.rs b/rs/moq-scene/src/source.rs index 61e531fe..573bc354 100644 --- a/rs/moq-scene/src/source.rs +++ b/rs/moq-scene/src/source.rs @@ -45,8 +45,8 @@ pub(crate) enum Picture { /// A texture on the compositor's device with premultiplied alpha, such as /// a web page. #[cfg_attr( - not(target_os = "linux"), - expect(dead_code, reason = "browser sources are Linux-only") + not(any(target_os = "linux", target_os = "macos")), + expect(dead_code, reason = "browser sources run on Linux and macOS") )] Texture(wgpu::Texture), /// A LUT source's table, which is not drawn but looked up. @@ -850,8 +850,8 @@ pub struct Driver { strip: Option, status: kio::Producer, #[cfg_attr( - not(target_os = "linux"), - expect(dead_code, reason = "browser sources are Linux-only") + not(any(target_os = "linux", target_os = "macos")), + expect(dead_code, reason = "browser sources run on Linux and macOS") )] page: Option, /// The source's own track, when it publishes one. @@ -1235,7 +1235,7 @@ impl Driver { /// Render the page at `url` until its helper stops, or fail at once if the /// studio offers no helper. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] async fn browser(&self, url: &str, width: u32, height: u32) -> Result<(), Error> { let Some(helper) = &self.context.browser else { return Err(Error::Unsupported( @@ -1259,9 +1259,11 @@ impl Driver { crate::browser::run(helper, open, page, &self.picture, Some(sound), &self.status).await } - #[cfg(not(target_os = "linux"))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] async fn browser(&self, _: &str, _: u32, _: u32) -> Result<(), Error> { - Err(Error::Unsupported("browser sources run on Linux only for now".into())) + Err(Error::Unsupported( + "browser sources run on Linux and macOS only for now".into(), + )) } /// Follow the broadcast at `path` for as long as the feed lives, playing diff --git a/rs/moq-studio/Cargo.toml b/rs/moq-studio/Cargo.toml index 026d8cd1..d9c86f02 100644 --- a/rs/moq-studio/Cargo.toml +++ b/rs/moq-studio/Cargo.toml @@ -35,9 +35,11 @@ pipewire = ["capture", "moq-scene/pipewire", "dep:pipewire"] # system library at startup. `pipewire` is not one; the Flatpak, which bundles # libpipewire, adds it. release = ["capture", "nvidia", "openh264", "vaapi"] -# Browser sources, rendered by CEF in a helper process (Linux). Off by default: -# the build downloads the CEF runtime (or takes it from `CEF_PATH`) and copies -# it beside the binary, where the binary looks for it when it starts. +# Browser sources, rendered by CEF in a helper process (Linux and macOS). Off +# by default: the build downloads the CEF runtime (or takes it from +# `CEF_PATH`). On Linux it copies it beside the binary, where the binary looks +# for it when it starts; on macOS packaging/macos/bundle.sh puts it in the app +# bundle, the only place browser sources run from there. cef = ["moq-scene/cef"] [dependencies] diff --git a/rs/moq-studio/src/engine.rs b/rs/moq-studio/src/engine.rs index 6282b1b0..dc79be90 100644 --- a/rs/moq-studio/src/engine.rs +++ b/rs/moq-studio/src/engine.rs @@ -3371,10 +3371,11 @@ fn browser(gpu: &Gpu) -> anyhow::Result> { } /// Where browser sources keep their cookies and logins, whichever scene file -/// is open: `moq-studio/browser` in the user's data directory, since browser -/// sources run on Linux only for now. +/// is open: `browser` in the studio's own data directory, the user's +/// (`$XDG_DATA_HOME/moq-studio` on Linux, `Application Support` on macOS). fn browser_profile() -> anyhow::Result { - Ok(xdg("XDG_DATA_HOME", ".local/share")?.join("moq-studio/browser")) + let dir = crate::data_dir().context("no home directory to keep the browser profile in")?; + Ok(dir.join("browser")) } /// Where the system picker's grants for the scene file at `scene` are kept: diff --git a/rs/moq-studio/src/main.rs b/rs/moq-studio/src/main.rs index ded1df68..a512074c 100644 --- a/rs/moq-studio/src/main.rs +++ b/rs/moq-studio/src/main.rs @@ -165,8 +165,9 @@ fn data_dir() -> Option { } fn main() -> anyhow::Result { - // A browser source's helper, and CEF's subprocesses, are this executable - // started again. + // A browser source's helper is this executable started again, as are + // CEF's subprocesses on Linux; on macOS they run from the bundle's helper + // apps. if let Some(code) = moq_scene::browser::child() { return Ok(code); } diff --git a/rs/moq-studio/tests/browser.rs b/rs/moq-studio/tests/browser.rs index 7677e39d..051b2516 100644 --- a/rs/moq-studio/tests/browser.rs +++ b/rs/moq-studio/tests/browser.rs @@ -1,10 +1,11 @@ //! Browser sources against the real helper: this package's binary, built with //! `cef`, rendering `data:` pages, or pages served on loopback, with nothing -//! fetched from the network. +//! fetched from the network. On macOS the binary is the one in the app bundle +//! `MOQ_STUDIO_APP` names, since CEF runs only from there. -#![cfg(all(target_os = "linux", feature = "cef"))] +#![cfg(all(any(target_os = "linux", target_os = "macos"), feature = "cef"))] -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -18,6 +19,22 @@ const TIMEOUT: Duration = Duration::from_secs(20); const BLUE: [u8; 4] = [0, 0, 255, 255]; +/// The studio's executable, which becomes the helper. +#[cfg(target_os = "linux")] +fn program() -> PathBuf { + PathBuf::from(env!("CARGO_BIN_EXE_moq-studio")) +} + +/// The studio's executable in the app bundle `MOQ_STUDIO_APP` names, as +/// `packaging/macos/bundle.sh` lays it out with CEF. +#[cfg(target_os = "macos")] +fn program() -> PathBuf { + let app = std::env::var_os("MOQ_STUDIO_APP").expect("MOQ_STUDIO_APP names the app bundle to run CEF from"); + std::fs::canonicalize(app) + .expect("the app bundle") + .join("Contents/MacOS/moq-studio") +} + /// A studio of one scene, "Main", drawing `sources` back to front over the /// whole of a small canvas. Dropping it stops its helper. struct Studio { @@ -45,7 +62,7 @@ impl Studio { /// A studio whose pages keep their cookies in `profile`. async fn on(profile: &Path, sources: &[(&str, Source)]) -> Self { - Self::start(Path::new(env!("CARGO_BIN_EXE_moq-studio")), profile, sources).await + Self::start(&program(), profile, sources).await } /// A studio whose helper is `program`, with its pages' cookies in @@ -231,7 +248,7 @@ async fn local(f: F) -> F::Output { /// A page draws over what is under it with its own alpha, and its sound /// joins the bus. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_page_draws_and_plays() { local(async { // Half-transparent red over blue, and a tone. @@ -245,7 +262,15 @@ async fn a_page_draws_and_plays() { studio.until_center([128, 0, 127, 255], &[]).await; let feed = studio.sources.get("page").unwrap(); assert_eq!(feed.status(), Status::Live); - assert!(feed.page().unwrap().paint().is_some(), "the paint path shows"); + let paint = feed.page().unwrap().paint(); + assert!(paint.is_some(), "the paint path shows"); + // Every Mac draws with Metal, which imports the page's IOSurface. + #[cfg(target_os = "macos")] + assert_eq!( + paint, + Some(moq_scene::browser::Paint::Gpu), + "the page is copied on the GPU" + ); let strip = feed.strip().unwrap().clone(); let deadline = Instant::now().saturating_add(TIMEOUT); @@ -262,7 +287,7 @@ async fn a_page_draws_and_plays() { /// shared texture from a GPU whose tiling the studio's cannot read scrambles /// its rows. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_page_keeps_its_layout() { local(async { const RED: [u8; 4] = [255, 0, 0, 255]; @@ -290,7 +315,7 @@ async fn a_page_keeps_its_layout() { /// A page gets WebGL and WebGL2 contexts, and what it draws with them shows. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_webgl_page_draws() { local(async { // Red unless both contexts exist, and then green from WebGL2. @@ -309,7 +334,7 @@ async fn a_webgl_page_draws() { /// A click reaches the page where the preview put it, and a popup it asks for /// opens nothing. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_click_reaches_the_page() { local(async { let html = "`'s list, which CEF paints apart from the page, draws over the /// page, and a click on it picks an option like a click on the page would. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_dropdown_draws_and_takes_clicks() { local(async { // A select across the top, whose list of lime options covers the @@ -374,10 +399,100 @@ async fn a_dropdown_draws_and_takes_clicks() { .await; } +/// A page's own handler takes Undo's shortcut before the browser's command, +/// as an editor with its own history needs. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] +async fn a_page_takes_its_own_shortcuts() { + local(async { + let html = ""; + let mut studio = Studio::new(&[("page", page(html))]).await; + studio.until_center([255, 0, 0, 255], &[]).await; + + let page = studio.sources.get("page").unwrap().page().unwrap().clone(); + page.send(Input::Focus(true)); + for down in [true, false] { + page.send(Input::Button { + x: 160, + y: 120, + button: Button::Left, + down, + clicks: 1, + modifiers: Modifiers::default(), + }); + } + // Undo: Command-Z on a Mac. + let modifiers = Modifiers { + ctrl: cfg!(not(target_os = "macos")), + meta: cfg!(target_os = "macos"), + ..Default::default() + }; + for down in [true, false] { + page.send(Input::Key { + code: b'Z'.into(), + down, + modifiers, + }); + } + studio.until_center(BLUE, &[]).await; + }) + .await; +} + +/// A shifted key reaches the page's keydown as the character it types, as a +/// `?` shortcut needs. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] +async fn a_shifted_key_is_its_character() { + local(async { + // Green once `?` is pressed, then blue once `!` is. + let html = ""; + let mut studio = Studio::new(&[("page", page(html))]).await; + studio.until_center([255, 0, 0, 255], &[]).await; + + let page = studio.sources.get("page").unwrap().page().unwrap().clone(); + page.send(Input::Focus(true)); + for down in [true, false] { + page.send(Input::Button { + x: 160, + y: 120, + button: Button::Left, + down, + clicks: 1, + modifiers: Modifiers::default(), + }); + } + let shift = Modifiers { + shift: true, + ..Default::default() + }; + let key = |code: u8| { + for down in [true, false] { + page.send(Input::Key { + code: code.into(), + down, + modifiers: shift, + }); + } + }; + // The US layout's `/` key, then `1`. + key(0xbf); + studio.until_center(GREEN, &[]).await; + key(b'1'); + studio.until_center(BLUE, &[]).await; + }) + .await; +} + /// Copy and Cut put the page's selection on the clipboard, and Cut deletes it /// from the page. A password field's text is never taken. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn copy_and_cut_reach_the_clipboard() { local(async { // A text box over the whole page, then a password field and a second @@ -410,8 +525,10 @@ async fn copy_and_cut_reach_the_clipboard() { }); } }; + // Select All: Command-A on a Mac. let ctrl = Modifiers { - ctrl: true, + ctrl: cfg!(not(target_os = "macos")), + meta: cfg!(target_os = "macos"), ..Default::default() }; let mut clipboard = Clipboard::new(studio.helper.clone()); @@ -453,19 +570,20 @@ async fn copy_and_cut_reach_the_clipboard() { .await; } -/// Where a page's copies land: the X clipboard, where CEF copies itself, or -/// else the studio's, through the helper. +/// Where a page's copies land: the desktop's clipboard, where CEF copies +/// itself on macOS and through an X display, or else the studio's, through +/// the helper. enum Clipboard { Relay(Helper), /// With the text it held when last read. - X11(Option), + Desktop(Option), } impl Clipboard { fn new(helper: Helper) -> Self { match helper.relays_copies() { true => Self::Relay(helper), - false => Self::X11(x11_clipboard()), + false => Self::Desktop(desktop_clipboard()), } } @@ -473,8 +591,8 @@ impl Clipboard { fn take(&mut self) -> Option { match self { Self::Relay(helper) => helper.copied(), - Self::X11(held) => { - let text = x11_clipboard(); + Self::Desktop(held) => { + let text = desktop_clipboard(); if text == *held { return None; } @@ -497,9 +615,18 @@ impl Clipboard { } } +/// The pasteboard's text, as a paste takes it: none when it holds no text. +#[cfg(target_os = "macos")] +fn desktop_clipboard() -> Option { + let pasted = std::process::Command::new("pbpaste").output().unwrap(); + assert!(pasted.status.success()); + Some(String::from_utf8(pasted.stdout).unwrap()).filter(|text| !text.is_empty()) +} + /// The X clipboard's text, as a paste takes it: none with no owner, or one /// offering no text. -fn x11_clipboard() -> Option { +#[cfg(target_os = "linux")] +fn desktop_clipboard() -> Option { use x11rb::connection::Connection; use x11rb::protocol::Event; use x11rb::protocol::xproto::{AtomEnum, ConnectionExt, CreateWindowAux, WindowClass}; @@ -549,7 +676,7 @@ fn x11_clipboard() -> Option { /// A page that closes itself fails its own source and leaves the canvas, /// while the page beside it in the same helper keeps drawing. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_page_that_closes_itself_fails_alone() { local(async { let closer = page(""); @@ -566,7 +693,7 @@ async fn a_page_that_closes_itself_fails_alone() { /// source, while everything else keeps drawing. A crash of the helper every /// page shares fails them all and nothing else, and a reload starts a new one. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_crash_while_loading_drops_only_its_source() { local(async { let crash = Source::Browser { @@ -602,7 +729,7 @@ async fn a_crash_while_loading_drops_only_its_source() { /// leaves the canvas, and no longer reports a paint path, and a reload draws /// it again. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_crash_after_drawing_leaves_the_canvas() { local(async { let red = page(""); @@ -638,7 +765,7 @@ async fn a_crash_after_drawing_leaves_the_canvas() { /// A second studio on the profile while it is in use fails its pages saying /// why, and leaves the first one's drawing. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn cookies_survive_a_restart() { local(async { // Red until it has seen its cookie, then green. @@ -713,7 +840,7 @@ async fn serve(html: &'static str) -> String { /// component updates, a spellcheck dictionary, the network time, or /// autofill's guesses at a page's text field. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn the_helper_requests_only_its_pages() { use std::os::unix::fs::PermissionsExt; use tokio::io::AsyncBufReadExt; @@ -738,13 +865,13 @@ async fn the_helper_requests_only_its_pages() { }); // The helper, told to use the proxy. let dir = tempfile::tempdir().unwrap(); - let program = dir.path().join("helper"); + let wrapper = dir.path().join("helper"); let script = format!( "#!/bin/sh\nexec '{}' \"$@\" --proxy-server=http://{proxy}\n", - env!("CARGO_BIN_EXE_moq-studio") + program().display() ); - std::fs::write(&program, script).unwrap(); - std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::write(&wrapper, script).unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); local(async { let url = serve("").await; @@ -753,7 +880,7 @@ async fn the_helper_requests_only_its_pages() { width: 320, height: 240, }; - let mut studio = Studio::start(&program, &dir.path().join("profile"), &[("page", page)]).await; + let mut studio = Studio::start(&wrapper, &dir.path().join("profile"), &[("page", page)]).await; studio.until_center(GREEN, &[]).await; // The browser asks for what it wants as it starts and as the page // loads, so every request seen had begun by the time the page drew. @@ -772,7 +899,7 @@ const DYING: &str = "MOQ_STUDIO_TEST_DYING_PROFILE"; /// holds even while CEF is still starting, which can last for good, as on a /// display that never answers. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_helper_exits_with_its_studio() { let profile = tempfile::tempdir().unwrap(); let _stall = stall(profile.path()); @@ -823,7 +950,7 @@ async fn a_studio_that_dies() { /// A studio stops a helper still starting CEF without waiting for it to /// finish starting, which can take forever. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs CEF and a Vulkan device; run by just render-sw"] +#[ignore = "needs CEF and a GPU; run by just render-sw, and on macOS by macos.yml"] async fn a_helper_stops_while_starting() { local(async { let profile = tempfile::tempdir().unwrap(); @@ -852,23 +979,41 @@ async fn until_stalled(studio: u32, profile: &Path) -> u32 { let state = std::fs::canonicalize(profile).unwrap().join("Local State"); let deadline = Instant::now().saturating_add(TIMEOUT); loop { - if let Some(helper) = helper(studio) { - let fds = std::fs::read_dir(format!("/proc/{helper}/fd")) - .into_iter() - .flatten() - .flatten(); - if fds - .filter_map(|fd| std::fs::read_link(fd.path()).ok()) - .any(|path| path == state) - { - return helper; - } + if let Some(helper) = helper(studio) + && open_files(helper).contains(&state) + { + return helper; } assert!(Instant::now() < deadline, "no helper reads {}", state.display()); kio::clock::sleep(Duration::from_millis(30)).await; } } +/// The files process `pid` holds open. +#[cfg(target_os = "linux")] +fn open_files(pid: u32) -> Vec { + let fds = std::fs::read_dir(format!("/proc/{pid}/fd")) + .into_iter() + .flatten() + .flatten(); + fds.filter_map(|fd| std::fs::read_link(fd.path()).ok()).collect() +} + +/// The files process `pid` holds open. +#[cfg(target_os = "macos")] +fn open_files(pid: u32) -> Vec { + // One field per line, each a letter and its value: `n` is a file's name. + let listed = std::process::Command::new("lsof") + .args(["-n", "-Fn", "-p", &pid.to_string()]) + .output() + .unwrap(); + String::from_utf8_lossy(&listed.stdout) + .lines() + .filter_map(|line| line.strip_prefix('n')) + .map(PathBuf::from) + .collect() +} + /// The one helper `studio` still runs: a child started with the helper's /// argument. fn helper(studio: u32) -> Option { @@ -878,9 +1023,7 @@ fn helper(studio: u32) -> Option { .map(|process| process.pid) } -/// The renderers under `helper`. CEF forks them from its zygote, whose -/// arguments they keep, so they are told apart by the compositor thread every -/// renderer runs. +/// The renderers under `helper`. fn renderers(helper: u32) -> Vec { let processes = processes(); let mut family = vec![helper]; @@ -894,18 +1037,30 @@ fn renderers(helper: u32) -> Vec { ); at += 1; } - family + family.into_iter().filter(|&pid| is_renderer(pid, &processes)).collect() +} + +/// Whether `pid` is a renderer. CEF forks them from its zygote, whose +/// arguments they keep, so they are told apart by the compositor thread every +/// renderer runs. +#[cfg(target_os = "linux")] +fn is_renderer(pid: u32, _: &[Process]) -> bool { + let threads = std::fs::read_dir(format!("/proc/{pid}/task")) .into_iter() - .filter(|pid| { - let threads = std::fs::read_dir(format!("/proc/{pid}/task")) - .into_iter() - .flatten() - .flatten(); - threads - .filter_map(|thread| std::fs::read_to_string(thread.path().join("comm")).ok()) - .any(|name| name.trim_end() == "Compositor") - }) - .collect() + .flatten() + .flatten(); + threads + .filter_map(|thread| std::fs::read_to_string(thread.path().join("comm")).ok()) + .any(|name| name.trim_end() == "Compositor") +} + +/// Whether `pid` is a renderer, which macOS starts with its type in its +/// arguments, having no zygote. +#[cfg(target_os = "macos")] +fn is_renderer(pid: u32, processes: &[Process]) -> bool { + processes + .iter() + .any(|process| process.pid == pid && process.args.iter().any(|arg| arg == b"--type=renderer")) } struct Process { @@ -915,7 +1070,37 @@ struct Process { args: Vec>, } +/// Every process running, leaving out the dead ones waiting to be reaped. A +/// path with a space splits into several arguments, which no test looks at. +#[cfg(target_os = "macos")] +fn processes() -> Vec { + let listed = std::process::Command::new("ps") + .args(["-axww", "-o", "pid=,ppid=,pgid=,stat=,command="]) + .output() + .unwrap(); + String::from_utf8_lossy(&listed.stdout) + .lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + let pid = fields.next()?.parse().ok()?; + let parent = fields.next()?.parse().ok()?; + let group = fields.next()?.parse().ok()?; + if fields.next()?.starts_with('Z') { + return None; + } + let args = fields.map(|arg| arg.as_bytes().to_vec()).collect(); + Some(Process { + pid, + parent, + group, + args, + }) + }) + .collect() +} + /// Every process running, leaving out the dead ones waiting to be reaped. +#[cfg(target_os = "linux")] fn processes() -> Vec { let Ok(entries) = std::fs::read_dir("/proc") else { return Vec::new();