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:
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
234
crates/sf-compositor/src/osd.rs
Normal file
234
crates/sf-compositor/src/osd.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
323
crates/sf-compositor/src/screencopy.rs
Normal file
323
crates/sf-compositor/src/screencopy.rs
Normal 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>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sf-core"
|
||||
description = "Fennec OS core daemon: app lifecycle (systemd scopes, freeze/thaw), DIAL, AirPlay/Miracast receivers"
|
||||
description = "Fennec OS core daemon: app lifecycle (systemd scopes, one app at a time), DIAL, AirPlay/Miracast receivers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
//! App lifecycle: start, bring to front, send to the background (freeze),
|
||||
//! close. One app is in the foreground; with sf-compositor the others wait
|
||||
//! frozen in the background, under cage they are closed.
|
||||
//! App lifecycle: start and close. Only one app runs at a time: Home, a
|
||||
//! new app or a cast closes the one on screen.
|
||||
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command as StdCommand;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sf_ipc::launch::{LaunchOptions, command};
|
||||
@@ -15,21 +14,17 @@ use tokio::sync::broadcast;
|
||||
|
||||
use crate::wm;
|
||||
|
||||
/// Frozen apps kept in the background; the oldest beyond this is closed.
|
||||
const MAX_BACKGROUND: usize = 2;
|
||||
/// Below this much available memory the oldest frozen app is closed.
|
||||
const LOW_MEMORY_KB: u64 = 400 * 1024;
|
||||
/// Freeze only after the compositor's switch animation has finished.
|
||||
const FREEZE_DELAY: Duration = Duration::from_millis(600);
|
||||
/// Close only after the compositor's switch animation has finished.
|
||||
const CLOSE_DELAY: Duration = Duration::from_millis(600);
|
||||
|
||||
struct Running {
|
||||
id: String,
|
||||
pid: u32,
|
||||
/// systemd scope (`sf-app-<id>-<n>.scope`), if scopes are used.
|
||||
unit: Option<String>,
|
||||
frozen: bool,
|
||||
last_used: Instant,
|
||||
serial: u64,
|
||||
/// Being closed; it can't be brought back any more.
|
||||
stopping: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -38,8 +33,6 @@ struct State {
|
||||
running: Vec<Running>,
|
||||
foreground: Option<String>,
|
||||
serial: u64,
|
||||
/// While a cast window is up: what to show when it ends (None: launcher).
|
||||
cast_return: Option<Option<String>>,
|
||||
}
|
||||
|
||||
pub struct Core {
|
||||
@@ -80,12 +73,6 @@ async fn systemctl(verb: &str, unit: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mem_available_kb() -> Option<u64> {
|
||||
let text = std::fs::read_to_string("/proc/meminfo").ok()?;
|
||||
let line = text.lines().find(|l| l.starts_with("MemAvailable:"))?;
|
||||
line.split_whitespace().nth(1)?.parse().ok()
|
||||
}
|
||||
|
||||
impl Core {
|
||||
pub fn new(apps_dirs: Vec<PathBuf>, store_dir: Option<PathBuf>, settings_path: PathBuf) -> Result<Self> {
|
||||
let apps = sf_ipc::manifest::load_all(&apps_dirs, store_dir.as_deref())?;
|
||||
@@ -149,61 +136,57 @@ impl Core {
|
||||
if query.is_some() && self.is_running(id) {
|
||||
self.stop_and_wait(id).await;
|
||||
}
|
||||
let switching = wm::available();
|
||||
|
||||
// Already running: thaw and show it.
|
||||
let existing = {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid, r.frozen))
|
||||
};
|
||||
if let Some((unit, pid, frozen)) = existing {
|
||||
if frozen {
|
||||
self.thaw(id, unit.as_deref(), pid).await;
|
||||
}
|
||||
// Still running (brought back before it closed): show it again.
|
||||
let alive = self.state.lock().unwrap().running.iter().any(|r| r.id == id && !r.stopping);
|
||||
if alive {
|
||||
let prev = self.set_foreground(Some(id));
|
||||
self.leave_foreground(prev, switching);
|
||||
self.close_previous(prev);
|
||||
wm::focus(Some(id));
|
||||
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let prev = self.set_foreground(None);
|
||||
self.leave_foreground(prev, switching);
|
||||
if !switching {
|
||||
// Under cage only the newest window shows; don't leave others running.
|
||||
let others: Vec<String> = self.state.lock().unwrap().running.iter().map(|r| r.id.clone()).collect();
|
||||
for other in others {
|
||||
self.stop(&other);
|
||||
}
|
||||
// One app at a time: anything else still running closes now.
|
||||
let others: Vec<String> = {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().map(|r| r.id.clone()).filter(|r| Some(r) != prev.as_ref()).collect()
|
||||
};
|
||||
for other in others {
|
||||
self.stop(&other);
|
||||
}
|
||||
self.close_previous(prev);
|
||||
// Opened again while it was closing: start fresh once it is gone.
|
||||
self.wait_gone(id).await;
|
||||
self.spawn(&app, query.as_deref())?;
|
||||
self.set_foreground(Some(id));
|
||||
wm::focus(Some(id));
|
||||
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
|
||||
self.enforce_background_limit();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_foreground(&self, id: Option<&str>) -> Option<String> {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
if let Some(id) = id {
|
||||
if let Some(r) = st.running.iter_mut().find(|r| r.id == id) {
|
||||
r.last_used = Instant::now();
|
||||
}
|
||||
}
|
||||
let prev = std::mem::replace(&mut st.foreground, id.map(str::to_string));
|
||||
prev.filter(|p| Some(p.as_str()) != id)
|
||||
}
|
||||
|
||||
/// The previous foreground app goes to the background (or is closed
|
||||
/// when the compositor can't keep it there).
|
||||
fn leave_foreground(self: &Arc<Self>, prev: Option<String>, switching: bool) {
|
||||
/// Closes the app that was on screen, once the switch animation is
|
||||
/// over (at once under cage, which has no animation).
|
||||
fn close_previous(self: &Arc<Self>, prev: Option<String>) {
|
||||
let Some(prev) = prev else { return };
|
||||
if switching {
|
||||
self.freeze_later(prev);
|
||||
} else {
|
||||
if !wm::available() {
|
||||
self.stop(&prev);
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(CLOSE_DELAY).await;
|
||||
if core.foreground().as_deref() == Some(prev.as_str()) {
|
||||
return; // brought back in the meantime
|
||||
}
|
||||
core.stop(&prev);
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn(self: &Arc<Self>, app: &AppManifest, query: Option<&str>) -> Result<()> {
|
||||
@@ -251,9 +234,8 @@ impl Core {
|
||||
id: app.id.clone(),
|
||||
pid,
|
||||
unit,
|
||||
frozen: false,
|
||||
last_used: Instant::now(),
|
||||
serial,
|
||||
stopping: false,
|
||||
});
|
||||
let core = self.clone();
|
||||
let id = app.id.clone();
|
||||
@@ -276,11 +258,6 @@ impl Core {
|
||||
if fg {
|
||||
st.foreground = None;
|
||||
}
|
||||
if let Some(Some(ret)) = &st.cast_return {
|
||||
if ret == id {
|
||||
st.cast_return = Some(None);
|
||||
}
|
||||
}
|
||||
fg
|
||||
};
|
||||
if was_foreground {
|
||||
@@ -289,86 +266,34 @@ impl Core {
|
||||
self.emit(CoreEvent::AppStopped { app_id: id.to_string() });
|
||||
}
|
||||
|
||||
/// Home: show the launcher; the foreground app waits frozen (or closes).
|
||||
/// Home: show the launcher; the app on screen closes.
|
||||
pub fn go_home(self: &Arc<Self>) {
|
||||
let prev = self.set_foreground(None);
|
||||
let switching = wm::available();
|
||||
wm::focus(None);
|
||||
self.leave_foreground(prev, switching);
|
||||
self.enforce_background_limit();
|
||||
}
|
||||
|
||||
fn freeze_later(self: &Arc<Self>, id: String) {
|
||||
let core = self.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(FREEZE_DELAY).await;
|
||||
let target = {
|
||||
let st = core.state.lock().unwrap();
|
||||
if st.foreground.as_deref() == Some(id.as_str()) {
|
||||
return; // came back in the meantime
|
||||
}
|
||||
st.running.iter().find(|r| r.id == id && !r.frozen).map(|r| (r.unit.clone(), r.pid))
|
||||
};
|
||||
let Some((unit, pid)) = target else { return };
|
||||
let ok = match &unit {
|
||||
Some(u) => systemctl("freeze", u).await.map_err(|e| log::warn!("{e:#}")).is_ok(),
|
||||
None => kill_group(pid, libc::SIGSTOP),
|
||||
};
|
||||
if ok {
|
||||
// It may have been brought back while we were freezing it.
|
||||
let back = {
|
||||
let mut st = core.state.lock().unwrap();
|
||||
if let Some(r) = st.running.iter_mut().find(|r| r.id == id) {
|
||||
r.frozen = true;
|
||||
}
|
||||
st.foreground.as_deref() == Some(id.as_str())
|
||||
};
|
||||
if back {
|
||||
core.thaw(&id, unit.as_deref(), pid).await;
|
||||
} else {
|
||||
log::info!("{id} frozen");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn thaw(&self, id: &str, unit: Option<&str>, pid: u32) {
|
||||
match unit {
|
||||
Some(u) => {
|
||||
if let Err(e) = systemctl("thaw", u).await {
|
||||
log::warn!("{e:#}");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
kill_group(pid, libc::SIGCONT);
|
||||
}
|
||||
}
|
||||
if let Some(r) = self.state.lock().unwrap().running.iter_mut().find(|r| r.id == id) {
|
||||
r.frozen = false;
|
||||
}
|
||||
log::info!("{id} thawed");
|
||||
self.close_previous(prev);
|
||||
}
|
||||
|
||||
/// Closes the app (asynchronously); false if it wasn't running.
|
||||
pub fn stop(self: &Arc<Self>, id: &str) -> bool {
|
||||
let target = {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid))
|
||||
let mut st = self.state.lock().unwrap();
|
||||
st.running.iter_mut().find(|r| r.id == id).map(|r| {
|
||||
r.stopping = true;
|
||||
(r.unit.clone(), r.pid)
|
||||
})
|
||||
};
|
||||
let Some((unit, pid)) = target else { return false };
|
||||
log::info!("stopping {id}");
|
||||
tokio::spawn(async move {
|
||||
match unit {
|
||||
// Stops every process of the scope, thawing it first.
|
||||
// Stops every process of the scope.
|
||||
Some(u) => {
|
||||
let _ = systemctl("thaw", &u).await;
|
||||
if let Err(e) = systemctl("stop", &u).await {
|
||||
log::warn!("{e:#}");
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
kill_group(pid, libc::SIGCONT);
|
||||
kill_group(pid, libc::SIGTERM);
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
@@ -379,9 +304,13 @@ impl Core {
|
||||
}
|
||||
|
||||
async fn stop_and_wait(self: &Arc<Self>, id: &str) {
|
||||
if !self.stop(id) {
|
||||
return;
|
||||
if self.stop(id) {
|
||||
self.wait_gone(id).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits (up to 6 s) until no instance of the app runs.
|
||||
async fn wait_gone(&self, id: &str) {
|
||||
for _ in 0..60 {
|
||||
if !self.is_running(id) {
|
||||
return;
|
||||
@@ -391,70 +320,20 @@ impl Core {
|
||||
log::warn!("{id} did not stop in time");
|
||||
}
|
||||
|
||||
/// The oldest frozen app, if any.
|
||||
fn oldest_background(&self) -> Option<String> {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running
|
||||
.iter()
|
||||
.filter(|r| st.foreground.as_deref() != Some(r.id.as_str()))
|
||||
.min_by_key(|r| r.last_used)
|
||||
.map(|r| r.id.clone())
|
||||
}
|
||||
|
||||
fn background_count(&self) -> usize {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().filter(|r| st.foreground.as_deref() != Some(r.id.as_str())).count()
|
||||
}
|
||||
|
||||
fn enforce_background_limit(self: &Arc<Self>) {
|
||||
while self.background_count() > MAX_BACKGROUND {
|
||||
let Some(id) = self.oldest_background() else { break };
|
||||
log::info!("too many apps in the background, closing {id}");
|
||||
if !self.stop(&id) {
|
||||
break;
|
||||
}
|
||||
// Don't pick it again while it shuts down.
|
||||
self.state.lock().unwrap().running.retain(|r| r.id != id);
|
||||
self.emit(CoreEvent::AppStopped { app_id: id });
|
||||
}
|
||||
}
|
||||
|
||||
/// A receiver (AirPlay/Miracast) got a connection: its window goes on
|
||||
/// top, the foreground app pauses in the background.
|
||||
/// A receiver (AirPlay/Miracast) got a connection: its window takes the
|
||||
/// screen and the app on screen closes (one app at a time).
|
||||
pub fn cast_connected(self: &Arc<Self>, app_id: &str, device: &str) {
|
||||
let switching = wm::available();
|
||||
let prev = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
if st.cast_return.is_none() {
|
||||
st.cast_return = Some(st.foreground.clone());
|
||||
}
|
||||
if switching { st.foreground.take() } else { None }
|
||||
};
|
||||
if let Some(prev) = prev {
|
||||
self.freeze_later(prev);
|
||||
}
|
||||
let prev = self.set_foreground(None);
|
||||
self.close_previous(prev);
|
||||
wm::focus(Some(app_id));
|
||||
self.emit(CoreEvent::CastConnected { app_id: app_id.to_string(), device: device.to_string() });
|
||||
}
|
||||
|
||||
/// The cast ended: back to what was on screen before.
|
||||
/// The cast ended: back to the launcher, unless an app was opened meanwhile.
|
||||
pub fn cast_ended(self: &Arc<Self>, app_id: &str) {
|
||||
let ret = self.state.lock().unwrap().cast_return.take();
|
||||
self.emit(CoreEvent::CastEnded { app_id: app_id.to_string() });
|
||||
let Some(ret) = ret else { return };
|
||||
if !wm::available() {
|
||||
return;
|
||||
}
|
||||
match ret.filter(|id| self.is_running(id)) {
|
||||
Some(id) => {
|
||||
let core = self.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = core.launch(&id, None, false).await {
|
||||
log::warn!("back to {id}: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
None => wm::focus(None),
|
||||
if wm::available() && self.foreground().is_none() {
|
||||
wm::focus(None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,31 +342,9 @@ impl Core {
|
||||
self.state.lock().unwrap().running.iter().map(|r| (r.unit.clone(), r.pid)).collect();
|
||||
for (unit, pid) in ids {
|
||||
if let Some(u) = unit {
|
||||
let _ = StdCommand::new("systemctl").args(["--user", "thaw", &u]).status();
|
||||
let _ = StdCommand::new("systemctl").args(["--user", "stop", "--no-block", &u]).status();
|
||||
}
|
||||
kill_group(pid, libc::SIGCONT);
|
||||
kill_group(pid, libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the oldest frozen app when memory runs low.
|
||||
pub async fn watch_memory(core: Arc<Core>) {
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(5));
|
||||
loop {
|
||||
tick.tick().await;
|
||||
let Some(avail) = mem_available_kb() else { continue };
|
||||
if avail >= LOW_MEMORY_KB {
|
||||
continue;
|
||||
}
|
||||
let Some(id) = core.oldest_background() else { continue };
|
||||
let name = core.apps().into_iter().find(|a| a.id == id).map(|a| a.name).unwrap_or(id.clone());
|
||||
log::warn!("low memory ({} MB available), closing {id}", avail / 1024);
|
||||
if core.stop(&id) {
|
||||
core.state.lock().unwrap().running.retain(|r| r.id != id);
|
||||
core.emit(CoreEvent::AppStopped { app_id: id });
|
||||
core.emit(CoreEvent::Toast { text: format!("Kevés a memória: {name} bezárva") });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! sf-core: the Fennec OS core daemon.
|
||||
//!
|
||||
//! - Starts apps for the launcher, each in its own systemd user scope.
|
||||
//! Home freezes the foreground app (`systemctl --user freeze`) so it comes
|
||||
//! back instantly; under memory pressure the oldest frozen app is closed.
|
||||
//! Only one app runs at a time: Home, another app or a cast closes it.
|
||||
//! - Runs the DIAL server, so the YouTube app on a phone can cast to the TV.
|
||||
//! - Keeps the AirPlay (UxPlay) and Miracast receivers running and reports
|
||||
//! when a device connects.
|
||||
@@ -101,7 +100,6 @@ fn unix_main() -> anyhow::Result<()> {
|
||||
core.uses_scopes(),
|
||||
wm::available()
|
||||
);
|
||||
tokio::spawn(apps::watch_memory(core.clone()));
|
||||
if !opts.no_services {
|
||||
services::start_all(core.clone());
|
||||
}
|
||||
|
||||
@@ -9,15 +9,14 @@ use serde::{Deserialize, Serialize};
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum LauncherRequest {
|
||||
/// Start the app, or bring it back if it waits in the background.
|
||||
/// Start the app (the one on screen closes).
|
||||
Launch {
|
||||
app_id: String,
|
||||
/// Extra query string for the start URL (DIAL uses this).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
query: Option<String>,
|
||||
},
|
||||
/// Show the launcher. The foreground app is frozen in the background if
|
||||
/// the compositor can switch windows, otherwise it is closed.
|
||||
/// Show the launcher. The app on screen closes.
|
||||
GoHome,
|
||||
/// Close the app.
|
||||
Stop { app_id: String },
|
||||
@@ -28,7 +27,7 @@ pub enum LauncherRequest {
|
||||
pub enum CoreEvent {
|
||||
/// First message on every connection.
|
||||
Hello {
|
||||
/// True if apps are kept (frozen) in the background on Home.
|
||||
/// True if the compositor can switch windows (sf-compositor, not cage).
|
||||
switching: bool,
|
||||
/// The app in the foreground, if any.
|
||||
#[serde(default)]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#![cfg_attr(not(unix), allow(dead_code))]
|
||||
//! Connection to sf-core. On the TV sf-core starts, freezes and closes apps;
|
||||
//! Connection to sf-core. On the TV sf-core starts and closes apps;
|
||||
//! without it (desktop testing) the launcher starts apps itself.
|
||||
|
||||
use sf_ipc::{CoreEvent, LauncherRequest};
|
||||
|
||||
@@ -86,6 +86,11 @@ pub fn setup(ui: &App) -> Snapshot {
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// A snapshot is still to be taken: keep frames coming until then.
|
||||
pub fn pending(&self) -> bool {
|
||||
self.path.is_some()
|
||||
}
|
||||
|
||||
pub fn capture_if_due(&self, ui: &App, r: &GlassRenderer) {
|
||||
if !self.due.get() {
|
||||
return;
|
||||
|
||||
@@ -24,7 +24,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::{Datelike, Local, Timelike};
|
||||
use sf_ui::render::{Frame, GlassRenderer, Panel};
|
||||
use sf_ui::render::{Frame, GlassRenderer, Panel, Quality};
|
||||
use sf_ipc::{AppKind, AppManifest, Settings};
|
||||
use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel};
|
||||
|
||||
@@ -572,8 +572,8 @@ fn main() -> Result<()> {
|
||||
});
|
||||
}
|
||||
|
||||
// Launching. On the TV sf-core starts apps (and keeps them frozen in the
|
||||
// background on Home); without it the launcher starts them itself.
|
||||
// Launching. On the TV sf-core starts apps (and closes them on Home);
|
||||
// without it the launcher starts them itself.
|
||||
let toast_timer = Rc::new(slint::Timer::default());
|
||||
let running: Rc<RefCell<Option<(String, std::process::Child)>>> = Rc::default();
|
||||
let core = {
|
||||
@@ -676,8 +676,8 @@ fn main() -> Result<()> {
|
||||
}
|
||||
});
|
||||
}
|
||||
// Global "home" (remote's TV button): the foreground app goes to the
|
||||
// background (sf-core) or closes, and the reverse morph plays.
|
||||
// Global "home" (remote's TV button): the foreground app closes and
|
||||
// the reverse morph plays.
|
||||
{
|
||||
let weak = ui.as_weak();
|
||||
let core = core.clone();
|
||||
@@ -753,6 +753,10 @@ fn main() -> Result<()> {
|
||||
let backdrop = Rc::new(RefCell::new(Backdrop { palette: palettes.first().copied().unwrap_or([0.0; 9]), last: 0.0 }));
|
||||
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
|
||||
let frames = Rc::new(RefCell::new((Instant::now(), 0u32)));
|
||||
// Glass quality, measured on the GPU for the window size (sf-ui), and
|
||||
// whether the last frame left anything still easing.
|
||||
let quality: Rc<std::cell::Cell<Option<(Quality, (u32, u32))>>> = Rc::default();
|
||||
let easing = Rc::new(std::cell::Cell::new(true));
|
||||
|
||||
let weak = ui.as_weak();
|
||||
ui.window()
|
||||
@@ -777,13 +781,26 @@ fn main() -> Result<()> {
|
||||
let size = ui.window().size();
|
||||
let scale = ui.window().scale_factor();
|
||||
|
||||
let q = match quality.get() {
|
||||
Some((q, at)) if at == (size.width, size.height) => q,
|
||||
_ => {
|
||||
// SAFETY: the rendering notifier runs with the GL context current.
|
||||
let q = unsafe { r.choose_quality(size.width, size.height) };
|
||||
log::info!("glass quality: {}", q.name());
|
||||
quality.set(Some((q, (size.width, size.height))));
|
||||
q
|
||||
}
|
||||
};
|
||||
|
||||
let mut bd = backdrop.borrow_mut();
|
||||
let focus = ui.get_focus_index().max(0) as usize;
|
||||
easing.set(false);
|
||||
if let Some(target) = palettes.get(focus) {
|
||||
let k = 1.0 - (-(time - bd.last).max(0.0) / CROSSFADE).exp();
|
||||
for (c, t) in bd.palette.iter_mut().zip(target) {
|
||||
*c += (t - *c) * k;
|
||||
}
|
||||
easing.set(bd.palette.iter().zip(target).any(|(c, t)| (c - t).abs() > 0.002));
|
||||
}
|
||||
bd.last = time;
|
||||
|
||||
@@ -811,7 +828,7 @@ fn main() -> Result<()> {
|
||||
images: &[],
|
||||
video: None,
|
||||
rects,
|
||||
quality: Default::default(),
|
||||
quality: q,
|
||||
};
|
||||
drop(bd);
|
||||
// SAFETY: called on the UI thread with the Slint GL context current.
|
||||
@@ -825,12 +842,17 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
slint::RenderingState::AfterRendering => {
|
||||
// The backdrop is animated, so keep frames coming (vsync-limited).
|
||||
// The glass backdrop is animated, so keep frames coming
|
||||
// (vsync-limited). Material is still: frames only while the
|
||||
// colours ease; Slint asks for its own animations.
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
if let Some(r) = renderer.borrow().as_ref() {
|
||||
snapshot.capture_if_due(&ui, r);
|
||||
}
|
||||
ui.window().request_redraw();
|
||||
let still = matches!(quality.get(), Some((Quality::Material, _)));
|
||||
if !still || easing.get() || snapshot.pending() {
|
||||
ui.window().request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
slint::RenderingState::RenderingTeardown => {
|
||||
|
||||
@@ -149,8 +149,7 @@ fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result<Option<CatalogApp>> {
|
||||
let app: AppManifest = toml::from_str(&forge::asset_text(agent, manifest_asset)?).context("app.toml")?;
|
||||
app.check_store_rules()?;
|
||||
anyhow::ensure!(crate::registry::is_release(&app.version), "version {} is not a release version (1.2.3)", app.version);
|
||||
let file = format!("{}-{}.tar.zst", app.id, app.version);
|
||||
let package = release.asset(&file).with_context(|| format!("release {} has no {file}", release.tag))?;
|
||||
let package = package_asset(&release, &app)?;
|
||||
Ok(Some(CatalogApp {
|
||||
id: app.id.clone(),
|
||||
name: app.name.clone(),
|
||||
@@ -171,6 +170,24 @@ fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result<Option<CatalogApp>> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// The release's package for this TV (docs/store.md): `<id>-<version>.tar.zst`
|
||||
/// on x86-64, `<id>-<version>-aarch64.tar.zst` on ARM. A web app is the same
|
||||
/// everywhere, so its plain package is fine on any architecture; an exec app's
|
||||
/// plain package is an x86-64 build.
|
||||
fn package_asset<'a>(release: &'a forge::Release, app: &AppManifest) -> Result<&'a forge::Asset> {
|
||||
let plain = format!("{}-{}.tar.zst", app.id, app.version);
|
||||
let native = crate::arch::file_name(&app.id, &app.version);
|
||||
if let Some(a) = release.asset(&native) {
|
||||
return Ok(a);
|
||||
}
|
||||
if !crate::arch::IS_DEFAULT && app.kind == sf_ipc::manifest::AppKind::Web {
|
||||
if let Some(a) = release.asset(&plain) {
|
||||
return Ok(a);
|
||||
}
|
||||
}
|
||||
anyhow::bail!("release {} has no {native}", release.tag)
|
||||
}
|
||||
|
||||
/// Marks what's installed and what's held back, and returns the store
|
||||
/// packages to download (new installs and updates).
|
||||
pub fn plan(store: &Store, wanted: &Wanted, catalog: &mut Catalog) -> BTreeMap<String, (String, StoreDownload)> {
|
||||
|
||||
45
crates/sf-update/src/arch.rs
Normal file
45
crates/sf-update/src/arch.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
//! The CPU architecture of this TV, and how packages built for it are named
|
||||
//! (docs/updates.md, "Architektúrák").
|
||||
//!
|
||||
//! Fennec OS started on x86-64: its package files carry no architecture
|
||||
//! (`sf-shell-1.2.0.tar.zst`). Packages for any other architecture have a
|
||||
//! suffix (`sf-shell-1.2.0-aarch64.tar.zst`).
|
||||
|
||||
/// This build's architecture, as in Rust's `std::env::consts::ARCH`.
|
||||
pub const NAME: &str = std::env::consts::ARCH;
|
||||
|
||||
/// Whether this is the original architecture (unsuffixed package files).
|
||||
pub const IS_DEFAULT: bool = cfg!(target_arch = "x86_64");
|
||||
|
||||
/// `name-version.tar.zst` for this architecture.
|
||||
pub fn file_name(name: &str, version: &str) -> String {
|
||||
if IS_DEFAULT { format!("{name}-{version}.tar.zst") } else { format!("{name}-{version}-{NAME}.tar.zst") }
|
||||
}
|
||||
|
||||
/// Whether a package that says it was built for `arch` (pkg.toml; missing =
|
||||
/// an old package, built for x86-64) runs here.
|
||||
pub fn runs_here(arch: Option<&str>) -> bool {
|
||||
match arch {
|
||||
Some(a) => a == NAME,
|
||||
None => IS_DEFAULT,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names() {
|
||||
if IS_DEFAULT {
|
||||
assert_eq!(file_name("sf-shell", "1.2.0"), "sf-shell-1.2.0.tar.zst");
|
||||
assert!(runs_here(None));
|
||||
assert!(!runs_here(Some("aarch64")));
|
||||
} else {
|
||||
assert_eq!(file_name("sf-shell", "1.2.0"), format!("sf-shell-1.2.0-{NAME}.tar.zst"));
|
||||
assert!(!runs_here(None));
|
||||
assert!(!runs_here(Some("x86_64")));
|
||||
}
|
||||
assert!(runs_here(Some(NAME)));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
//! sf-update status print status.json
|
||||
|
||||
mod appstore;
|
||||
mod arch;
|
||||
mod config;
|
||||
mod forge;
|
||||
mod migrate;
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
//!
|
||||
//! list: GET {server}/api/v1/packages/{owner}?type=generic&q=sf-
|
||||
//! download: GET {server}/api/packages/{owner}/generic/{name}/{version}/{name}-{version}.tar.zst (+ .sig)
|
||||
//! files: GET {server}/api/v1/packages/{owner}/generic/{name}/{version}/files
|
||||
//!
|
||||
//! The shell is native code: on any architecture but x86-64 its file has a
|
||||
//! suffix (`sf-shell-1.2.0-aarch64.tar.zst`, crate::arch). App packages are
|
||||
//! manifests only and are the same everywhere.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Read;
|
||||
@@ -73,10 +78,12 @@ struct PackageVersion {
|
||||
version: String,
|
||||
}
|
||||
|
||||
/// Newest release version of every package on the server.
|
||||
/// Newest release version of every package on the server. A shell version
|
||||
/// without a file for this architecture doesn't count.
|
||||
pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
|
||||
let agent = agent();
|
||||
let mut latest: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut shells: Vec<String> = Vec::new();
|
||||
for page in 1..=100 {
|
||||
let url = format!("{}/api/v1/packages/{}?type=generic&q=sf-&limit=50&page={page}", cfg.server, cfg.owner);
|
||||
let text = get(cfg, &agent, &url)?.body_mut().read_to_string()?;
|
||||
@@ -88,6 +95,10 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
|
||||
if !is_official(&p.name) || !is_release(&p.version) {
|
||||
continue;
|
||||
}
|
||||
if p.name == SHELL && !crate::arch::IS_DEFAULT {
|
||||
shells.push(p.version);
|
||||
continue;
|
||||
}
|
||||
match latest.get(&p.name) {
|
||||
Some(v) if version_cmp(v, &p.version).is_ge() => {}
|
||||
_ => {
|
||||
@@ -96,12 +107,46 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !shells.is_empty() {
|
||||
shells.sort_by(|a, b| version_cmp(b, a));
|
||||
shells.dedup();
|
||||
// Newest first; a few tries are enough (CI builds every architecture together).
|
||||
for v in shells.iter().take(5) {
|
||||
match has_file(cfg, &agent, SHELL, v) {
|
||||
Ok(true) => {
|
||||
latest.insert(SHELL.into(), v.clone());
|
||||
break;
|
||||
}
|
||||
Ok(false) => log::info!("{SHELL} {v}: no {} build", crate::arch::NAME),
|
||||
Err(e) => {
|
||||
log::warn!("{SHELL} {v}: {e:#}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(latest)
|
||||
}
|
||||
|
||||
const SHELL: &str = "sf-shell";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PackageFile {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// Whether a package version has its file for this architecture.
|
||||
fn has_file(cfg: &Config, agent: &ureq::Agent, name: &str, version: &str) -> Result<bool> {
|
||||
let url = format!("{}/api/v1/packages/{}/generic/{name}/{version}/files", cfg.server, cfg.owner);
|
||||
let text = get(cfg, agent, &url)?.body_mut().read_to_string()?;
|
||||
let files: Vec<PackageFile> = serde_json::from_str(&text).context("package files")?;
|
||||
let want = file_name(name, version);
|
||||
Ok(files.iter().any(|f| f.name == want))
|
||||
}
|
||||
|
||||
/// File name of a package in the registry.
|
||||
pub fn file_name(name: &str, version: &str) -> String {
|
||||
format!("{name}-{version}.tar.zst")
|
||||
if name == SHELL { crate::arch::file_name(name, version) } else { format!("{name}-{version}.tar.zst") }
|
||||
}
|
||||
|
||||
/// Downloads a package and its signature into `dir`.
|
||||
|
||||
@@ -81,6 +81,9 @@ const MAX_STORE_FILES: usize = 200_000;
|
||||
struct PkgInfo {
|
||||
name: String,
|
||||
version: String,
|
||||
/// Native packages (the shell): the architecture they were built for.
|
||||
#[serde(default)]
|
||||
arch: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -263,6 +266,9 @@ impl Store {
|
||||
if info.name != expected_name || info.version != version {
|
||||
bail!("package says it is {} {}, expected {expected_name} {version}", info.name, info.version);
|
||||
}
|
||||
if name == "sf-shell" && !crate::arch::runs_here(info.arch.as_deref()) {
|
||||
bail!("{name} {version} is built for {}, this TV is {}", info.arch.as_deref().unwrap_or("x86_64"), crate::arch::NAME);
|
||||
}
|
||||
if let Expect::Store { id, approved, .. } = expect {
|
||||
check_store_manifest(&tmp, id, version, approved)?;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user