//! Native host for the chandra compositor component. //! //! The compositor is a wasm component (build/compositor.wasm) that imports exactly one //! interface, `chandra:host/sys` (wit/host/sys.wit): sockets, memfd, poll, spawn, files, time. //! This program is the other side of that interface. The component only ever holds integer //! handles; every real file descriptor lives here. //! //! chandra-host [--component PATH] [-- compositor args...] //! chandra-host build/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window use std::ffi::CString; use std::sync::atomic::AtomicBool; use std::io::Read; use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; use wasmtime::component::{Component, HasSelf, Linker}; use wasmtime::{Config, Engine, Result, Store}; mod plasmoid; mod raster; #[cfg(feature = "drm")] mod kms; wasmtime::component::bindgen!({ path: "../wit/host", world: "compositor", // The desktop value types are the same WIT the modules use: share the Rust types, so draw ops // flow from a module straight to the compositor without conversion. // Draw operations are compared to reuse the cached wallpaper. additional_derives: [PartialEq], with: { "chandra:desktop/types@0.1.0": plasmoid::ph::chandra::desktop::types, "chandra:desktop/theme@0.1.0": plasmoid::ph::chandra::desktop::theme, }, }); use chandra::host::font::Glyph; use chandra::host::sys::{Host, Received}; /// SIGUSR1 (reload the panel modules) arrived and not yet taken by sys.take-sigusr1; whether /// its handler is installed. static SIGUSR1_SEEN: AtomicBool = AtomicBool::new(false); static SIGUSR1_INSTALLED: AtomicBool = AtomicBool::new(false); #[derive(Default)] struct State { /// Address of the private session bus launched apps use (started on first spawn). private_bus: Option, bus_tried: bool, started: Option, /// TTF faces loaded by the component (`font.load`), by slot, and their glyph cache. fonts: raster::Fonts, /// The framebuffer and client surfaces behind `chandra:host/raster`. raster: raster::Raster, /// Runs the panel modules; set once the engine exists. pl: Option, /// Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`. extra_fds: std::collections::HashMap>, /// The screen recording frame in flight (`grab-recording-frame`) and how much of it went out. rec_frame: Vec, rec_sent: usize, /// The frozen screen of a screenshot (`snapshot-frame`): RGBA8888, its width and height. snap: Vec, snap_w: i32, snap_h: i32, } fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) { let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() }; addr.sun_family = libc::AF_UNIX as libc::sa_family_t; let bytes = path.as_bytes(); let n = bytes.len().min(addr.sun_path.len() - 1); for (i, b) in bytes[..n].iter().enumerate() { addr.sun_path[i] = *b as libc::c_char; } (addr, std::mem::size_of::() as libc::socklen_t) } fn set_nonblock_cloexec(fd: i32) { unsafe { let fl = libc::fcntl(fd, libc::F_GETFL, 0); if fl >= 0 { libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); } let fdfl = libc::fcntl(fd, libc::F_GETFD, 0); if fdfl >= 0 { libc::fcntl(fd, libc::F_SETFD, fdfl | libc::FD_CLOEXEC); } } } impl State { /// A private session bus, so single-instance apps (Firefox, Kate, Dolphin...) don't forward /// their launch to an instance on the host session. Dies with this process. /// /// Only when nested inside another graphical session (WAYLAND_DISPLAY or DISPLAY set). As a /// login session (--drm from a VT or the display manager) the session bus *is* ours, and it is /// where the PAM-unlocked gnome-keyring (org.freedesktop.secrets), portals and notifications /// live: a private bus would hide them, so apps D-Bus-activate a fresh, locked keyring on it. fn private_bus(&mut self) -> Option { if self.bus_tried { return self.private_bus.clone(); } self.bus_tried = true; let nested = ["WAYLAND_DISPLAY", "DISPLAY"] .iter() .any(|v| std::env::var_os(v).map(|x| !x.is_empty()).unwrap_or(false)); if !nested { return None; } let mut cmd = Command::new("dbus-daemon"); cmd.args(["--session", "--nofork", "--print-address=1"]) .stdout(Stdio::piped()) .stderr(Stdio::null()); unsafe { cmd.pre_exec(|| { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); Ok(()) }); } let mut child = cmd.spawn().ok()?; let mut out = child.stdout.take()?; let mut buf = [0u8; 256]; let n = out.read(&mut buf).unwrap_or(0); std::mem::forget(child); // keep it running; PDEATHSIG ends it with us std::mem::forget(out); if n > 0 { let s = String::from_utf8_lossy(&buf[..n]); self.private_bus = s.lines().next().map(|l| l.to_string()); } self.private_bus.clone() } } impl State { fn pl(&mut self) -> &mut plasmoid::Runtime { self.pl.as_mut().expect("plasmoid runtime is set before the component runs") } } impl chandra::host::plasmoids::Host for State { fn load(&mut self, path: String) -> Result { let l = self.pl().load(&path)?; Ok(chandra::host::plasmoids::Loaded { handle: l.handle, id: l.info.id, name: l.info.name, preferred: l.info.preferred, min_width: l.info.min_width, stretch: l.info.stretch, imports: l.imports, }) } fn unload(&mut self, handle: u32) { self.pl().unload(handle); } fn set_tokens(&mut self, t: plasmoid::ph::chandra::desktop::theme::Tokens) { self.pl().shared.borrow_mut().tokens = Some(t); } fn render( &mut self, handle: u32, box_: plasmoid::ph::chandra::desktop::types::Size, ) -> Vec { self.pl().render(handle, box_) } fn popup(&mut self, handle: u32) -> Option { self.pl().popup(handle).map(|p| chandra::host::plasmoids::PopupSurface { box_: p.size, ops: p.ops }) } fn on_event( &mut self, handle: u32, on_popup: bool, event: plasmoid::ph::chandra::desktop::types::InputEvent, ) -> bool { self.pl().on_event(handle, on_popup, event) } fn config_items(&mut self, handle: u32) -> Vec { self.pl() .config_items(handle) .into_iter() .map(|c| chandra::host::plasmoids::ConfigItem { key: c.key, label: c.label, choices: c.choices, value: c.value }) .collect() } fn set_config(&mut self, handle: u32, key: String, value: String) -> bool { self.pl().set_config(handle, &key, &value) } fn desktop_backdrop(&mut self, handle: u32) -> i32 { self.pl().desktop_backdrop(handle) } fn desktop_scroll(&mut self, handle: u32, x: i32, y: i32, dx: i32, dy: i32) -> bool { self.pl().desktop_scroll(handle, x, y, dx, dy) } fn desktop_tick(&mut self, handle: u32, now_ms: u32) -> u32 { self.pl().desktop_tick(handle, now_ms) } fn publish_table(&mut self, which: u32, rows: Vec) { if let Some(t) = self.pl().shared.borrow_mut().tables.get_mut(which as usize) { *t = rows; } } fn publish_state(&mut self, layout_mode: i32, inspector_on: bool) { let sh = &self.pl().shared; let mut sh = sh.borrow_mut(); sh.layout_mode = layout_mode; sh.inspector_on = inspector_on; } fn publish_wallpaper(&mut self, current: i32) { self.pl().shared.borrow_mut().wallpaper = current; } fn publish_desktop(&mut self, current: i32) { self.pl().shared.borrow_mut().desktop = current; } fn publish_session_settings(&mut self, on: u32) { self.pl().shared.borrow_mut().session_settings = on; } fn publish_screenshot(&mut self, state: u32) { self.pl().shared.borrow_mut().screenshot = state; } fn publish_power(&mut self, screen_off: u32, suspend: u32) { let mut sh = self.pl().shared.borrow_mut(); sh.screen_off_min = screen_off; sh.suspend_min = suspend; } fn publish_battery(&mut self, percent: i32, state: u32, secs_left: u32) { self.pl().shared.borrow_mut().battery = (percent, state, secs_left); } fn publish_system(&mut self, s: chandra::host::plasmoids::SystemSnapshot) { use plasmoid::ph::chandra::desktop::system::Snapshot; self.pl().shared.borrow_mut().system = Some(Snapshot { cpu_permille: s.cpu_permille, mem_used_kib: s.mem_used_kib, mem_total_kib: s.mem_total_kib, battery_percent: s.battery_percent, charging: s.charging, uptime_secs: s.uptime_secs, net_rx_bytes_per_sec: s.net_rx_bytes_per_sec, net_tx_bytes_per_sec: s.net_tx_bytes_per_sec, load_centi: s.load_centi, }); } fn publish_windows(&mut self, wins: Vec) { self.pl().shared.borrow_mut().windows = wins.into_iter().map(|w| (w.id, w.title, w.app_id, w.focused)).collect(); } fn next_request(&mut self) -> Option { use chandra::host::plasmoids::Request as R; use plasmoid::Req; let r = self.pl().shared.borrow_mut().requests.pop_front()?; Some(match r { Req::Launch(s) => R::Launch(s), Req::FocusWindow(n) => R::FocusWindow(n), Req::SetLayout(n) => R::SetLayout(n), Req::SetInspector(b) => R::SetInspector(b), Req::LoadModule(s) => R::LoadModule(s), Req::UnloadInstance(s) => R::UnloadInstance(s), Req::MoveInstance(slot, delta) => { R::MoveInstance(chandra::host::plasmoids::InstanceMove { slot, delta }) } Req::Browse => R::Browse, Req::Logout => R::Logout, Req::ReloadSession => R::ReloadSession, Req::SetWallpaper(n) => R::SetWallpaper(n), Req::SetSessionSetting(index, on) => { R::SetSessionSetting(chandra::host::plasmoids::SettingChange { index, on }) } Req::Screenshot(code) => R::Screenshot(code), Req::SetScreenOff(m) => R::SetScreenOff(m), Req::SetSuspendAfter(m) => R::SetSuspendAfter(m), Req::PowerAction(a) => R::PowerAction(a), Req::Network(action, ssid, password) => { R::Network(chandra::host::plasmoids::NetworkRequest { action, ssid, password }) } Req::Shortcut(code) => R::Shortcut(code), Req::DefaultApp(code) => R::DefaultApp(code), Req::SetDesktop(i) => R::SetDesktop(i), Req::FaceUnlock(code) => R::FaceUnlock(code), Req::GameLibrary(action, game, mode) => { R::GameLibrary(chandra::host::plasmoids::GameRequest { action, game, mode }) } }) } fn take_focus_request(&mut self) -> Option { self.pl().shared.borrow_mut().focus_req.take() } fn list_wasm_files(&mut self, dir: String) -> Vec { let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; let mut v: Vec = rd .filter_map(|e| e.ok()) .map(|e| e.file_name().to_string_lossy().into_owned()) .filter(|n| n.ends_with(".wasm")) .collect(); v.sort(); v } fn picker_start(&mut self) -> bool { self.pl().picker_start() } fn picker_poll(&mut self) -> chandra::host::plasmoids::PickerState { use chandra::host::plasmoids::PickerState as P; match self.pl().picker_poll() { None => P::Open, Some(None) => P::Cancelled, Some(Some(path)) => P::Chosen(path), } } } impl chandra::host::display::Host for State { fn open(&mut self) -> Option { #[cfg(feature = "drm")] { kms::open() } #[cfg(not(feature = "drm"))] { eprintln!("this host was built without the `drm` feature (no login-session backend)"); None } } fn poll(&mut self) -> bool { #[cfg(feature = "drm")] return kms::poll(); #[cfg(not(feature = "drm"))] false } fn frame_ready(&mut self) -> bool { #[cfg(feature = "drm")] return kms::frame_ready(); #[cfg(not(feature = "drm"))] false } fn present_frame(&mut self) { #[cfg(feature = "drm")] kms::present(&self.raster.fb, self.raster.w as u32, self.raster.h as u32); } fn present(&mut self, pixels: Vec, width: u32, height: u32) { #[cfg(feature = "drm")] kms::present(&pixels, width, height); #[cfg(not(feature = "drm"))] let _ = (pixels, width, height); } fn set_power(&mut self, on: bool) { #[cfg(feature = "drm")] kms::set_power(on); #[cfg(not(feature = "drm"))] let _ = on; } fn set_cursor_shape(&mut self, shape: u32) { #[cfg(feature = "drm")] kms::set_cursor_shape(shape); #[cfg(not(feature = "drm"))] let _ = shape; } fn take_input(&mut self) -> Vec { #[cfg(feature = "drm")] return kms::take_input(); #[cfg(not(feature = "drm"))] Vec::new() } fn close(&mut self) { #[cfg(feature = "drm")] kms::close(); } } impl chandra::host::font::Host for State { fn load(&mut self, slot: u32, path: String) -> bool { self.fonts.load(slot, &path) } fn rasterise(&mut self, slot: u32, codepoint: u32, size: u32) -> Glyph { let g = self.fonts.glyph(slot, codepoint, size); Glyph { width: g.w, height: g.h, xoff: g.xoff, yoff: g.yoff, advance: g.advance, coverage: g.coverage.clone() } } } impl chandra::host::raster::Host for State { fn capture(&mut self, fd: i32, offset: i32, stride: i32, width: i32, height: i32, format: i32) -> u32 { if fd < 0 || offset < 0 || stride <= 0 || width <= 0 || height <= 0 { return 0; } let len = stride as i64 * height as i64; let end = offset as i64 + len; unsafe { let mut st: libc::stat = std::mem::zeroed(); if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < end { return 0; } // Mapping a large pool only reserves address space; just the pages copied are touched. let p = libc::mmap(std::ptr::null_mut(), end as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); if p == libc::MAP_FAILED { return 0; } let src = std::slice::from_raw_parts((p as *const u8).add(offset as usize), len as usize); let surface = raster::Surface::from_bgra(src, stride as usize, width, height, format == 1); libc::munmap(p, end as usize); match surface { Some(s) => self.raster.add_surface(s), None => 0, } } } fn release(&mut self, id: u32) { self.raster.release(id); } fn load_image(&mut self, path: String) -> u32 { self.raster.images.load(&path) } fn thumbnail(&mut self, surface: u32, w: i32, h: i32, reuse: u32) -> u32 { self.raster.thumbnail(surface, w, h, reuse) } fn image_pixels(&mut self, w: i32, h: i32, rgba: Vec, reuse: u32) -> u32 { self.raster.image_pixels(w, h, rgba, reuse) } fn submit(&mut self, f: chandra::host::raster::Frame) { self.raster.submit_frame(f, &mut self.fonts); } fn read_frame(&mut self) -> Vec { self.raster.fb.clone() } fn export_memfd(&mut self) -> i32 { let data = self.raster.to_argb8888(); let Ok(name) = CString::new("chandra-frame") else { return -1 }; unsafe { let fd = libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC); if fd < 0 { return -1; } let mut done = 0usize; while done < data.len() { let n = libc::write(fd, data[done..].as_ptr() as *const _, data.len() - done); if n <= 0 { libc::close(fd); return -1; } done += n as usize; } fd } } fn write_frame_png(&mut self, path: String) -> bool { let (w, h) = (self.raster.w, self.raster.h); if w <= 0 || h <= 0 { return false; } let Ok(file) = std::fs::File::create(&path) else { return false }; let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w as u32, h as u32); enc.set_color(png::ColorType::Rgba); enc.set_depth(png::BitDepth::Eight); enc.set_compression(png::Compression::Fast); match enc.write_header() { Ok(mut wr) => wr.write_image_data(&self.raster.fb).is_ok(), Err(_) => false, } } fn grab_recording_frame(&mut self, x: i32, y: i32, w: i32, h: i32, pointer: bool, px: i32, py: i32) -> bool { let (fw, fh) = (self.raster.w, self.raster.h); if w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fw || y + h > fh { return false; } let (w, h) = (w as usize, h as usize); let mut out = std::mem::take(&mut self.rec_frame); out.clear(); out.reserve(w * h * 4); for row in 0..h { let at = ((y as usize + row) * fw as usize + x as usize) * 4; out.extend_from_slice(&self.raster.fb[at..at + w * 4]); } for a in out.iter_mut().skip(3).step_by(4) { *a = 255; } if pointer { draw_record_pointer(&mut out, w as i32, h as i32, px - x, py - y); } self.rec_frame = out; self.rec_sent = 0; true } fn send_recording_frame(&mut self, fd: i32) -> i32 { unsafe { let fl = libc::fcntl(fd, libc::F_GETFL); if fl >= 0 && fl & libc::O_NONBLOCK == 0 { libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); } while self.rec_sent < self.rec_frame.len() { let rest = &self.rec_frame[self.rec_sent..]; let n = libc::write(fd, rest.as_ptr() as *const _, rest.len()); if n < 0 { let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); if e == libc::EINTR { continue; } if e == libc::EAGAIN || e == libc::EWOULDBLOCK { break; } return -1; } self.rec_sent += n as usize; } } (self.rec_frame.len() - self.rec_sent).min(i32::MAX as usize) as i32 } fn snapshot_frame(&mut self) -> bool { if self.raster.w <= 0 || self.raster.h <= 0 { return false; } self.snap.clear(); self.snap.extend_from_slice(&self.raster.fb); (self.snap_w, self.snap_h) = (self.raster.w, self.raster.h); true } fn snapshot_png(&mut self, x: i32, y: i32, w: i32, h: i32) -> Vec { let (x0, y0) = (x.max(0), y.max(0)); let (x1, y1) = (x.saturating_add(w).min(self.snap_w), y.saturating_add(h).min(self.snap_h)); if x1 <= x0 || y1 <= y0 { return Vec::new(); } let (w, h) = (x1 - x0, y1 - y0); let px = self.snapshot_pixels(x0, y0, w, h, w, h); let mut out = Vec::new(); let mut enc = png::Encoder::new(&mut out, w as u32, h as u32); enc.set_color(png::ColorType::Rgba); enc.set_depth(png::BitDepth::Eight); let ok = match enc.write_header() { Ok(mut wr) => wr.write_image_data(&px).is_ok(), Err(_) => false, }; if ok { out } else { Vec::new() } } fn snapshot_pixels(&mut self, x: i32, y: i32, w: i32, h: i32, out_w: i32, out_h: i32) -> Vec { if out_w <= 0 || out_h <= 0 || out_w > 16384 || out_h > 16384 { return Vec::new(); } let mut out = vec![0u8; out_w as usize * out_h as usize * 4]; for ty in 0..out_h { let sy = y as i64 + ty as i64 * h as i64 / out_h as i64; for tx in 0..out_w { let sx = x as i64 + tx as i64 * w as i64 / out_w as i64; let d = (ty as usize * out_w as usize + tx as usize) * 4; if sx >= 0 && sy >= 0 && sx < self.snap_w as i64 && sy < self.snap_h as i64 { let s = (sy as usize * self.snap_w as usize + sx as usize) * 4; out[d..d + 3].copy_from_slice(&self.snap[s..s + 3]); } out[d + 3] = 255; } } out } } /// The arrow pointer with its tip at (x, y) in an RGBA `w` x `h` frame, as the compositor's /// recorder draws it: a black body widening over 13 rows and a short tail, then the white inside. fn draw_record_pointer(px: &mut [u8], w: i32, h: i32, x: i32, y: i32) { let mut fill = |rx: i32, ry: i32, rw: i32, rh: i32, v: u8| { for j in ry.max(0)..(ry + rh).min(h) { for i in rx.max(0)..(rx + rw).min(w) { let at = ((j * w + i) * 4) as usize; px[at..at + 4].copy_from_slice(&[v, v, v, 255]); } } }; for i in 0..17 { let (l, bw) = if i < 13 { (0, i * 2 / 3 + 1) } else { (3 + (i - 13), 3) }; fill(x + l - 1, y + i - 1, bw + 2, 3, 0); } for i in 1..16 { let (l, bw) = if i < 13 { (0, i * 2 / 3 - 1) } else { (4 + (i - 13), 1) }; if bw > 0 { fill(x + l + 1, y + i, bw, 1, 255); } } } impl Host for State { fn unix_listen(&mut self, path: String) -> i32 { let _ = std::fs::remove_file(&path); unsafe { let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); if fd < 0 { return -1; } set_nonblock_cloexec(fd); let (addr, len) = sockaddr_un(&path); if libc::bind(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 || libc::listen(fd, 16) < 0 { libc::close(fd); return -1; } fd } } fn unix_accept(&mut self, listen_fd: i32) -> i32 { unsafe { let fd = libc::accept(listen_fd, std::ptr::null_mut(), std::ptr::null_mut()); if fd < 0 { return -1; } set_nonblock_cloexec(fd); fd } } fn unix_connect(&mut self, path: String) -> i32 { unsafe { let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); if fd < 0 { return -1; } let (addr, len) = sockaddr_un(&path); if libc::connect(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 { libc::close(fd); return -1; } fd } } fn close_fd(&mut self, fd: i32) { if fd >= 0 { // A closed client socket's number is reused by the next one: drop what it left. if let Some(left) = self.extra_fds.remove(&fd) { for f in left { unsafe { libc::close(f) }; } } unsafe { libc::close(fd) }; } } fn unlink(&mut self, path: String) { let _ = std::fs::remove_file(path); } fn poll_read(&mut self, fd: i32, timeout_ms: i32) -> i32 { let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; let r = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; if r < 0 { -1 } else if r == 0 { 0 } else if pfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { 1 } else { 0 } } fn wait_readable(&mut self, fds: Vec, timeout_ms: i32) -> i32 { let mut pfds: Vec = fds .into_iter() .chain(kms::fds()) .filter(|&fd| fd >= 0) .map(|fd| libc::pollfd { fd, events: libc::POLLIN, revents: 0 }) .collect(); unsafe { libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, timeout_ms) } } fn recvmsg(&mut self, fd: i32, max_len: u32) -> Received { // Fds from the previous read nobody took would leak: close them. if let Some(left) = self.extra_fds.remove(&fd) { for f in left { unsafe { libc::close(f) }; } } let mut data = vec![0u8; max_len as usize]; if data.is_empty() { return Received { count: 0, fd: -1, data }; } unsafe { let mut iov = libc::iovec { iov_base: data.as_mut_ptr() as *mut _, iov_len: data.len() }; // A client flushes up to 28 fds (libwayland's limit) in one sendmsg, e.g. a Vulkan // swapchain making a wl_shm_pool per image: every one is needed, in order. let space = libc::CMSG_SPACE((std::mem::size_of::() * 32) as u32) as usize; let mut cbuf = vec![0u8; space]; let mut msg: libc::msghdr = std::mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = cbuf.as_mut_ptr() as *mut _; msg.msg_controllen = space as _; let n = libc::recvmsg(fd, &mut msg, libc::MSG_CMSG_CLOEXEC); if n < 0 { let e = *libc::__errno_location(); let c = if e == libc::EAGAIN || e == libc::EWOULDBLOCK { -1 } else { -2 }; return Received { count: c, fd: -1, data: Vec::new() }; } let mut got = -1; let mut cm = libc::CMSG_FIRSTHDR(&msg); while !cm.is_null() { if (*cm).cmsg_level == libc::SOL_SOCKET && (*cm).cmsg_type == libc::SCM_RIGHTS { let n_fds = ((*cm).cmsg_len as usize - libc::CMSG_LEN(0) as usize) / std::mem::size_of::(); let fds = libc::CMSG_DATA(cm) as *const i32; for i in 0..n_fds { let f = *fds.add(i); if got < 0 { got = f; } else { self.extra_fds.entry(fd).or_default().push_back(f); } } } cm = libc::CMSG_NXTHDR(&msg, cm); } data.truncate(n as usize); Received { count: n as i32, fd: got, data } } } fn take_fd(&mut self, sock: i32) -> i32 { let q = match self.extra_fds.get_mut(&sock) { Some(q) => q, None => return -1, }; let f = q.pop_front().unwrap_or(-1); if q.is_empty() { self.extra_fds.remove(&sock); } f } fn sendmsg(&mut self, fd: i32, data: Vec, send_fd: i32) -> i32 { if data.is_empty() { return 0; } unsafe { let mut total = 0usize; let mut with_fd = send_fd >= 0; while total < data.len() { let mut iov = libc::iovec { iov_base: data.as_ptr().add(total) as *mut _, iov_len: data.len() - total, }; let space = libc::CMSG_SPACE(std::mem::size_of::() as u32) as usize; let mut cbuf = vec![0u8; space]; let mut msg: libc::msghdr = std::mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; if with_fd { msg.msg_control = cbuf.as_mut_ptr() as *mut _; msg.msg_controllen = space as _; let cm = libc::CMSG_FIRSTHDR(&msg); (*cm).cmsg_level = libc::SOL_SOCKET; (*cm).cmsg_type = libc::SCM_RIGHTS; (*cm).cmsg_len = libc::CMSG_LEN(std::mem::size_of::() as u32) as _; std::ptr::copy_nonoverlapping(&send_fd as *const i32 as *const u8, libc::CMSG_DATA(cm), 4); } let sent = libc::sendmsg(fd, &msg, libc::MSG_NOSIGNAL); if sent < 0 { let e = *libc::__errno_location(); if e == libc::EAGAIN || e == libc::EWOULDBLOCK { let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; libc::poll(&mut pfd, 1, 50); continue; } return -1; } total += sent as usize; with_fd = false; // ancillary data goes with the first chunk only } total as i32 } } fn memfd_create(&mut self, name: String, size: i32) -> i32 { let Ok(cname) = CString::new(name) else { return -1 }; unsafe { let fd = libc::memfd_create(cname.as_ptr(), libc::MFD_CLOEXEC); if fd < 0 { return -1; } if size > 0 && libc::ftruncate(fd, size as libc::off_t) < 0 { libc::close(fd); return -1; } fd } } fn pwrite(&mut self, fd: i32, data: Vec, offset: i32) -> i32 { if offset < 0 { // A pipe or socket (clipboard paste, screen recording): write what fits now. 0 when it // is full, -1 on error. (Rust already ignores SIGPIPE, so a gone reader is just EPIPE.) unsafe { let fl = libc::fcntl(fd, libc::F_GETFL); if fl >= 0 && fl & libc::O_NONBLOCK == 0 { libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); } let w = libc::write(fd, data.as_ptr() as *const _, data.len()); if w < 0 { let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); return if e == libc::EAGAIN || e == libc::EWOULDBLOCK || e == libc::EINTR { 0 } else { -1 }; } return w as i32; } } let w = unsafe { libc::pwrite(fd, data.as_ptr() as *const _, data.len(), offset as libc::off_t) }; if w < 0 { -1 } else { w as i32 } } fn mmap_read(&mut self, fd: i32, size: i32) -> Vec { if fd < 0 || size <= 0 { return Vec::new(); } unsafe { let mut st: libc::stat = std::mem::zeroed(); if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < size as i64 { return Vec::new(); } let p = libc::mmap(std::ptr::null_mut(), size as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); if p == libc::MAP_FAILED { return Vec::new(); } let out = std::slice::from_raw_parts(p as *const u8, size as usize).to_vec(); libc::munmap(p, size as usize); out } } fn mmap_read_at(&mut self, fd: i32, offset: i32, len: i32) -> Vec { if fd < 0 || offset < 0 || len <= 0 { return Vec::new(); } let end = offset as i64 + len as i64; unsafe { let mut st: libc::stat = std::mem::zeroed(); if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < end { return Vec::new(); } // Mapping a large pool only reserves address space; just the pages copied are touched. let p = libc::mmap(std::ptr::null_mut(), end as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); if p == libc::MAP_FAILED { return Vec::new(); } let out = std::slice::from_raw_parts((p as *const u8).add(offset as usize), len as usize).to_vec(); libc::munmap(p, end as usize); out } } fn read_file(&mut self, path: String) -> Vec { std::fs::read(path).unwrap_or_default() } fn write_file(&mut self, path: String, data: Vec) -> i32 { match std::fs::write(path, &data) { Ok(()) => 0, Err(_) => -1, } } fn append_file(&mut self, path: String, data: Vec) -> i32 { use std::io::Write; let f = std::fs::OpenOptions::new().append(true).create(true).open(path); match f.and_then(|mut f| f.write_all(&data)) { Ok(()) => 0, Err(_) => -1, } } fn read_proc(&mut self, path: String) -> Vec { // /proc and /sys files report size 0: read to EOF, capped at 64 KiB. let Ok(f) = std::fs::File::open(path) else { return Vec::new() }; let mut out = Vec::new(); let _ = f.take(65536).read_to_end(&mut out); out } fn mkdir_p(&mut self, path: String) -> bool { std::fs::create_dir_all(path).is_ok() } fn list_desktop_files(&mut self, dir: String) -> Vec { let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; rd.filter_map(|e| e.ok()) .map(|e| e.file_name().to_string_lossy().into_owned()) .filter(|n| n.ends_with(".desktop")) .collect() } fn sleep_ms(&mut self, ms: i32) { if ms > 0 { std::thread::sleep(std::time::Duration::from_millis(ms as u64)); } } fn monotonic_ms(&mut self) -> u64 { self.started.get_or_insert_with(std::time::Instant::now).elapsed().as_millis() as u64 } fn log(&mut self, message: String) { eprintln!("{message}"); } fn getpid(&mut self) -> i32 { std::process::id() as i32 } fn take_sigusr1(&mut self) -> bool { // The handler only sets a flag. No SA_RESTART: a blocked poll() in wait-readable returns // EINTR, so an idle compositor runs a pass and sees the request. extern "C" fn on_sigusr1(_: libc::c_int) { SIGUSR1_SEEN.store(true, std::sync::atomic::Ordering::SeqCst); } if !SIGUSR1_INSTALLED.swap(true, std::sync::atomic::Ordering::SeqCst) { unsafe { let mut sa: libc::sigaction = std::mem::zeroed(); sa.sa_sigaction = on_sigusr1 as extern "C" fn(libc::c_int) as usize; libc::sigemptyset(&mut sa.sa_mask); sa.sa_flags = 0; libc::sigaction(libc::SIGUSR1, &sa, std::ptr::null_mut()); } } SIGUSR1_SEEN.swap(false, std::sync::atomic::Ordering::SeqCst) } fn wall_time_field(&mut self, which: i32) -> i32 { unsafe { let t = libc::time(std::ptr::null_mut()); let mut tm: libc::tm = std::mem::zeroed(); libc::localtime_r(&t, &mut tm); match which { 0 => tm.tm_year + 1900, 1 => tm.tm_mon + 1, 2 => tm.tm_mday, 3 => tm.tm_hour, 4 => tm.tm_min, 5 => tm.tm_sec, 6 => tm.tm_wday, _ => 0, } } } fn getenv(&mut self, name: String) -> String { std::env::var(name).unwrap_or_default() } fn has_exe(&mut self, name: String) -> bool { let ok = |p: &std::path::Path| { CString::new(p.as_os_str().as_encoded_bytes()) .map(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) == 0 }) .unwrap_or(false) }; if name.contains('/') { return ok(std::path::Path::new(&name)); } std::env::var_os("PATH") .map(|p| std::env::split_paths(&p).any(|d| ok(&d.join(&name)))) .unwrap_or(false) } fn spawn(&mut self, cmd: String, display: String) -> bool { let bus = self.private_bus(); let mut c = Command::new("/bin/sh"); c.arg("-c").arg(&cmd); // Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak on // the real session bus, so they keep it; everything else gets the private bus. if let Some(b) = bus { if !cmd.contains("flatpak run") { c.env("DBUS_SESSION_BUS_ADDRESS", b); } } c.env("WAYLAND_DISPLAY", display) .env_remove("DISPLAY") // Make toolkits pick our Wayland socket, not X11 or the host session. .env("XDG_SESSION_TYPE", "wayland") .env("QT_QPA_PLATFORM", "wayland") .env("GDK_BACKEND", "wayland") .env("SDL_VIDEODRIVER", "wayland") .env("MOZ_ENABLE_WAYLAND", "1") .env("ELECTRON_OZONE_PLATFORM_HINT", "wayland") .env("CLUTTER_BACKEND", "wayland") .stdin(Stdio::null()); unsafe { c.pre_exec(|| { libc::setsid(); libc::signal(libc::SIGCHLD, libc::SIG_DFL); Ok(()) }); } c.spawn().is_ok() } fn spawn_socket(&mut self, argv: String) -> i32 { use std::os::fd::{FromRawFd, IntoRawFd, OwnedFd}; let args: Vec<&str> = argv.split('\n').filter(|a| !a.is_empty()).collect(); if args.is_empty() || !args[0].starts_with('/') { return -1; } let mut sv = [-1i32; 2]; if unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0, sv.as_mut_ptr()) } != 0 { return -1; } let child_end = unsafe { OwnedFd::from_raw_fd(sv[1]) }; let out = match child_end.try_clone() { Ok(f) => f, Err(_) => { unsafe { libc::close(sv[0]) }; return -1; } }; let mut c = Command::new(args[0]); c.args(&args[1..]).stdin(Stdio::from(child_end)).stdout(Stdio::from(out)); unsafe { c.pre_exec(|| { libc::signal(libc::SIGCHLD, libc::SIG_DFL); libc::signal(libc::SIGPIPE, libc::SIG_DFL); Ok(()) }); } match c.spawn() { Ok(mut child) => { // Reap it when it exits, so it never lingers as a zombie. std::thread::spawn(move || { let _ = child.wait(); }); let fd = unsafe { OwnedFd::from_raw_fd(sv[0]) }; fd.into_raw_fd() } Err(_) => { unsafe { libc::close(sv[0]) }; -1 } } } } fn main() -> Result<()> { let mut args: Vec = std::env::args().skip(1).collect(); // First argument may be the component path; otherwise use the default build location. let component_path = if args.first().map(|a| a.ends_with(".wasm")).unwrap_or(false) { args.remove(0) } else { "build/compositor.wasm".to_string() }; if args.first().map(|a| a == "--").unwrap_or(false) { args.remove(0); } // No zombies from launched apps. unsafe { libc::signal(libc::SIGCHLD, libc::SIG_IGN) }; let mut config = Config::new(); config.wasm_component_model(true); let engine = Engine::new(&config)?; let component = match Component::from_file(&engine, &component_path) { Ok(c) => c, Err(e) => { eprintln!("error: cannot load {component_path}: {e}\n build it with `just compositor-wasm`"); std::process::exit(1); } }; let mut linker: Linker = Linker::new(&engine); chandra::host::sys::add_to_linker::>(&mut linker, |s| s)?; chandra::host::font::add_to_linker::>(&mut linker, |s| s)?; chandra::host::raster::add_to_linker::>(&mut linker, |s| s)?; chandra::host::display::add_to_linker::>(&mut linker, |s| s)?; chandra::host::plasmoids::add_to_linker::>(&mut linker, |s| s)?; let mut store = Store::new(&engine, State::default()); store.data_mut().pl = Some(plasmoid::Runtime::new(&engine)?); let compositor = Compositor::instantiate(&mut store, &component, &linker)?; let code = compositor.call_run(&mut store, &args)?; std::process::exit(code); }