Fennec OS 0.3.2: one app at a time, Raspberry Pi shell packages

- sf-core: only one app runs. Home, another app or a cast closes the app
  on screen (after the switch animation) instead of freezing it in the
  background. A frozen app that held a sound stream stalled PipeWire, so
  the next app could not play at all ("Failed to connect stream: No such
  entity" in Netflex after YouTube was sent home mid-video). The
  background limit and the low-memory watcher go with the freezing.
- Raspberry Pi: image/pi (installer on Raspberry Pi OS), aarch64 shell
  packages (sf-shell-<v>-aarch64, arch in pkg.toml, sf-update installs only
  its own architecture), CI builds the aarch64 shell too.
- sf-compositor: volume OSD, screencopy for remote view, blank cursor.
- SDK v0.1.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-11-02 19:38:09 +01:00
parent 54cdaf5e35
commit 9c710bedb9
33 changed files with 1329 additions and 319 deletions

View File

@@ -12,6 +12,8 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Volume OSD text (osd.rs): pure Rust, the font comes from the system.
ab_glyph = "0.2"
smithay = { version = "0.7", default-features = false, features = [
"backend_drm",
"backend_gbm",

View File

@@ -16,8 +16,12 @@
#[cfg(target_os = "linux")]
mod control;
#[cfg(target_os = "linux")]
mod osd;
#[cfg(target_os = "linux")]
mod output_mgmt;
#[cfg(target_os = "linux")]
mod screencopy;
#[cfg(target_os = "linux")]
mod state;
#[cfg(target_os = "linux")]
mod udev;

View File

@@ -0,0 +1,234 @@
//! The volume OSD: a dark pill at the top of the screen with a speaker
//! icon, a level bar and the level as a number ("Némítva" when muted), in
//! the style of the launcher's status pill.
//!
//! Drawn on the CPU into a small image (anti-aliased shapes, text from the
//! system's Noto Sans), only when the level, the mute state or the output
//! size changes; the compositor shows it as one textured element.
use ab_glyph::{Font, FontVec, PxScale, ScaleFont};
use smithay::backend::allocator::Fourcc;
use smithay::backend::renderer::element::memory::MemoryRenderBuffer;
use smithay::utils::Transform;
/// Size at 1080p (scaled with the output height).
const W: f32 = 460.0;
const H: f32 = 76.0;
const TOP: f32 = 48.0;
const PAD: f32 = 30.0;
const ICON: f32 = 34.0;
const TEXT_W: f32 = 112.0;
const TEXT_PX: f32 = 28.0;
const FONTS: &[&str] = &[
"/usr/share/fonts/truetype/noto/NotoSans-SemiBold.ttf",
"/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf",
"/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
];
#[derive(Clone, Copy, PartialEq)]
struct Key {
percent: u32,
muted: bool,
out: (i32, i32),
}
#[derive(Default)]
pub struct VolumeOsd {
font: Option<FontVec>,
font_tried: bool,
cached: Option<(Key, MemoryRenderBuffer, (i32, i32))>,
}
impl VolumeOsd {
/// The OSD image for this level and output size, and where it goes
/// (top-left corner, physical px).
pub fn image(&mut self, level: f32, muted: bool, out: (i32, i32)) -> (&MemoryRenderBuffer, (i32, i32)) {
let key = Key { percent: (level.clamp(0.0, 1.0) * 100.0).round() as u32, muted, out };
if self.cached.as_ref().is_none_or(|(k, _, _)| *k != key) {
if !self.font_tried {
self.font_tried = true;
self.font = FONTS.iter().find_map(|p| std::fs::read(p).ok().and_then(|d| FontVec::try_from_vec(d).ok()));
if self.font.is_none() {
tracing::warn!("volume OSD: no font found, showing the bar only");
}
}
let k = (out.1 as f32 / 1080.0).max(0.5);
let (w, h) = ((W * k).round() as usize, (H * k).round() as usize);
let px = draw(w, h, k, key.percent, muted, self.font.as_ref());
let buf = MemoryRenderBuffer::from_slice(&px, Fourcc::Argb8888, (w as i32, h as i32), 1, Transform::Normal, None);
let at = ((out.0 - w as i32) / 2, (TOP * k).round() as i32);
self.cached = Some((key, buf, at));
}
let (_, buf, at) = self.cached.as_ref().unwrap();
(buf, *at)
}
}
/// Premultiplied RGBA, f32.
struct Canvas {
w: usize,
h: usize,
px: Vec<[f32; 4]>,
}
impl Canvas {
fn over(&mut self, x: usize, y: usize, rgb: [f32; 3], a: f32) {
if x >= self.w || y >= self.h || a <= 0.0 {
return;
}
let d = &mut self.px[y * self.w + x];
let a = a.min(1.0);
for i in 0..3 {
d[i] = rgb[i] * a + d[i] * (1.0 - a);
}
d[3] = a + d[3] * (1.0 - a);
}
/// A shape given by its signed distance (px, negative inside), drawn
/// with a one-pixel anti-aliased edge, within the box x0..x1, y0..y1.
fn shape(&mut self, (x0, y0, x1, y1): (f32, f32, f32, f32), rgb: [f32; 3], a: f32, sd: impl Fn(f32, f32) -> f32) {
let (xa, ya) = (x0.floor().max(0.0) as usize, y0.floor().max(0.0) as usize);
let (xb, yb) = ((x1.ceil() as usize).min(self.w), (y1.ceil() as usize).min(self.h));
for y in ya..yb {
for x in xa..xb {
let cov = (0.5 - sd(x as f32 + 0.5, y as f32 + 0.5)).clamp(0.0, 1.0);
self.over(x, y, rgb, a * cov);
}
}
}
/// BGRA bytes, premultiplied (DRM ARGB8888, little endian).
fn bytes(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(self.px.len() * 4);
for p in &self.px {
let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
out.extend_from_slice(&[c(p[2]), c(p[1]), c(p[0]), c(p[3])]);
}
out
}
}
fn round_rect(px: f32, py: f32, (x, y, w, h): (f32, f32, f32, f32), r: f32) -> f32 {
let (hw, hh) = (w * 0.5, h * 0.5);
let (qx, qy) = ((px - x - hw).abs() - hw + r, (py - y - hh).abs() - hh + r);
qx.max(qy).min(0.0) + (qx.max(0.0).hypot(qy.max(0.0))) - r
}
/// Distance to the segment a-b, minus half the stroke width.
fn capsule(px: f32, py: f32, (ax, ay): (f32, f32), (bx, by): (f32, f32), half: f32) -> f32 {
let (pax, pay, bax, bay) = (px - ax, py - ay, bx - ax, by - ay);
let t = ((pax * bax + pay * bay) / (bax * bax + bay * bay)).clamp(0.0, 1.0);
(pax - bax * t).hypot(pay - bay * t) - half
}
const WHITE: [f32; 3] = [1.0, 1.0, 1.0];
fn draw(w: usize, h: usize, k: f32, percent: u32, muted: bool, font: Option<&FontVec>) -> Vec<u8> {
let mut c = Canvas { w, h, px: vec![[0.0; 4]; w * h] };
let (wf, hf) = (w as f32, h as f32);
let all = (0.0, 0.0, wf, hf);
let pill = (0.5, 0.5, wf - 1.0, hf - 1.0);
let r = hf * 0.5 - 0.5;
// Pill: dark, nearly opaque, with a faint light rim.
c.shape(all, [0.09, 0.09, 0.11], 0.92, |x, y| round_rect(x, y, pill, r));
c.shape(all, WHITE, 0.14, |x, y| {
let d = round_rect(x, y, pill, r);
(d + 0.75 * k).abs() - 0.75 * k
});
// Speaker: a small box and a cone, then sound waves (or a cross when muted).
let s = ICON * k;
let (ix, iy) = (PAD * k, (hf - s) * 0.5);
let cy = iy + s * 0.5;
let ink = if muted { 0.55 } else { 1.0 };
c.shape((ix, iy, ix + s * 0.3, iy + s), WHITE, ink, |x, y| round_rect(x, y, (ix, cy - s * 0.17, s * 0.24, s * 0.34), 1.5 * k));
c.shape((ix, iy, ix + s * 0.62, iy + s), WHITE, ink, |x, y| {
// Cone: from the box (x = 0.20 s, half height 0.17 s) to x = 0.56 s (half height 0.42 s).
let (x0, x1, h0, h1) = (ix + s * 0.20, ix + s * 0.56, s * 0.17, s * 0.42);
let t = ((x - x0) / (x1 - x0)).clamp(0.0, 1.0);
let half = h0 + (h1 - h0) * t;
let dy = (y - cy).abs() - half;
let dx = (x0 - x).max(x - x1);
// Slanted edge: scale the vertical distance by the edge's slope.
let slope = ((h1 - h0) / (x1 - x0)).hypot(1.0);
dx.max(dy / slope)
});
let ax = ix + s * 0.56;
if muted {
let (x0, x1, half) = (ax + s * 0.14, ax + s * 0.46, s * 0.16);
let st = 1.3 * k;
c.shape((ax, iy, ix + s * 1.2, iy + s), WHITE, 0.85, |x, y| {
capsule(x, y, (x0, cy - half), (x1, cy + half), st).min(capsule(x, y, (x0, cy + half), (x1, cy - half), st))
});
} else {
let waves = if percent == 0 { 0 } else if percent < 34 { 1 } else if percent < 67 { 2 } else { 3 };
for i in 0..3 {
let rad = s * (0.18 + 0.17 * i as f32);
let a = if i < waves { 1.0 } else { 0.25 };
let st = 1.4 * k;
c.shape((ax, iy - 2.0, ix + s * 1.3, iy + s + 2.0), WHITE, a, |x, y| {
let (dx, dy) = (x - (ax - s * 0.06), y - cy);
let ring = (dx.hypot(dy) - rad).abs() - st;
// Only the right-hand 90 degrees of the circle.
let cone = dy.abs() - dx * 0.9;
ring.max(cone)
});
}
}
// Level bar.
let bx0 = (PAD + ICON + 24.0) * k;
let bx1 = wf - (PAD + TEXT_W + 16.0) * k;
let bh = 8.0 * k;
let bar = (bx0, (hf - bh) * 0.5, bx1 - bx0, bh);
c.shape(all, WHITE, 0.22, |x, y| round_rect(x, y, bar, bh * 0.5));
let level = percent as f32 / 100.0;
if level > 0.0 {
let fill = (bar.0, bar.1, (bar.2 * level).max(bh), bh);
c.shape(all, WHITE, if muted { 0.45 } else { 1.0 }, |x, y| round_rect(x, y, fill, bh * 0.5));
}
// The number, right-aligned.
if let Some(font) = font {
let text = if muted { "Némítva".to_string() } else { percent.to_string() };
let px = if muted { TEXT_PX * 0.86 } else { TEXT_PX } * k;
let sf = font.as_scaled(PxScale::from(px));
let width: f32 = text.chars().map(|ch| sf.h_advance(font.glyph_id(ch))).sum();
let mut x = wf - PAD * k - width;
let baseline = hf * 0.5 + (sf.ascent() + sf.descent()) * 0.5;
for ch in text.chars() {
let id = font.glyph_id(ch);
let glyph = id.with_scale_and_position(px, ab_glyph::point(x, baseline));
if let Some(outline) = font.outline_glyph(glyph) {
let b = outline.px_bounds();
outline.draw(|gx, gy, cov| {
let (px_, py_) = (b.min.x as i32 + gx as i32, b.min.y as i32 + gy as i32);
if px_ >= 0 && py_ >= 0 {
c.over(px_ as usize, py_ as usize, WHITE, cov * if muted { 0.8 } else { 1.0 });
}
});
}
x += sf.h_advance(id);
}
}
c.bytes()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn draws_a_pill() {
let (w, h) = (460, 76);
let px = draw(w, h, 1.0, 45, false, None);
assert_eq!(px.len(), w * h * 4);
// Corners are transparent (rounded), the middle of the pill is not.
assert_eq!(px[3], 0);
let mid = (h / 2 * w + w / 2) * 4;
assert!(px[mid + 3] > 200);
}
}

View File

@@ -0,0 +1,323 @@
//! Remote viewing for development: wlr-screencopy (v3) and the virtual
//! keyboard, so `wayvnc` can show the TV and send keys (README, "Távoli
//! képernyő (VNC)").
//!
//! Both are off unless the session sets `SMARTFOX_REMOTE_VIEW=1`, and even
//! then only trusted programs get them (`trusted`): sandboxed store apps
//! must not read the screen or type into other apps.
//!
//! A copy request waits for the next frame the backend renders and gets the
//! same render elements, drawn into the client's buffer (dmabuf: on the GPU,
//! which wayvnc's H.264 encoder needs; shm: read back).
use std::os::unix::fs::MetadataExt;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use smithay::backend::allocator::{Buffer, Fourcc};
use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::renderer::gles::{GlesRenderbuffer, GlesRenderer};
use smithay::backend::renderer::utils::draw_render_elements;
use smithay::backend::renderer::{Bind, ExportMem, Frame, Offscreen, Renderer, TextureMapping};
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::{
zwlr_screencopy_frame_v1::{self, ZwlrScreencopyFrameV1},
zwlr_screencopy_manager_v1::{self, ZwlrScreencopyManagerV1},
};
use smithay::reexports::wayland_server::backend::GlobalId;
use smithay::reexports::wayland_server::protocol::{wl_buffer::WlBuffer, wl_shm};
use smithay::reexports::wayland_server::{Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource};
use smithay::utils::{Physical, Rectangle, Size, Transform};
use smithay::wayland::dmabuf::get_dmabuf;
use smithay::wayland::shm::with_buffer_contents_mut;
use crate::state::{SfElement, State};
const VERSION: u32 = 3;
/// Programs that may capture the screen and type: the VNC server, and grim
/// for screenshots.
const TRUSTED: &[&str] = &["wayvnc", "grim"];
/// Whether remote viewing is switched on for this session.
pub fn enabled() -> bool {
std::env::var("SMARTFOX_REMOTE_VIEW").is_ok_and(|v| v == "1")
}
/// Whether a newly connected client may capture and type: one of
/// `TRUSTED`, running as our user, and outside any sandbox (bubblewrap gives
/// every store app its own mount namespace). Decided from the socket before
/// the client is inserted, and kept in its `ClientState`: asking the display
/// for credentials from inside a dispatch (can_view, filters) deadlocks.
pub fn trusted_peer(stream: &std::os::unix::net::UnixStream) -> bool {
use smithay::reexports::rustix;
let Ok(cred) = rustix::net::sockopt::socket_peercred(stream) else { return false };
let pid = rustix::process::Pid::as_raw(Some(cred.pid));
let proc = format!("/proc/{pid}");
let same_user = std::fs::metadata("/proc/self").ok().map(|m| m.uid()) == Some(cred.uid.as_raw());
let ns = |p: &str| std::fs::read_link(format!("{p}/ns/mnt")).ok();
let same_ns = ns("/proc/self").is_some() && ns("/proc/self") == ns(&proc);
let exe = std::fs::read_link(format!("{proc}/exe")).ok();
let name = exe.as_ref().and_then(|e| e.file_name()).and_then(|n| n.to_str()).unwrap_or("").to_string();
let ok = same_user && same_ns && TRUSTED.contains(&name.as_str());
if ok {
tracing::info!("remote view: pid {pid} ({name}) may capture and type");
}
ok
}
/// What `trusted_peer` said when the client connected.
pub fn trusted(client: &Client) -> bool {
client.get_data::<crate::state::ClientState>().is_some_and(|d| d.remote_view)
}
pub struct ScreencopyState {
_global: GlobalId,
}
impl ScreencopyState {
pub fn new(dh: &DisplayHandle) -> Self {
let global = dh.create_global::<State, ZwlrScreencopyManagerV1, _>(VERSION, ());
ScreencopyState { _global: global }
}
}
/// A copy waiting for the next rendered frame.
pub struct Pending {
frame: ZwlrScreencopyFrameV1,
buffer: WlBuffer,
with_damage: bool,
}
/// What a frame object captures.
pub struct FrameData {
size: Size<i32, Physical>,
/// The output isn't there (or a region was asked for): every copy fails.
unusable: bool,
used: Mutex<bool>,
}
impl GlobalDispatch<ZwlrScreencopyManagerV1, ()> for State {
fn bind(_: &mut State, _: &DisplayHandle, _: &Client, resource: New<ZwlrScreencopyManagerV1>, _: &(), init: &mut DataInit<'_, State>) {
init.init(resource, ());
}
fn can_view(client: Client, _: &()) -> bool {
trusted(&client)
}
}
impl Dispatch<ZwlrScreencopyManagerV1, ()> for State {
fn request(
state: &mut State,
_: &Client,
_: &ZwlrScreencopyManagerV1,
request: zwlr_screencopy_manager_v1::Request,
_: &(),
_: &DisplayHandle,
init: &mut DataInit<'_, State>,
) {
let (frame, region) = match request {
zwlr_screencopy_manager_v1::Request::CaptureOutput { frame, .. } => (frame, false),
// Regions aren't supported (wayvnc and grim take the whole output).
zwlr_screencopy_manager_v1::Request::CaptureOutputRegion { frame, .. } => (frame, true),
zwlr_screencopy_manager_v1::Request::Destroy => return,
_ => return,
};
let size = state.output_size();
let unusable = region || state.output.is_none();
let frame = init.init(frame, FrameData { size, unusable, used: Mutex::new(false) });
if unusable {
frame.failed();
return;
}
let (w, h) = (size.w as u32, size.h as u32);
frame.buffer(wl_shm::Format::Xrgb8888, w, h, w * 4);
if frame.version() >= 3 {
frame.linux_dmabuf(Fourcc::Xrgb8888 as u32, w, h);
frame.buffer_done();
}
}
}
impl Dispatch<ZwlrScreencopyFrameV1, FrameData> for State {
fn request(
state: &mut State,
_: &Client,
frame: &ZwlrScreencopyFrameV1,
request: zwlr_screencopy_frame_v1::Request,
data: &FrameData,
_: &DisplayHandle,
_: &mut DataInit<'_, State>,
) {
let (buffer, with_damage) = match request {
zwlr_screencopy_frame_v1::Request::Copy { buffer } => (buffer, false),
zwlr_screencopy_frame_v1::Request::CopyWithDamage { buffer } => (buffer, true),
_ => return,
};
{
let mut used = data.used.lock().unwrap();
if *used {
frame.post_error(zwlr_screencopy_frame_v1::Error::AlreadyUsed, "frame already used");
return;
}
*used = true;
}
if data.unusable || data.size != state.output_size() {
frame.failed();
return;
}
state.screencopies.push(Pending { frame: frame.clone(), buffer, with_damage });
}
}
/// Answers the copies waiting for a frame, with the elements the backend
/// just rendered. `damaged`: the frame changed (copy-with-damage waits for
/// that; a plain copy is answered right away).
pub fn fulfil(state: &mut State, renderer: &mut GlesRenderer, elements: &[SfElement], damaged: bool) {
let size = state.output_size();
let pending = std::mem::take(&mut state.screencopies);
let (ready, waiting): (Vec<_>, Vec<_>) = pending.into_iter().partition(|p| damaged || !p.with_damage);
state.screencopies = waiting.into_iter().filter(|p| p.frame.is_alive()).collect();
if ready.is_empty() {
return;
}
let time: Duration = state.clock.now().into();
for p in ready {
if !p.frame.is_alive() {
continue;
}
let result = match get_dmabuf(&p.buffer) {
Ok(dmabuf) => draw_dmabuf(renderer, &mut dmabuf.clone(), size, elements),
Err(_) => draw_shm(renderer, &p.buffer, size, elements),
};
match result {
Ok(()) => {
p.frame.flags(zwlr_screencopy_frame_v1::Flags::empty());
if p.with_damage {
p.frame.damage(0, 0, size.w as u32, size.h as u32);
}
let secs = time.as_secs();
p.frame.ready((secs >> 32) as u32, secs as u32, time.subsec_nanos());
}
Err(e) => {
tracing::warn!("screencopy: {e:#}");
p.frame.failed();
}
}
}
}
fn draw(renderer: &mut GlesRenderer, fb: &mut <GlesRenderer as smithay::backend::renderer::RendererSuper>::Framebuffer<'_>, size: Size<i32, Physical>, elements: &[SfElement]) -> Result<()> {
let all = [Rectangle::from_size(size)];
let mut frame = renderer.render(fb, size, Transform::Normal).map_err(|e| anyhow!("render: {e:?}"))?;
frame.clear([0.0, 0.0, 0.0, 1.0].into(), &all).map_err(|e| anyhow!("clear: {e:?}"))?;
draw_render_elements::<GlesRenderer, _, SfElement>(&mut frame, 1.0, elements, &all).map_err(|e| anyhow!("draw: {e:?}"))?;
let sync = frame.finish().map_err(|e| anyhow!("finish: {e:?}"))?;
renderer.wait(&sync).map_err(|e| anyhow!("wait: {e:?}"))?;
Ok(())
}
/// Straight into the client's dmabuf, on the GPU.
fn draw_dmabuf(renderer: &mut GlesRenderer, dmabuf: &mut Dmabuf, size: Size<i32, Physical>, elements: &[SfElement]) -> Result<()> {
if (dmabuf.width() as i32, dmabuf.height() as i32) != (size.w, size.h) {
bail!("dmabuf is {}x{}, the output {}x{}", dmabuf.width(), dmabuf.height(), size.w, size.h);
}
let mut fb = renderer.bind(dmabuf).map_err(|e| anyhow!("binding the dmabuf: {e:?}"))?;
draw(renderer, &mut fb, size, elements)
}
/// Into an offscreen buffer, read back into the client's shm buffer.
fn draw_shm(renderer: &mut GlesRenderer, buffer: &WlBuffer, size: Size<i32, Physical>, elements: &[SfElement]) -> Result<()> {
let buf_size = Size::from((size.w, size.h));
let mut rb: GlesRenderbuffer = renderer.create_buffer(Fourcc::Abgr8888, buf_size).map_err(|e| anyhow!("offscreen buffer: {e:?}"))?;
let mut fb = renderer.bind(&mut rb).map_err(|e| anyhow!("binding: {e:?}"))?;
draw(renderer, &mut fb, size, elements)?;
let mapping = renderer
.copy_framebuffer(&fb, Rectangle::from_size(buf_size), Fourcc::Xrgb8888)
.map_err(|e| anyhow!("read back: {e:?}"))?;
let flipped = mapping.flipped();
let pixels = renderer.map_texture(&mapping).map_err(|e| anyhow!("map: {e:?}"))?;
let row = size.w as usize * 4;
let rows = size.h as usize;
anyhow::ensure!(pixels.len() >= row * rows, "short read back");
with_buffer_contents_mut(buffer, |ptr, len, data| -> Result<()> {
if !matches!(data.format, wl_shm::Format::Xrgb8888 | wl_shm::Format::Argb8888) || (data.width, data.height) != (size.w, size.h) {
bail!("unexpected shm buffer {}x{} {:?}", data.width, data.height, data.format);
}
let stride = data.stride as usize;
let offset = data.offset as usize;
anyhow::ensure!(stride >= row && offset + stride * (rows - 1) + row <= len, "shm buffer too small");
// SAFETY: bounds checked above; the pool stays mapped during the call.
let dst = unsafe { std::slice::from_raw_parts_mut(ptr.add(offset), len - offset) };
for y in 0..rows {
// GL reads rows bottom-up unless the mapping says it is already flipped.
let src_y = if flipped { y } else { rows - 1 - y };
dst[y * stride..y * stride + row].copy_from_slice(&pixels[src_y * row..src_y * row + row]);
}
Ok(())
})
.context("shm buffer")?
}
// ---- virtual pointer ------------------------------------------------------
// wayvnc won't start input without wlr-virtual-pointer. The TV has no
// pointer, so the device exists and its events are dropped; keys go through
// the virtual keyboard.
use smithay::reexports::wayland_protocols_wlr::virtual_pointer::v1::server::{
zwlr_virtual_pointer_manager_v1::{self, ZwlrVirtualPointerManagerV1},
zwlr_virtual_pointer_v1::{self, ZwlrVirtualPointerV1},
};
pub struct VirtualPointerState {
_global: GlobalId,
}
impl VirtualPointerState {
pub fn new(dh: &DisplayHandle) -> Self {
VirtualPointerState { _global: dh.create_global::<State, ZwlrVirtualPointerManagerV1, _>(2, ()) }
}
}
impl GlobalDispatch<ZwlrVirtualPointerManagerV1, ()> for State {
fn bind(_: &mut State, _: &DisplayHandle, _: &Client, resource: New<ZwlrVirtualPointerManagerV1>, _: &(), init: &mut DataInit<'_, State>) {
init.init(resource, ());
}
fn can_view(client: Client, _: &()) -> bool {
trusted(&client)
}
}
impl Dispatch<ZwlrVirtualPointerManagerV1, ()> for State {
fn request(
_: &mut State,
_: &Client,
_: &ZwlrVirtualPointerManagerV1,
request: zwlr_virtual_pointer_manager_v1::Request,
_: &(),
_: &DisplayHandle,
init: &mut DataInit<'_, State>,
) {
match request {
zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointer { id, .. }
| zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointerWithOutput { id, .. } => {
init.init(id, ());
}
_ => {}
}
}
}
impl Dispatch<ZwlrVirtualPointerV1, ()> for State {
fn request(
_: &mut State,
_: &Client,
_: &ZwlrVirtualPointerV1,
_: zwlr_virtual_pointer_v1::Request,
_: &(),
_: &DisplayHandle,
_: &mut DataInit<'_, State>,
) {
}
}

View File

@@ -12,7 +12,7 @@ use std::time::{Duration, Instant};
use smithay::backend::input::{Event, InputBackend, InputEvent, KeyState, KeyboardKeyEvent};
use smithay::backend::renderer::element::Kind;
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement;
use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
use smithay::backend::renderer::element::utils::RescaleRenderElement;
use smithay::backend::renderer::element::AsRenderElements;
@@ -56,10 +56,11 @@ use smithay::wayland::shell::xdg::{
use smithay::wayland::shm::{ShmHandler, ShmState};
use smithay::wayland::socket::ListeningSocketSource;
use smithay::wayland::viewporter::ViewporterState;
use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;
use smithay::{
delegate_compositor, delegate_data_device, delegate_dmabuf, delegate_output, delegate_pointer_constraints,
delegate_presentation, delegate_relative_pointer, delegate_seat, delegate_shm, delegate_viewporter,
delegate_xdg_decoration, delegate_xdg_shell,
delegate_virtual_keyboard_manager, delegate_xdg_decoration, delegate_xdg_shell,
};
use crate::output_mgmt::{OutputMgmtState, PendingConfig};
@@ -84,12 +85,16 @@ const KEY_MUTE: u32 = 113 + 8;
const KEY_VOLUMEDOWN: u32 = 114 + 8;
const KEY_VOLUMEUP: u32 = 115 + 8;
const KEY_HOMEPAGE: u32 = 172 + 8;
const KEY_SPACE: u32 = 57 + 8;
/// Play/pause keys: the remote's (KEY_PLAYPAUSE), Bluetooth speakers and
/// HDMI-CEC (play, pause, the CD variants).
const MEDIA_PLAY_KEYS: [u32; 5] = [164 + 8, 207 + 8, 119 + 8, 200 + 8, 201 + 8];
smithay::backend::renderer::element::render_elements! {
pub SfElement<=GlesRenderer>;
Surface=WaylandSurfaceRenderElement<GlesRenderer>,
Scaled=RescaleRenderElement<WaylandSurfaceRenderElement<GlesRenderer>>,
Solid=SolidColorRenderElement,
Memory=MemoryRenderBufferRenderElement<GlesRenderer>,
}
/// The event loop data: protocol state plus the display backend.
@@ -196,6 +201,11 @@ pub struct State {
pub clock: Clock<Monotonic>,
pub output_mgmt: OutputMgmtState,
pub pending_configs: Vec<PendingConfig>,
/// Remote viewing (SMARTFOX_REMOTE_VIEW=1): screencopy and virtual
/// keyboard for wayvnc; screen copies waiting for the next frame.
#[allow(dead_code)]
remote_view: Option<(crate::screencopy::ScreencopyState, VirtualKeyboardManagerState, crate::screencopy::VirtualPointerState)>,
pub screencopies: Vec<crate::screencopy::Pending>,
pub popups: PopupManager,
pub seat: Seat<State>,
pub space: Space<Window>,
@@ -216,9 +226,7 @@ pub struct State {
pub visible: Option<Window>,
pub transition: Option<Transition>,
pub osd: Option<Osd>,
osd_bg: SolidColorBuffer,
osd_track: SolidColorBuffer,
osd_fill: SolidColorBuffer,
osd_art: crate::osd::VolumeOsd,
/// False while the screen is turned off (wlr-randr --off / standby).
pub screen_on: bool,
}
@@ -226,6 +234,8 @@ pub struct State {
#[derive(Default)]
pub struct ClientState {
pub compositor_state: CompositorClientState,
/// May use screencopy and the virtual keyboard (crate::screencopy).
pub remote_view: bool,
}
impl ClientData for ClientState {
@@ -312,6 +322,14 @@ impl State {
let relative_pointer_state = RelativePointerManagerState::new::<Self>(&dh);
let pointer_constraints_state = PointerConstraintsState::new::<Self>(&dh);
let output_mgmt = OutputMgmtState::new(&dh);
let remote_view = crate::screencopy::enabled().then(|| {
tracing::info!("remote view on: screencopy and virtual keyboard for wayvnc");
(
crate::screencopy::ScreencopyState::new(&dh),
VirtualKeyboardManagerState::new::<Self, _>(&dh, crate::screencopy::trusted),
crate::screencopy::VirtualPointerState::new(&dh),
)
});
let mut seat: Seat<Self> = seat_state.new_wl_seat(&dh, "seat0");
// Same repeat as cage/wlroots: 600 ms delay, 25 per second.
@@ -321,12 +339,14 @@ impl State {
// relative pointer and pointer constraints work on a wl_pointer.
seat.add_pointer();
let remote_view_on = remote_view.is_some();
let socket = ListeningSocketSource::new_auto()?;
let socket_name = socket.socket_name().to_os_string();
let handle = event_loop.handle();
handle
.insert_source(socket, |stream, _, app: &mut App| {
if let Err(e) = app.state.dh.insert_client(stream, Arc::new(ClientState::default())) {
.insert_source(socket, move |stream, _, app: &mut App| {
let data = ClientState { remote_view: remote_view_on && crate::screencopy::trusted_peer(&stream), ..Default::default() };
if let Err(e) = app.state.dh.insert_client(stream, Arc::new(data)) {
tracing::warn!("client: {e}");
}
})
@@ -363,6 +383,8 @@ impl State {
clock,
output_mgmt,
pending_configs: vec![],
remote_view,
screencopies: vec![],
popups: PopupManager::default(),
seat,
space: Space::default(),
@@ -378,9 +400,7 @@ impl State {
visible: None,
transition: None,
osd: None,
osd_bg: SolidColorBuffer::default(),
osd_track: SolidColorBuffer::default(),
osd_fill: SolidColorBuffer::default(),
osd_art: Default::default(),
screen_on: true,
})
}
@@ -582,6 +602,7 @@ impl State {
let time = Event::time_msec(&event);
let pressed = event.state() == KeyState::Pressed;
let Some(kb) = self.seat.get_keyboard() else { return };
let keycode = self.remap_media_key(&kb, event.key_code());
enum Action {
Home,
Volume(i32),
@@ -591,7 +612,7 @@ impl State {
/// Release or repeat of a key we handle: keep it from the app.
Swallow,
}
let action = kb.input::<Action, _>(self, event.key_code(), event.state(), serial, time, |_, mods, key| {
let action = kb.input::<Action, _>(self, keycode, event.state(), serial, time, |_, mods, key| {
let code = key.raw_code().raw();
let sym = key.modified_sym().raw();
let hit = match code {
@@ -631,6 +652,24 @@ impl State {
}
}
/// Play/pause for apps that can't see media keys. Slint (the Fennec SDK's
/// UI toolkit) has no media keys, so native apps get play/pause as
/// space, which they treat as play/pause. The web runtime (Chromium)
/// handles media keys itself and gets them as they are.
fn remap_media_key(&self, kb: &smithay::input::keyboard::KeyboardHandle<State>, code: smithay::input::keyboard::Keycode) -> smithay::input::keyboard::Keycode {
if !MEDIA_PLAY_KEYS.contains(&code.raw()) {
return code;
}
let browser = kb
.current_focus()
.and_then(|s| s.client())
.and_then(|c| c.get_credentials(&self.dh).ok())
.and_then(|cred| std::fs::read_link(format!("/proc/{}/exe", cred.pid)).ok())
.and_then(|exe| exe.file_name().map(|n| n.to_string_lossy().to_lowercase()))
.is_some_and(|name| name.contains("chrom"));
if browser { code } else { KEY_SPACE.into() }
}
/// Volume up/down by `delta` percent, or toggle mute (`None`), then show the OSD.
fn change_volume(&mut self, delta: Option<i32>) {
let (tx, rx) = smithay::reexports::calloop::channel::channel::<(f32, bool)>();
@@ -674,24 +713,16 @@ impl State {
let size = self.output_size();
let now = Instant::now();
// Volume OSD: a pill near the bottom with a level bar.
// Volume OSD (osd.rs): a pill at the top with icon, bar and number.
if let Some(osd) = &self.osd {
if now < osd.until {
let fade = ((osd.until - now).as_secs_f32() / 0.3).min(1.0);
let (w, h) = (size.w as f32, size.h as f32);
let bar_w = (w * 0.26) as i32;
let bar_h = (h * 0.010).max(8.0) as i32;
let pad = (h * 0.022) as i32;
let x = (size.w - bar_w) / 2;
let y = (h * 0.86) as i32;
let fill_w = ((bar_w as f32) * osd.level.clamp(0.0, 1.0)) as i32;
let fill = if osd.muted { [1.0, 0.42, 0.42, 0.95] } else { [1.0, 1.0, 1.0, 0.95] };
self.osd_fill.update((fill_w.max(1), bar_h), fill);
self.osd_track.update((bar_w, bar_h), [1.0, 1.0, 1.0, 0.22]);
self.osd_bg.update((bar_w + 2 * pad, bar_h + 2 * pad), [0.04, 0.05, 0.08, 0.72]);
out.push(SolidColorRenderElement::from_buffer(&self.osd_fill, (x, y), 1.0, fade, Kind::Unspecified).into());
out.push(SolidColorRenderElement::from_buffer(&self.osd_track, (x, y), 1.0, fade, Kind::Unspecified).into());
out.push(SolidColorRenderElement::from_buffer(&self.osd_bg, (x - pad, y - pad), 1.0, fade, Kind::Unspecified).into());
let (level, muted) = (osd.level, osd.muted);
let (buf, at) = self.osd_art.image(level, muted, (size.w, size.h));
match MemoryRenderBufferRenderElement::from_buffer(renderer, (at.0 as f64, at.1 as f64), buf, Some(fade), None, None, Kind::Unspecified) {
Ok(el) => out.push(el.into()),
Err(e) => tracing::warn!("volume OSD: {e:?}"),
}
} else {
self.osd = None;
}
@@ -1015,3 +1046,4 @@ delegate_viewporter!(State);
delegate_presentation!(State);
delegate_relative_pointer!(State);
delegate_pointer_constraints!(State);
delegate_virtual_keyboard_manager!(State);

View File

@@ -65,14 +65,38 @@ pub struct UdevData {
retry_scheduled: bool,
}
/// The GPU that drives the screen. On a PC that's the primary GPU. On ARM
/// boards the display and the 3D engine are separate DRM devices (Raspberry
/// Pi: vc4 has the HDMI ports, v3d only renders), so a card without display
/// connectors is skipped; mesa renders on v3d through the vc4 device.
fn pick_gpu(seat: &str) -> Result<std::path::PathBuf> {
let primary = primary_gpu(seat)?;
let all = all_gpus(seat).unwrap_or_default();
let candidates: Vec<_> = primary.iter().cloned().chain(all.into_iter().filter(|p| Some(p) != primary.as_ref())).collect();
candidates
.iter()
.find(|p| has_connectors(p))
.or(candidates.first())
.cloned()
.context("no GPU found")
}
/// Whether a DRM card (/dev/dri/cardN) has display connectors, from sysfs
/// (/sys/class/drm/cardN-HDMI-A-1 ...).
fn has_connectors(path: &std::path::Path) -> bool {
let Some(card) = path.file_name().and_then(|n| n.to_str()) else { return false };
let prefix = format!("{card}-");
std::fs::read_dir("/sys/class/drm")
.map(|dir| dir.flatten().any(|e| e.file_name().to_str().is_some_and(|n| n.starts_with(&prefix) && !n.contains("Writeback"))))
.unwrap_or(false)
}
pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result<Backend> {
let (session, notifier) = LibSeatSession::new().map_err(|e| anyhow!("libseat session: {e}"))?;
state.session = Some(session.clone());
let seat = session.seat();
let path = primary_gpu(&seat)?
.or_else(|| all_gpus(&seat).ok()?.into_iter().next())
.context("no GPU found")?;
let path = pick_gpu(&seat)?;
tracing::info!("GPU {}", path.display());
let mut session_for_open = session.clone();
let fd = session_for_open
@@ -93,6 +117,8 @@ pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Resu
state.shm_state.update_formats(renderer.shm_formats());
let dmabuf_formats = renderer.dmabuf_formats();
// Clients render on the GPU's render node (Raspberry Pi: v3d). Not the
// display device: mesa would fall back to software rendering on vc4.
let feedback = DmabufFeedbackBuilder::new(render_node.dev_id(), dmabuf_formats.clone())
.build()
.map_err(|e| anyhow!("dmabuf feedback: {e}"))?;
@@ -350,6 +376,9 @@ impl UdevData {
false
}
};
if !state.screencopies.is_empty() {
crate::screencopy::fulfil(state, &mut self.renderer, &elements, rendered);
}
if rendered {
match out.drm_output.queue_frame(state.presentation_feedback()) {
Ok(()) => out.frame_pending = true,

View File

@@ -71,22 +71,24 @@ pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Resu
fn render(app: &mut App) {
let Backend::Winit(w) = &mut app.backend else { return };
let age = w.backend.buffer_age().unwrap_or(0);
let damage = match w.backend.bind() {
let (damage, elements) = match w.backend.bind() {
Ok((renderer, mut fb)) => {
let elements = app.state.elements(renderer);
match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) {
let damage = match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) {
Ok(r) => r.damage.cloned(),
Err(e) => {
tracing::warn!("render: {e:?}");
None
}
}
};
(damage, Some(elements))
}
Err(e) => {
tracing::warn!("bind: {e:?}");
None
(None, None)
}
};
let damaged = damage.is_some();
if let Some(damage) = damage {
let feedback = app.state.presentation_feedback();
match w.backend.submit(Some(&damage)) {
@@ -99,6 +101,10 @@ fn render(app: &mut App) {
Err(e) => tracing::warn!("submit: {e:?}"),
}
}
// After the swap: copying binds other targets.
if let Some(elements) = elements.filter(|_| !app.state.screencopies.is_empty()) {
crate::screencopy::fulfil(&mut app.state, w.backend.renderer(), &elements, damaged);
}
app.state.send_frames();
w.backend.window().request_redraw();
}