Add Store support and unsigned app releases
This commit is contained in:
493
crates/sf-core/src/apps.rs
Normal file
493
crates/sf-core/src/apps.rs
Normal file
@@ -0,0 +1,493 @@
|
||||
//! 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.
|
||||
|
||||
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 anyhow::{Context, Result, bail};
|
||||
use sf_ipc::launch::{LaunchOptions, command};
|
||||
use sf_ipc::{AppKind, AppManifest, CoreEvent, Settings};
|
||||
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);
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
apps: Vec<AppManifest>,
|
||||
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 {
|
||||
apps_dirs: Vec<PathBuf>,
|
||||
/// Installed store apps (sandboxed, see sf_ipc::sandbox).
|
||||
store_dir: Option<PathBuf>,
|
||||
settings_path: PathBuf,
|
||||
scopes: bool,
|
||||
pub events: broadcast::Sender<CoreEvent>,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
/// True if a systemd user manager answers (`systemctl --user`).
|
||||
fn systemd_user_available() -> bool {
|
||||
if std::env::var_os("SMARTFOX_NO_SCOPES").is_some() {
|
||||
return false;
|
||||
}
|
||||
StdCommand::new("systemctl")
|
||||
.args(["--user", "is-system-running"])
|
||||
.output()
|
||||
.map(|o| {
|
||||
let s = String::from_utf8_lossy(&o.stdout);
|
||||
["running", "degraded", "starting"].iter().any(|w| s.trim() == *w)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn kill_group(pid: u32, sig: libc::c_int) -> bool {
|
||||
// SAFETY: plain syscall; a negative pid addresses the process group.
|
||||
unsafe { libc::kill(-(pid as libc::pid_t), sig) == 0 }
|
||||
}
|
||||
|
||||
async fn systemctl(verb: &str, unit: &str) -> Result<()> {
|
||||
let st = tokio::process::Command::new("systemctl").args(["--user", verb, unit]).status().await?;
|
||||
if !st.success() {
|
||||
bail!("systemctl --user {verb} {unit}: {st}");
|
||||
}
|
||||
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())?;
|
||||
let (events, _) = broadcast::channel(64);
|
||||
Ok(Core {
|
||||
apps_dirs,
|
||||
store_dir,
|
||||
settings_path,
|
||||
scopes: systemd_user_available(),
|
||||
events,
|
||||
state: Mutex::new(State { apps, ..Default::default() }),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn app_count(&self) -> usize {
|
||||
self.state.lock().unwrap().apps.len()
|
||||
}
|
||||
|
||||
pub fn uses_scopes(&self) -> bool {
|
||||
self.scopes
|
||||
}
|
||||
|
||||
pub fn apps(&self) -> Vec<AppManifest> {
|
||||
self.state.lock().unwrap().apps.clone()
|
||||
}
|
||||
|
||||
pub fn foreground(&self) -> Option<String> {
|
||||
self.state.lock().unwrap().foreground.clone()
|
||||
}
|
||||
|
||||
pub fn is_running(&self, id: &str) -> bool {
|
||||
self.state.lock().unwrap().running.iter().any(|r| r.id == id)
|
||||
}
|
||||
|
||||
pub fn emit(&self, ev: CoreEvent) {
|
||||
log::debug!("event {ev:?}");
|
||||
let _ = self.events.send(ev);
|
||||
}
|
||||
|
||||
/// Re-reads the manifests (new packages may have been installed).
|
||||
fn reload_apps(&self) {
|
||||
match sf_ipc::manifest::load_all(&self.apps_dirs, self.store_dir.as_deref()) {
|
||||
Ok(apps) => self.state.lock().unwrap().apps = apps,
|
||||
Err(e) => log::warn!("reloading apps: {e:#}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn data_dir(&self) -> PathBuf {
|
||||
self.settings_path.parent().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
|
||||
}
|
||||
|
||||
/// Starts the app or brings it back. `query` (DIAL) restarts a running
|
||||
/// app so it sees the new parameters.
|
||||
pub async fn launch(self: &Arc<Self>, id: &str, query: Option<String>, cast: bool) -> Result<()> {
|
||||
self.reload_apps();
|
||||
let app = self.state.lock().unwrap().apps.iter().find(|a| a.id == id).cloned();
|
||||
let app = app.with_context(|| format!("no app {id:?}"))?;
|
||||
if app.kind == AppKind::Builtin || app.service {
|
||||
return Ok(());
|
||||
}
|
||||
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;
|
||||
}
|
||||
let prev = self.set_foreground(Some(id));
|
||||
self.leave_foreground(prev, switching);
|
||||
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);
|
||||
}
|
||||
}
|
||||
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) {
|
||||
let Some(prev) = prev else { return };
|
||||
if switching {
|
||||
self.freeze_later(prev);
|
||||
} else {
|
||||
self.stop(&prev);
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn(self: &Arc<Self>, app: &AppManifest, query: Option<&str>) -> Result<()> {
|
||||
let settings = Settings::load(&self.settings_path).unwrap_or_default();
|
||||
let data_dir = self.data_dir();
|
||||
let opts = LaunchOptions { data_dir: &data_dir, fullscreen: true, bounds: None, query };
|
||||
let inner = command(app, &settings, &opts)?;
|
||||
|
||||
let serial = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
st.serial += 1;
|
||||
st.serial
|
||||
};
|
||||
let (mut cmd, unit) = if self.scopes {
|
||||
let unit = format!("sf-app-{}-{serial}", app.id);
|
||||
let mut cmd = StdCommand::new("systemd-run");
|
||||
cmd.args(["--user", "--scope", "--quiet", "--collect"])
|
||||
.arg(format!("--unit={unit}"))
|
||||
.args(["-p", "TimeoutStopSec=3"])
|
||||
.arg("--")
|
||||
.arg(inner.get_program())
|
||||
.args(inner.get_args());
|
||||
(cmd, Some(format!("{unit}.scope")))
|
||||
} else {
|
||||
let mut cmd = StdCommand::new(inner.get_program());
|
||||
cmd.args(inner.get_args());
|
||||
(cmd, None)
|
||||
};
|
||||
for (k, v) in inner.get_envs() {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
cmd.process_group(0);
|
||||
let mut child = tokio::process::Command::from(cmd)
|
||||
.kill_on_drop(false)
|
||||
.spawn()
|
||||
.with_context(|| format!("starting {}", app.id))?;
|
||||
let pid = child.id().context("no pid")?;
|
||||
// The app runs in its own process group (pgid == pid).
|
||||
wm::register(pid, &app.id);
|
||||
log::info!("started {} (pid {pid}{})", app.id, unit.as_deref().map(|u| format!(", {u}")).unwrap_or_default());
|
||||
self.state.lock().unwrap().running.push(Running {
|
||||
id: app.id.clone(),
|
||||
pid,
|
||||
unit,
|
||||
frozen: false,
|
||||
last_used: Instant::now(),
|
||||
serial,
|
||||
});
|
||||
let core = self.clone();
|
||||
let id = app.id.clone();
|
||||
tokio::spawn(async move {
|
||||
let status = child.wait().await;
|
||||
log::info!("{id} exited ({status:?})");
|
||||
core.on_exit(&id, serial);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_exit(&self, id: &str, serial: u64) {
|
||||
let was_foreground = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
st.running.retain(|r| !(r.id == id && r.serial == serial));
|
||||
if st.running.iter().any(|r| r.id == id) {
|
||||
return; // a newer instance is already up
|
||||
}
|
||||
let fg = st.foreground.as_deref() == Some(id);
|
||||
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 {
|
||||
wm::focus(None);
|
||||
}
|
||||
self.emit(CoreEvent::AppStopped { app_id: id.to_string() });
|
||||
}
|
||||
|
||||
/// Home: show the launcher; the foreground app waits frozen (or 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");
|
||||
}
|
||||
|
||||
/// 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 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.
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
async fn stop_and_wait(self: &Arc<Self>, id: &str) {
|
||||
if !self.stop(id) {
|
||||
return;
|
||||
}
|
||||
for _ in 0..60 {
|
||||
if !self.is_running(id) {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
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.
|
||||
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);
|
||||
}
|
||||
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.
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shutdown(self: &Arc<Self>) {
|
||||
let ids: Vec<(Option<String>, u32)> =
|
||||
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") });
|
||||
}
|
||||
}
|
||||
}
|
||||
57
crates/sf-core/src/dial.rs
Normal file
57
crates/sf-core/src/dial.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
//! DIAL glue: apps with a `[dial]` section in their manifest (YouTube) can be
|
||||
//! started from a phone.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sf_dial::{AppState, Config, Handler, LaunchParams};
|
||||
|
||||
use crate::apps::Core;
|
||||
|
||||
struct Dial(Arc<Core>);
|
||||
|
||||
impl Dial {
|
||||
fn app_for(&self, dial_name: &str) -> Option<String> {
|
||||
self.0.apps().into_iter().find(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).map(|a| a.id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for Dial {
|
||||
fn state(&self, name: &str) -> Option<AppState> {
|
||||
let id = self.app_for(name)?;
|
||||
Some(if self.0.is_running(&id) { AppState::Running } else { AppState::Stopped })
|
||||
}
|
||||
|
||||
fn launch(&self, name: &str, params: LaunchParams) -> Result<()> {
|
||||
let id = self.app_for(name).context("unknown app")?;
|
||||
log::info!("dial: {name} -> {id} from {}", params.peer);
|
||||
let core = self.0.clone();
|
||||
let query = params.query();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = core.launch(&id, Some(query), true).await {
|
||||
log::error!("dial launch {id}: {e:#}");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop(&self, name: &str) -> bool {
|
||||
match self.app_for(name) {
|
||||
Some(id) => self.0.stop(&id),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(core: Arc<Core>, port: u16) -> Result<()> {
|
||||
let settings = sf_ipc::Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default();
|
||||
let mut config = Config { http_port: port, ..Default::default() };
|
||||
if let Some(name) = settings.get("device_name").filter(|n| !n.trim().is_empty()) {
|
||||
config.friendly_name = name.trim().to_string();
|
||||
}
|
||||
if let Ok(id) = std::fs::read_to_string("/etc/machine-id") {
|
||||
config.uuid = sf_dial::uuid_from_machine_id(&id);
|
||||
}
|
||||
log::info!("dial: \"{}\" uuid:{}", config.friendly_name, config.uuid);
|
||||
sf_dial::run(config, Dial(core)).await
|
||||
}
|
||||
128
crates/sf-core/src/main.rs
Normal file
128
crates/sf-core/src/main.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
//! 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.
|
||||
//! - 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.
|
||||
//!
|
||||
//! Talks JSON lines with the launcher (`sf_ipc::message`) and plain text
|
||||
//! lines with the compositor (`focus launcher`, `focus <app-id>`).
|
||||
|
||||
#[cfg(unix)]
|
||||
mod apps;
|
||||
#[cfg(unix)]
|
||||
mod dial;
|
||||
#[cfg(unix)]
|
||||
mod server;
|
||||
#[cfg(unix)]
|
||||
mod services;
|
||||
#[cfg(unix)]
|
||||
mod wm;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
unix_main()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
anyhow::bail!("sf-core runs on the TV (Linux); on a desktop the launcher starts apps itself")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct Options {
|
||||
apps_dirs: Vec<std::path::PathBuf>,
|
||||
store_dir: Option<std::path::PathBuf>,
|
||||
settings: std::path::PathBuf,
|
||||
dial_port: u16,
|
||||
no_dial: bool,
|
||||
no_services: bool,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn parse_args() -> Options {
|
||||
let mut o = Options {
|
||||
apps_dirs: vec![],
|
||||
store_dir: None,
|
||||
settings: sf_ipc::paths::settings_file(),
|
||||
dial_port: 56789,
|
||||
no_dial: false,
|
||||
no_services: false,
|
||||
};
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--apps" => o.apps_dirs.extend(args.next().map(Into::into)),
|
||||
"--store-apps" => o.store_dir = args.next().map(Into::into),
|
||||
"--settings" => o.settings = args.next().map(Into::into).unwrap_or(o.settings),
|
||||
"--dial-port" => o.dial_port = args.next().and_then(|p| p.parse().ok()).unwrap_or(o.dial_port),
|
||||
"--no-dial" => o.no_dial = true,
|
||||
"--no-services" => o.no_services = true,
|
||||
other => log::warn!("unknown argument {other}"),
|
||||
}
|
||||
}
|
||||
if o.apps_dirs.is_empty() {
|
||||
o.apps_dirs.push(sf_ipc::paths::apps_dir());
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Resolves when the Wayland display we started in goes away, so a new
|
||||
/// session doesn't find an old sf-core still running.
|
||||
#[cfg(unix)]
|
||||
async fn session_gone() {
|
||||
let Some(display) = std::env::var_os("WAYLAND_DISPLAY") else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
let path = sf_ipc::paths::runtime_dir().join(display);
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
if !path.exists() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn unix_main() -> anyhow::Result<()> {
|
||||
use std::sync::Arc;
|
||||
|
||||
let opts = parse_args();
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
|
||||
rt.block_on(async move {
|
||||
let core = Arc::new(apps::Core::new(opts.apps_dirs.clone(), opts.store_dir.clone(), opts.settings.clone())?);
|
||||
log::info!(
|
||||
"{} apps; systemd scopes: {}; window switching: {}",
|
||||
core.app_count(),
|
||||
core.uses_scopes(),
|
||||
wm::available()
|
||||
);
|
||||
tokio::spawn(apps::watch_memory(core.clone()));
|
||||
if !opts.no_services {
|
||||
services::start_all(core.clone());
|
||||
}
|
||||
if !opts.no_dial {
|
||||
let core = core.clone();
|
||||
let port = opts.dial_port;
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = dial::run(core, port).await {
|
||||
log::error!("dial: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
let serve = server::serve(core.clone());
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
tokio::select! {
|
||||
r = serve => r?,
|
||||
_ = session_gone() => log::info!("the Wayland session ended"),
|
||||
_ = term.recv() => log::info!("terminating"),
|
||||
_ = tokio::signal::ctrl_c() => log::info!("interrupted"),
|
||||
}
|
||||
core.shutdown();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
81
crates/sf-core/src/server.rs
Normal file
81
crates/sf-core/src/server.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
//! The core socket: the launcher sends requests, every client gets events.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sf_ipc::{CoreEvent, LauncherRequest};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
|
||||
use crate::apps::Core;
|
||||
use crate::wm;
|
||||
|
||||
pub async fn serve(core: Arc<Core>) -> Result<()> {
|
||||
let path = sf_ipc::paths::core_socket();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let listener = UnixListener::bind(&path).with_context(|| format!("binding {}", path.display()))?;
|
||||
log::info!("core socket {}", path.display());
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let core = core.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = client(core, stream).await {
|
||||
log::debug!("client: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn client(core: Arc<Core>, stream: UnixStream) -> Result<()> {
|
||||
let (read, mut write) = stream.into_split();
|
||||
let mut events = core.events.subscribe();
|
||||
let hello = CoreEvent::Hello { switching: wm::available(), foreground: core.foreground() };
|
||||
write.write_all(hello.to_line().as_bytes()).await?;
|
||||
|
||||
let writer = tokio::spawn(async move {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Ok(ev) => {
|
||||
if write.write_all(ev.to_line().as_bytes()).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(RecvError::Lagged(n)) => log::warn!("client lagged, {n} events dropped"),
|
||||
Err(RecvError::Closed) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut lines = BufReader::new(read).lines();
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match serde_json::from_str::<LauncherRequest>(line) {
|
||||
Ok(req) => handle(&core, req).await,
|
||||
Err(e) => log::warn!("bad request {line:?}: {e}"),
|
||||
}
|
||||
}
|
||||
writer.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle(core: &Arc<Core>, req: LauncherRequest) {
|
||||
log::info!("request {req:?}");
|
||||
match req {
|
||||
LauncherRequest::Launch { app_id, query } => {
|
||||
if let Err(e) = core.launch(&app_id, query, false).await {
|
||||
log::error!("launch {app_id}: {e:#}");
|
||||
let name = core.apps().into_iter().find(|a| a.id == app_id).map(|a| a.name).unwrap_or(app_id.clone());
|
||||
core.emit(CoreEvent::Toast { text: format!("{name}: {e:#}") });
|
||||
core.emit(CoreEvent::AppStopped { app_id });
|
||||
}
|
||||
}
|
||||
LauncherRequest::GoHome => core.go_home(),
|
||||
LauncherRequest::Stop { app_id } => {
|
||||
core.stop(&app_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
179
crates/sf-core/src/services.rs
Normal file
179
crates/sf-core/src/services.rs
Normal file
@@ -0,0 +1,179 @@
|
||||
//! Background receivers (manifests with `service = true`): AirPlay (UxPlay)
|
||||
//! and Miracast (sf-miracast). They run all the time and are restarted if
|
||||
//! they exit; their output tells us when a device connects.
|
||||
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use sf_ipc::launch::{LaunchOptions, command};
|
||||
use sf_ipc::{AppManifest, Settings};
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::apps::Core;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Signal {
|
||||
Connected(String),
|
||||
Ended,
|
||||
}
|
||||
|
||||
/// Recognizes connection events in a receiver's output.
|
||||
/// - UxPlay: `connection request from <name> (<model>) with deviceID = …`,
|
||||
/// `Open connections: <n>`;
|
||||
/// - our own receivers: `SF-EVENT connected <name>`, `SF-EVENT ended`.
|
||||
pub fn parse_line(line: &str, connected: bool) -> Option<Signal> {
|
||||
let line = line.trim();
|
||||
if let Some(rest) = line.strip_prefix("SF-EVENT ") {
|
||||
return match rest.split_once(' ') {
|
||||
Some(("connected", name)) => Some(Signal::Connected(name.trim().to_string())),
|
||||
_ if rest == "connected" => Some(Signal::Connected(String::new())),
|
||||
_ if rest.starts_with("ended") => Some(Signal::Ended),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if let Some(i) = line.find("connection request from ") {
|
||||
let rest = &line[i + "connection request from ".len()..];
|
||||
let name = rest.split(" (").next().unwrap_or(rest).trim();
|
||||
return Some(Signal::Connected(name.to_string()));
|
||||
}
|
||||
if let Some(i) = line.find("Open connections: ") {
|
||||
let n: u32 = line[i + "Open connections: ".len()..].trim().parse().ok()?;
|
||||
return match (n, connected) {
|
||||
(0, true) => Some(Signal::Ended),
|
||||
(n, false) if n > 0 => Some(Signal::Connected(String::new())),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn start_all(core: Arc<Core>) {
|
||||
for app in core.apps().into_iter().filter(|a| a.service) {
|
||||
tokio::spawn(supervise(core.clone(), app));
|
||||
}
|
||||
}
|
||||
|
||||
async fn supervise(core: Arc<Core>, app: AppManifest) {
|
||||
let mut failures = 0u32;
|
||||
loop {
|
||||
let settings = Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default();
|
||||
let data_dir = std::env::temp_dir();
|
||||
let opts = LaunchOptions { data_dir: &data_dir, fullscreen: true, bounds: None, query: None };
|
||||
let cmd = match command(&app, &settings, &opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("{}: {e:#}", app.id);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut cmd = cmd;
|
||||
// The receiver must not outlive us: an orphaned UxPlay would keep its
|
||||
// ports and make the next session's copy fail.
|
||||
// SAFETY: prctl is async-signal-safe.
|
||||
unsafe {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.pre_exec(|| {
|
||||
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut cmd = tokio::process::Command::from(cmd);
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null()).kill_on_drop(true);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
log::warn!("{}: {:?} is not installed; retrying in 5 minutes", app.id, app.exec);
|
||||
tokio::time::sleep(Duration::from_secs(300)).await;
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{}: {e}", app.id);
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
log::info!("{} receiver running (pid {:?})", app.id, child.id());
|
||||
if let Some(pid) = child.id() {
|
||||
crate::wm::register(pid, &app.id);
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
|
||||
for out in [child.stdout.take().map(|s| Box::new(s) as Box<dyn tokio::io::AsyncRead + Unpin + Send>),
|
||||
child.stderr.take().map(|s| Box::new(s) as Box<dyn tokio::io::AsyncRead + Unpin + Send>)]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(out).lines();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
let mut connected = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = rx.recv() => {
|
||||
let Some(line) = line else {
|
||||
let status = child.wait().await;
|
||||
log::warn!("{} receiver exited: {status:?}", app.id);
|
||||
break;
|
||||
};
|
||||
log::debug!("[{}] {line}", app.id);
|
||||
match parse_line(&line, connected) {
|
||||
Some(Signal::Connected(name)) if !connected => {
|
||||
connected = true;
|
||||
let name = if name.is_empty() { "eszköz".to_string() } else { name };
|
||||
log::info!("{}: {name} connected", app.id);
|
||||
core.cast_connected(&app.id, &name);
|
||||
}
|
||||
Some(Signal::Ended) if connected => {
|
||||
connected = false;
|
||||
log::info!("{}: session ended", app.id);
|
||||
core.cast_ended(&app.id);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
status = child.wait() => {
|
||||
log::warn!("{} receiver exited: {status:?}", app.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill().await;
|
||||
if connected {
|
||||
core.cast_ended(&app.id);
|
||||
}
|
||||
failures = if started.elapsed() > Duration::from_secs(60) { 0 } else { failures + 1 };
|
||||
let wait = Duration::from_secs((2u64 << failures.min(5)).min(60));
|
||||
tokio::time::sleep(wait).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_receiver_output() {
|
||||
assert_eq!(
|
||||
parse_line("connection request from Peti iPhone-ja (iPhone15,2) with deviceID = AA:BB", false),
|
||||
Some(Signal::Connected("Peti iPhone-ja".into()))
|
||||
);
|
||||
assert_eq!(parse_line("Open connections: 0", true), Some(Signal::Ended));
|
||||
assert_eq!(parse_line("Open connections: 0", false), None);
|
||||
assert_eq!(parse_line("Open connections: 1", false), Some(Signal::Connected(String::new())));
|
||||
assert_eq!(parse_line("SF-EVENT connected Galaxy S24", false), Some(Signal::Connected("Galaxy S24".into())));
|
||||
assert_eq!(parse_line("SF-EVENT ended", true), Some(Signal::Ended));
|
||||
assert_eq!(parse_line("random", false), None);
|
||||
}
|
||||
}
|
||||
56
crates/sf-core/src/wm.rs
Normal file
56
crates/sf-core/src/wm.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
//! Client for the sf-compositor control socket. One command per line, one
|
||||
//! reply line (`ok` or `err <reason>`):
|
||||
//! focus launcher show the launcher
|
||||
//! focus <app-id> show that app's window (as soon as it has one)
|
||||
//! register <pgid> <app-id> windows of that process group belong to the app
|
||||
//!
|
||||
//! Without sf-compositor (e.g. under cage) there is no socket: the newest
|
||||
//! window is always on top, so apps can't wait in the background.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
pub fn available() -> bool {
|
||||
sf_ipc::paths::wm_socket().exists()
|
||||
}
|
||||
|
||||
pub fn send(cmd: &str) -> Result<()> {
|
||||
let path = sf_ipc::paths::wm_socket();
|
||||
let mut s = UnixStream::connect(&path).with_context(|| format!("connecting {}", path.display()))?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
s.set_write_timeout(Some(Duration::from_secs(2)))?;
|
||||
writeln!(s, "{cmd}")?;
|
||||
let mut reply = String::new();
|
||||
BufReader::new(s).read_line(&mut reply)?;
|
||||
let reply = reply.trim();
|
||||
if reply == "ok" {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("compositor: {reply}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows an app, or the launcher with `None`. Logs instead of failing.
|
||||
pub fn focus(app_id: Option<&str>) {
|
||||
if !available() {
|
||||
return;
|
||||
}
|
||||
let cmd = format!("focus {}", app_id.unwrap_or("launcher"));
|
||||
if let Err(e) = send(&cmd) {
|
||||
log::warn!("{cmd}: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells the compositor which app a process group belongs to (Chromium hides
|
||||
/// its environment, so the compositor can't find out by itself).
|
||||
pub fn register(pgid: u32, app_id: &str) {
|
||||
if !available() {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = send(&format!("register {pgid} {app_id}")) {
|
||||
log::warn!("register {app_id}: {e:#}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user