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

@@ -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

View File

@@ -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") });
}
}
}

View File

@@ -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());
}