Add Store support and unsigned app releases
This commit is contained in:
26
crates/sf-compositor/Cargo.toml
Normal file
26
crates/sf-compositor/Cargo.toml
Normal file
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "sf-compositor"
|
||||
description = "Fennec OS kiosk Wayland compositor (Smithay): launcher + one full-screen app, animated switching, volume OSD"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
smithay = { version = "0.7", default-features = false, features = [
|
||||
"backend_drm",
|
||||
"backend_gbm",
|
||||
"backend_egl",
|
||||
"backend_libinput",
|
||||
"backend_udev",
|
||||
"backend_session_libseat",
|
||||
"backend_winit",
|
||||
"renderer_gl",
|
||||
"wayland_frontend",
|
||||
"desktop",
|
||||
] }
|
||||
72
crates/sf-compositor/src/control.rs
Normal file
72
crates/sf-compositor/src/control.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
//! Control socket for sf-core. One command per line, one reply line:
|
||||
//! focus launcher | focus <app-id> -> ok
|
||||
//! register <pgid> <app-id> -> ok (windows of that process group belong to the app)
|
||||
//! status -> ok visible=<app|launcher|none> target=<...>
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use smithay::reexports::calloop::generic::Generic;
|
||||
use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
|
||||
|
||||
use crate::state::{App, Target};
|
||||
|
||||
pub fn listen(handle: &LoopHandle<'static, App>) -> Result<()> {
|
||||
let path = sf_ipc::paths::wm_socket();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let listener = UnixListener::bind(&path)?;
|
||||
listener.set_nonblocking(true)?;
|
||||
tracing::info!("control socket {}", path.display());
|
||||
handle
|
||||
.insert_source(Generic::new(listener, Interest::READ, Mode::Level), |_, listener, app: &mut App| {
|
||||
while let Ok((stream, _)) = listener.accept() {
|
||||
let _ = stream.set_nonblocking(false);
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(300)));
|
||||
let Ok(mut writer) = stream.try_clone() else { continue };
|
||||
let mut line = String::new();
|
||||
if BufReader::new(stream).read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
let reply = handle_command(app, line.trim());
|
||||
let _ = writeln!(writer, "{reply}");
|
||||
}
|
||||
Ok(PostAction::Continue)
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("control source: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_command(app: &mut App, cmd: &str) -> String {
|
||||
let st = &mut app.state;
|
||||
match cmd.split_once(' ') {
|
||||
Some(("focus", "launcher")) => {
|
||||
st.set_target(Target::Launcher);
|
||||
"ok".into()
|
||||
}
|
||||
Some(("focus", id)) if !id.trim().is_empty() => {
|
||||
st.set_target(Target::App(id.trim().to_string()));
|
||||
"ok".into()
|
||||
}
|
||||
Some(("register", rest)) => match rest.trim().split_once(' ') {
|
||||
Some((pgid, id)) if pgid.parse::<i32>().is_ok() && !id.trim().is_empty() => {
|
||||
st.register(pgid.parse().unwrap(), id.trim().to_string());
|
||||
"ok".into()
|
||||
}
|
||||
_ => "err usage: register <pgid> <app-id>".into(),
|
||||
},
|
||||
_ if cmd == "status" => {
|
||||
let visible = match &st.visible {
|
||||
Some(w) => st.app_of_window(w).unwrap_or_else(|| "launcher".into()),
|
||||
None => "none".into(),
|
||||
};
|
||||
let target = match &st.target {
|
||||
Target::Launcher => "launcher".to_string(),
|
||||
Target::App(id) => id.clone(),
|
||||
};
|
||||
format!("ok visible={visible} target={target} windows={} screen={}", st.wins.len(), if st.screen_on { "on" } else { "off" })
|
||||
}
|
||||
_ => format!("err unknown command {cmd:?}"),
|
||||
}
|
||||
}
|
||||
112
crates/sf-compositor/src/main.rs
Normal file
112
crates/sf-compositor/src/main.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
//! sf-compositor: the Fennec OS kiosk Wayland compositor (Smithay).
|
||||
//!
|
||||
//! - Every window is full screen. One is visible: the launcher or the app
|
||||
//! sf-core put in front (`focus <app-id>` on the control socket). Other
|
||||
//! app windows stay mapped but hidden, so a frozen app comes back at once.
|
||||
//! - Switching animates: an app zooms and fades in over the launcher, and
|
||||
//! back out on Home.
|
||||
//! - Volume keys change the PipeWire volume and show an OSD bar; the Home key
|
||||
//! (if it reaches us as a key) is sent to the launcher.
|
||||
//! - wlr-output-management, so `wlr-randr` can list and set display modes
|
||||
//! and turn the screen off (the launcher's display settings and standby).
|
||||
//!
|
||||
//! Usage: `sf-compositor [--winit] -- <startup command>`; exits when the
|
||||
//! startup command exits (like cage).
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod control;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod output_mgmt;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod state;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod udev;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod winit;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info,smithay=warn"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).init();
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
linux_main()
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
anyhow::bail!("sf-compositor needs Linux (DRM/KMS or a Wayland/X11 session for --winit)")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn linux_main() -> anyhow::Result<()> {
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
|
||||
use smithay::reexports::wayland_server::Display;
|
||||
|
||||
let mut winit = std::env::var_os("WAYLAND_DISPLAY").is_some() || std::env::var_os("DISPLAY").is_some();
|
||||
let mut command: Vec<String> = vec![];
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--winit" => winit = true,
|
||||
"--drm" => winit = false,
|
||||
"--" => {
|
||||
command = args.by_ref().collect();
|
||||
break;
|
||||
}
|
||||
other => command.push(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
let mut event_loop: EventLoop<state::App> = EventLoop::try_new()?;
|
||||
let display: Display<state::State> = Display::new()?;
|
||||
let mut st = state::State::new(&mut event_loop, display)?;
|
||||
let backend = if winit {
|
||||
tracing::info!("backend: winit (nested window)");
|
||||
winit::init(&mut event_loop, &mut st)?
|
||||
} else {
|
||||
tracing::info!("backend: DRM/KMS");
|
||||
udev::init(&mut event_loop, &mut st)?
|
||||
};
|
||||
control::listen(&event_loop.handle()).context("control socket")?;
|
||||
|
||||
// SAFETY-free env setup: done before any thread is spawned by us.
|
||||
unsafe {
|
||||
std::env::set_var("WAYLAND_DISPLAY", &st.socket_name);
|
||||
std::env::set_var("SMARTFOX_WM_SOCKET", sf_ipc::paths::wm_socket());
|
||||
}
|
||||
tracing::info!("WAYLAND_DISPLAY={}", st.socket_name.to_string_lossy());
|
||||
|
||||
let mut app = state::App { state: st, backend };
|
||||
|
||||
if let Some((prog, rest)) = command.split_first() {
|
||||
let mut child = std::process::Command::new(prog)
|
||||
.args(rest)
|
||||
.spawn()
|
||||
.with_context(|| format!("starting {prog}"))?;
|
||||
tracing::info!("started {prog} (pid {})", child.id());
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(Timer::from_duration(Duration::from_millis(500)), move |_, _, app: &mut state::App| {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
tracing::info!("startup command exited ({status}), quitting");
|
||||
app.state.loop_signal.stop();
|
||||
TimeoutAction::Drop
|
||||
}
|
||||
_ => TimeoutAction::ToDuration(Duration::from_millis(500)),
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("timer: {e}"))?;
|
||||
}
|
||||
|
||||
event_loop.run(Some(Duration::from_millis(16)), &mut app, |app| {
|
||||
app.after_dispatch();
|
||||
})?;
|
||||
let _ = std::fs::remove_file(sf_ipc::paths::wm_socket());
|
||||
Ok(())
|
||||
}
|
||||
355
crates/sf-compositor/src/output_mgmt.rs
Normal file
355
crates/sf-compositor/src/output_mgmt.rs
Normal file
@@ -0,0 +1,355 @@
|
||||
//! wlr-output-management (v2), so `wlr-randr` works: it lists the TV's
|
||||
//! modes, sets one, and turns the output off/on (standby).
|
||||
//!
|
||||
//! Changes are not applied here: `apply` queues a `PendingConfig`, and the
|
||||
//! backend applies it after the dispatch (`App::after_dispatch`).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use smithay::reexports::wayland_protocols_wlr::output_management::v1::server::{
|
||||
zwlr_output_configuration_head_v1::{self, ZwlrOutputConfigurationHeadV1},
|
||||
zwlr_output_configuration_v1::{self, ZwlrOutputConfigurationV1},
|
||||
zwlr_output_head_v1::{self, ZwlrOutputHeadV1},
|
||||
zwlr_output_manager_v1::{self, ZwlrOutputManagerV1},
|
||||
zwlr_output_mode_v1::{self, ZwlrOutputModeV1},
|
||||
};
|
||||
use smithay::reexports::wayland_server::backend::GlobalId;
|
||||
use smithay::reexports::wayland_server::protocol::wl_output;
|
||||
use smithay::reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, WEnum,
|
||||
};
|
||||
|
||||
use crate::state::State;
|
||||
|
||||
const VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ModeInfo {
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
/// mHz
|
||||
pub refresh: i32,
|
||||
pub preferred: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct HeadInfo {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub make: String,
|
||||
pub model: String,
|
||||
pub physical: (i32, i32),
|
||||
pub modes: Vec<ModeInfo>,
|
||||
pub current: Option<usize>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl HeadInfo {
|
||||
/// From the current output; the backend keeps the mode list in the
|
||||
/// output's user data (`OutputModes`).
|
||||
pub fn from_state(state: &State) -> Option<HeadInfo> {
|
||||
let output = state.output.as_ref()?;
|
||||
let props = output.physical_properties();
|
||||
let modes: Vec<ModeInfo> = output
|
||||
.user_data()
|
||||
.get::<OutputModes>()
|
||||
.map(|m| m.0.lock().unwrap().clone())
|
||||
.unwrap_or_default();
|
||||
let cur = output.current_mode();
|
||||
let current = cur.and_then(|c| {
|
||||
modes.iter().position(|m| m.width == c.size.w && m.height == c.size.h && (m.refresh - c.refresh).abs() < 500)
|
||||
});
|
||||
Some(HeadInfo {
|
||||
name: output.name(),
|
||||
description: format!("{} {} ({})", props.make, props.model, output.name()),
|
||||
make: props.make.clone(),
|
||||
model: props.model.clone(),
|
||||
physical: (props.size.w, props.size.h),
|
||||
modes,
|
||||
current,
|
||||
enabled: state.screen_on,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode list of an output, stored in `Output::user_data()` by the backend.
|
||||
#[derive(Default)]
|
||||
pub struct OutputModes(pub Mutex<Vec<ModeInfo>>);
|
||||
|
||||
/// What a client asked for in one configuration.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct Requested {
|
||||
enabled: Option<bool>,
|
||||
mode: Option<ModeInfo>,
|
||||
/// Refresh 0 in a custom mode: any rate.
|
||||
any_refresh: bool,
|
||||
}
|
||||
|
||||
struct ConfigData {
|
||||
serial: u32,
|
||||
req: Requested,
|
||||
used: bool,
|
||||
}
|
||||
|
||||
pub struct PendingConfig {
|
||||
config: ZwlrOutputConfigurationV1,
|
||||
pub enabled: bool,
|
||||
/// Wanted mode; None keeps the current one.
|
||||
pub mode: Option<ModeInfo>,
|
||||
pub any_refresh: bool,
|
||||
pub test_only: bool,
|
||||
}
|
||||
|
||||
impl PendingConfig {
|
||||
pub fn succeeded(&self) {
|
||||
self.config.succeeded();
|
||||
}
|
||||
pub fn failed(&self) {
|
||||
self.config.failed();
|
||||
}
|
||||
}
|
||||
|
||||
struct ManagerEntry {
|
||||
manager: ZwlrOutputManagerV1,
|
||||
head: Option<ZwlrOutputHeadV1>,
|
||||
modes: Vec<ZwlrOutputModeV1>,
|
||||
}
|
||||
|
||||
pub struct OutputMgmtState {
|
||||
_global: GlobalId,
|
||||
managers: Vec<ManagerEntry>,
|
||||
info: Option<HeadInfo>,
|
||||
serial: u32,
|
||||
}
|
||||
|
||||
impl OutputMgmtState {
|
||||
pub fn new(dh: &DisplayHandle) -> Self {
|
||||
let global = dh.create_global::<State, ZwlrOutputManagerV1, _>(VERSION, ());
|
||||
OutputMgmtState { _global: global, managers: vec![], info: None, serial: 1 }
|
||||
}
|
||||
|
||||
/// New output state: resend it to every client if it changed.
|
||||
pub fn update(&mut self, dh: &DisplayHandle, info: Option<HeadInfo>) {
|
||||
if info == self.info {
|
||||
return;
|
||||
}
|
||||
self.info = info;
|
||||
self.serial += 1;
|
||||
for i in 0..self.managers.len() {
|
||||
self.send_heads(dh, i);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_heads(&mut self, dh: &DisplayHandle, i: usize) {
|
||||
let serial = self.serial;
|
||||
let info = self.info.clone();
|
||||
let entry = &mut self.managers[i];
|
||||
// Simplest correct way to change heads and modes: retire the old
|
||||
// objects and announce new ones.
|
||||
for m in entry.modes.drain(..) {
|
||||
m.finished();
|
||||
}
|
||||
if let Some(h) = entry.head.take() {
|
||||
h.finished();
|
||||
}
|
||||
let Ok(client) = dh.get_client(entry.manager.id()) else { return };
|
||||
if let Some(info) = info {
|
||||
let version = entry.manager.version();
|
||||
let Ok(head) = client.create_resource::<ZwlrOutputHeadV1, _, State>(dh, version, ()) else { return };
|
||||
entry.manager.head(&head);
|
||||
head.name(info.name.clone());
|
||||
head.description(info.description.clone());
|
||||
if info.physical.0 > 0 {
|
||||
head.physical_size(info.physical.0, info.physical.1);
|
||||
}
|
||||
for m in &info.modes {
|
||||
let Ok(mode) = client.create_resource::<ZwlrOutputModeV1, _, State>(dh, version, m.clone()) else {
|
||||
continue;
|
||||
};
|
||||
head.mode(&mode);
|
||||
mode.size(m.width, m.height);
|
||||
mode.refresh(m.refresh);
|
||||
if m.preferred {
|
||||
mode.preferred();
|
||||
}
|
||||
entry.modes.push(mode);
|
||||
}
|
||||
head.enabled(i32::from(info.enabled));
|
||||
if info.enabled {
|
||||
if let Some(cur) = info.current.and_then(|c| entry.modes.get(c)) {
|
||||
head.current_mode(cur);
|
||||
}
|
||||
head.position(0, 0);
|
||||
head.transform(wl_output::Transform::Normal);
|
||||
head.scale(1.0);
|
||||
}
|
||||
if version >= 2 {
|
||||
head.make(info.make.clone());
|
||||
head.model(info.model.clone());
|
||||
}
|
||||
entry.head = Some(head);
|
||||
}
|
||||
entry.manager.done(serial);
|
||||
}
|
||||
}
|
||||
|
||||
impl GlobalDispatch<ZwlrOutputManagerV1, ()> for State {
|
||||
fn bind(
|
||||
state: &mut State,
|
||||
dh: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<ZwlrOutputManagerV1>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
let manager = data_init.init(resource, ());
|
||||
state.output_mgmt.managers.push(ManagerEntry { manager, head: None, modes: vec![] });
|
||||
let i = state.output_mgmt.managers.len() - 1;
|
||||
state.output_mgmt.send_heads(dh, i);
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputManagerV1, ()> for State {
|
||||
fn request(
|
||||
state: &mut State,
|
||||
_client: &Client,
|
||||
resource: &ZwlrOutputManagerV1,
|
||||
request: zwlr_output_manager_v1::Request,
|
||||
_data: &(),
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
match request {
|
||||
zwlr_output_manager_v1::Request::CreateConfiguration { id, serial } => {
|
||||
data_init.init(id, Arc::new(Mutex::new(ConfigData { serial, req: Requested::default(), used: false })));
|
||||
}
|
||||
zwlr_output_manager_v1::Request::Stop => {
|
||||
resource.finished();
|
||||
state.output_mgmt.managers.retain(|m| &m.manager != resource);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(state: &mut State, _client: smithay::reexports::wayland_server::backend::ClientId, resource: &ZwlrOutputManagerV1, _data: &()) {
|
||||
state.output_mgmt.managers.retain(|m| &m.manager != resource);
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputHeadV1, ()> for State {
|
||||
fn request(
|
||||
_state: &mut State,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrOutputHeadV1,
|
||||
_request: zwlr_output_head_v1::Request,
|
||||
_data: &(),
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputModeV1, ModeInfo> for State {
|
||||
fn request(
|
||||
_state: &mut State,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrOutputModeV1,
|
||||
_request: zwlr_output_mode_v1::Request,
|
||||
_data: &ModeInfo,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
type ConfigRef = Arc<Mutex<ConfigData>>;
|
||||
|
||||
impl Dispatch<ZwlrOutputConfigurationV1, ConfigRef> for State {
|
||||
fn request(
|
||||
state: &mut State,
|
||||
_client: &Client,
|
||||
resource: &ZwlrOutputConfigurationV1,
|
||||
request: zwlr_output_configuration_v1::Request,
|
||||
data: &ConfigRef,
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
use zwlr_output_configuration_v1::Request;
|
||||
match request {
|
||||
Request::EnableHead { id, head: _ } => {
|
||||
data.lock().unwrap().req.enabled = Some(true);
|
||||
data_init.init(id, data.clone());
|
||||
}
|
||||
Request::DisableHead { head: _ } => {
|
||||
data.lock().unwrap().req.enabled = Some(false);
|
||||
}
|
||||
Request::Apply | Request::Test => {
|
||||
let test_only = matches!(request, Request::Test);
|
||||
let mut d = data.lock().unwrap();
|
||||
if d.used {
|
||||
resource.post_error(zwlr_output_configuration_v1::Error::AlreadyUsed, "already used");
|
||||
return;
|
||||
}
|
||||
d.used = true;
|
||||
if d.serial != state.output_mgmt.serial {
|
||||
resource.cancelled();
|
||||
return;
|
||||
}
|
||||
state.pending_configs.push(PendingConfig {
|
||||
config: resource.clone(),
|
||||
enabled: d.req.enabled.unwrap_or(true),
|
||||
mode: d.req.mode.clone(),
|
||||
any_refresh: d.req.any_refresh,
|
||||
test_only,
|
||||
});
|
||||
}
|
||||
Request::Destroy => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputConfigurationHeadV1, ConfigRef> for State {
|
||||
fn request(
|
||||
_state: &mut State,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrOutputConfigurationHeadV1,
|
||||
request: zwlr_output_configuration_head_v1::Request,
|
||||
data: &ConfigRef,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
use zwlr_output_configuration_head_v1::Request;
|
||||
let mut d = data.lock().unwrap();
|
||||
match request {
|
||||
Request::SetMode { mode } => {
|
||||
if let Some(m) = mode.data::<ModeInfo>() {
|
||||
d.req.mode = Some(m.clone());
|
||||
d.req.any_refresh = false;
|
||||
}
|
||||
}
|
||||
Request::SetCustomMode { width, height, refresh } => {
|
||||
d.req.mode = Some(ModeInfo { width, height, refresh, preferred: false });
|
||||
d.req.any_refresh = refresh == 0;
|
||||
}
|
||||
// One output at 0,0, normal, scale 1: accept and ignore.
|
||||
Request::SetPosition { .. } | Request::SetScale { .. } => {}
|
||||
Request::SetTransform { transform } => {
|
||||
if !matches!(transform, WEnum::Value(wl_output::Transform::Normal)) {
|
||||
tracing::info!("output transform not supported, ignored");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks the mode a client asked for from the available ones.
|
||||
pub fn match_mode<'a>(modes: &'a [ModeInfo], want: &ModeInfo, any_refresh: bool) -> Option<(usize, &'a ModeInfo)> {
|
||||
let same_size = modes.iter().enumerate().filter(|(_, m)| m.width == want.width && m.height == want.height);
|
||||
if any_refresh {
|
||||
same_size.max_by_key(|(_, m)| m.refresh)
|
||||
} else {
|
||||
same_size.min_by_key(|(_, m)| (m.refresh - want.refresh).abs()).filter(|(_, m)| (m.refresh - want.refresh).abs() < 1000)
|
||||
}
|
||||
}
|
||||
962
crates/sf-compositor/src/state.rs
Normal file
962
crates/sf-compositor/src/state.rs
Normal file
@@ -0,0 +1,962 @@
|
||||
//! Compositor state: Wayland protocol handlers, which window is visible,
|
||||
//! the switch animation, the volume OSD and the render element list.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
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::surface::WaylandSurfaceRenderElement;
|
||||
use smithay::backend::renderer::element::utils::RescaleRenderElement;
|
||||
use smithay::backend::renderer::element::AsRenderElements;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::utils::on_commit_buffer_handler;
|
||||
use smithay::backend::session::Session;
|
||||
use smithay::backend::session::libseat::LibSeatSession;
|
||||
use smithay::desktop::{PopupKind, PopupManager, Space, Window, find_popup_root_surface, get_popup_toplevel_coords};
|
||||
use smithay::input::keyboard::{FilterResult, XkbConfig, keysyms};
|
||||
use smithay::input::{Seat, SeatHandler, SeatState};
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::calloop::generic::Generic;
|
||||
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
|
||||
use smithay::reexports::calloop::{EventLoop, Interest, LoopHandle, LoopSignal, Mode, PostAction};
|
||||
use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
|
||||
use smithay::reexports::wayland_server::backend::{ClientData, ClientId, DisconnectReason};
|
||||
use smithay::reexports::wayland_server::protocol::{wl_buffer, wl_output, wl_seat, wl_surface::WlSurface};
|
||||
use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
|
||||
use smithay::utils::{IsAlive, Logical, Physical, Point, Rectangle, SERIAL_COUNTER, Scale, Serial, Size};
|
||||
use smithay::wayland::buffer::BufferHandler;
|
||||
use smithay::wayland::compositor::{
|
||||
CompositorClientState, CompositorHandler, CompositorState, get_parent, is_sync_subsurface, with_states,
|
||||
};
|
||||
use smithay::wayland::dmabuf::{DmabufGlobal, DmabufHandler, DmabufState, ImportNotifier};
|
||||
use smithay::wayland::output::{OutputHandler, OutputManagerState};
|
||||
use smithay::wayland::selection::SelectionHandler;
|
||||
use smithay::wayland::selection::data_device::{
|
||||
ClientDndGrabHandler, DataDeviceHandler, DataDeviceState, ServerDndGrabHandler, set_data_device_focus,
|
||||
};
|
||||
use smithay::wayland::shell::xdg::decoration::{XdgDecorationHandler, XdgDecorationState};
|
||||
use smithay::wayland::shell::xdg::{
|
||||
PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler, XdgShellState, XdgToplevelSurfaceData,
|
||||
};
|
||||
use smithay::wayland::shm::{ShmHandler, ShmState};
|
||||
use smithay::wayland::socket::ListeningSocketSource;
|
||||
use smithay::wayland::viewporter::ViewporterState;
|
||||
use smithay::{
|
||||
delegate_compositor, delegate_data_device, delegate_dmabuf, delegate_output, delegate_seat, delegate_shm,
|
||||
delegate_viewporter, delegate_xdg_decoration, delegate_xdg_shell,
|
||||
};
|
||||
|
||||
use crate::output_mgmt::{OutputMgmtState, PendingConfig};
|
||||
|
||||
/// App <-> launcher switch: the app fades in (growing a little) over the
|
||||
/// launcher's splash, or fades out (shrinking) over the home screen.
|
||||
const ENTER: Duration = Duration::from_millis(560);
|
||||
const LEAVE: Duration = Duration::from_millis(420);
|
||||
/// The launcher's launch morph (app.slint `launch-t`). An app coming up over
|
||||
/// the launcher waits until the morph has nearly settled.
|
||||
const MORPH: Duration = Duration::from_millis(720);
|
||||
/// A new window's first frames are often blank; give it a moment.
|
||||
const SETTLE: Duration = Duration::from_millis(250);
|
||||
/// Longest wait for a browser window to finish loading its page.
|
||||
const LOAD_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
/// How often a held-back app window is checked again.
|
||||
const HOLD_POLL: Duration = Duration::from_millis(30);
|
||||
const OSD_TIME: Duration = Duration::from_millis(1600);
|
||||
|
||||
/// evdev key codes + 8 (xkb keycodes).
|
||||
const KEY_MUTE: u32 = 113 + 8;
|
||||
const KEY_VOLUMEDOWN: u32 = 114 + 8;
|
||||
const KEY_VOLUMEUP: u32 = 115 + 8;
|
||||
const KEY_HOMEPAGE: u32 = 172 + 8;
|
||||
|
||||
smithay::backend::renderer::element::render_elements! {
|
||||
pub SfElement<=GlesRenderer>;
|
||||
Surface=WaylandSurfaceRenderElement<GlesRenderer>,
|
||||
Scaled=RescaleRenderElement<WaylandSurfaceRenderElement<GlesRenderer>>,
|
||||
Solid=SolidColorRenderElement,
|
||||
}
|
||||
|
||||
/// The event loop data: protocol state plus the display backend.
|
||||
pub struct App {
|
||||
pub state: State,
|
||||
pub backend: Backend,
|
||||
}
|
||||
|
||||
pub enum Backend {
|
||||
Winit(crate::winit::WinitData),
|
||||
Udev(crate::udev::UdevData),
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Runs after every event loop dispatch.
|
||||
pub fn after_dispatch(&mut self) {
|
||||
// Output configuration requests (wlr-randr) need the backend.
|
||||
for cfg in std::mem::take(&mut self.state.pending_configs) {
|
||||
let result = match &mut self.backend {
|
||||
Backend::Winit(w) => w.apply_config(&mut self.state, &cfg),
|
||||
Backend::Udev(u) => u.apply_config(&mut self.state, &cfg),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {
|
||||
cfg.succeeded();
|
||||
self.state.output_mgmt_refresh();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("output configuration failed: {e:#}");
|
||||
cfg.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Backend::Udev(u) = &mut self.backend {
|
||||
u.kick(&mut self.state);
|
||||
}
|
||||
self.state.space.refresh();
|
||||
self.state.popups.cleanup();
|
||||
let _ = self.state.dh.flush_clients();
|
||||
}
|
||||
}
|
||||
|
||||
/// What sf-core wants on screen.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Target {
|
||||
Launcher,
|
||||
App(String),
|
||||
}
|
||||
|
||||
pub struct Win {
|
||||
pub window: Window,
|
||||
/// The app the client belongs to; None for the launcher (system UI).
|
||||
pub app: Option<String>,
|
||||
pub pid: Option<i32>,
|
||||
/// Has a buffer, can be shown.
|
||||
pub mapped: bool,
|
||||
pub mapped_at: Option<Instant>,
|
||||
pub serial: u64,
|
||||
}
|
||||
|
||||
/// `over` zooms/fades in on top of `under` (entering) or out of it (leaving).
|
||||
pub struct Transition {
|
||||
pub over: Window,
|
||||
pub under: Option<Window>,
|
||||
pub start: Instant,
|
||||
pub duration: Duration,
|
||||
pub entering: bool,
|
||||
}
|
||||
|
||||
pub struct Osd {
|
||||
pub level: f32,
|
||||
pub muted: bool,
|
||||
pub until: Instant,
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub dh: DisplayHandle,
|
||||
pub handle: LoopHandle<'static, App>,
|
||||
pub loop_signal: LoopSignal,
|
||||
pub socket_name: OsString,
|
||||
pub start: Instant,
|
||||
|
||||
pub compositor_state: CompositorState,
|
||||
pub xdg_shell_state: XdgShellState,
|
||||
pub shm_state: ShmState,
|
||||
// Kept for their globals.
|
||||
#[allow(dead_code)]
|
||||
pub output_manager_state: OutputManagerState,
|
||||
pub seat_state: SeatState<State>,
|
||||
pub data_device_state: DataDeviceState,
|
||||
pub dmabuf_state: DmabufState,
|
||||
pub dmabuf_global: Option<DmabufGlobal>,
|
||||
#[allow(dead_code)]
|
||||
pub viewporter_state: ViewporterState,
|
||||
#[allow(dead_code)]
|
||||
pub decoration_state: XdgDecorationState,
|
||||
pub output_mgmt: OutputMgmtState,
|
||||
pub pending_configs: Vec<PendingConfig>,
|
||||
pub popups: PopupManager,
|
||||
pub seat: Seat<State>,
|
||||
pub space: Space<Window>,
|
||||
pub session: Option<LibSeatSession>,
|
||||
|
||||
pub output: Option<Output>,
|
||||
pub wins: Vec<Win>,
|
||||
/// Process groups of apps, from sf-core (`register`).
|
||||
pub registered: std::collections::HashMap<i32, String>,
|
||||
serial: u64,
|
||||
pub target: Target,
|
||||
/// When `target` last changed (the launcher starts its morph then).
|
||||
target_at: Instant,
|
||||
/// An app window that could be shown but waits for the launcher's
|
||||
/// morph and for its own first real frame.
|
||||
held: Option<Window>,
|
||||
hold_poll: bool,
|
||||
pub visible: Option<Window>,
|
||||
pub transition: Option<Transition>,
|
||||
pub osd: Option<Osd>,
|
||||
osd_bg: SolidColorBuffer,
|
||||
osd_track: SolidColorBuffer,
|
||||
osd_fill: SolidColorBuffer,
|
||||
/// False while the screen is turned off (wlr-randr --off / standby).
|
||||
pub screen_on: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ClientState {
|
||||
pub compositor_state: CompositorClientState,
|
||||
}
|
||||
|
||||
impl ClientData for ClientState {
|
||||
fn initialized(&self, _client_id: ClientId) {}
|
||||
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
|
||||
}
|
||||
|
||||
/// Process group of a pid (field 5 of /proc/<pid>/stat).
|
||||
fn pgid_of(pid: i32) -> Option<i32> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
||||
// The command name may contain spaces; fields start after the last ')'.
|
||||
let rest = &stat[stat.rfind(')')? + 1..];
|
||||
rest.split_whitespace().nth(2)?.parse().ok()
|
||||
}
|
||||
|
||||
/// The app a client process belongs to:
|
||||
/// 1. its process group, as registered by sf-core (`register <pgid> <app>`);
|
||||
/// 2. its systemd scope (`sf-app-<id>-<n>.scope`);
|
||||
/// 3. `SMARTFOX_APP` in its environment (Chromium overwrites that area, so
|
||||
/// this only works for simple programs like UxPlay).
|
||||
fn app_of_pid(pid: i32, registered: &std::collections::HashMap<i32, String>) -> Option<String> {
|
||||
if let Some(app) = pgid_of(pid).and_then(|g| registered.get(&g)) {
|
||||
return Some(app.clone());
|
||||
}
|
||||
if let Ok(cg) = std::fs::read_to_string(format!("/proc/{pid}/cgroup")) {
|
||||
for unit in cg.split(['/', '\n']) {
|
||||
if let Some(rest) = unit.strip_prefix("sf-app-").and_then(|u| u.strip_suffix(".scope")) {
|
||||
if let Some((id, _serial)) = rest.rsplit_once('-') {
|
||||
return Some(id.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let env = std::fs::read(format!("/proc/{pid}/environ")).ok()?;
|
||||
let key = format!("{}=", sf_ipc::launch::APP_ENV);
|
||||
env.split(|b| *b == 0)
|
||||
.find_map(|kv| kv.strip_prefix(key.as_bytes()))
|
||||
.map(|v| String::from_utf8_lossy(v).into_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn ease_out(t: f32) -> f32 {
|
||||
1.0 - (1.0 - t.clamp(0.0, 1.0)).powi(3)
|
||||
}
|
||||
|
||||
/// Slow start and end: a crossfade you can see, not a cut.
|
||||
fn ease_in_out(t: f32) -> f32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
if t < 0.5 { 4.0 * t * t * t } else { 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0 }
|
||||
}
|
||||
|
||||
/// Whether a window has something worth showing. Browsers show the URL as
|
||||
/// their title until the page has loaded and set its own.
|
||||
fn page_loaded(window: &Window) -> bool {
|
||||
let Some(toplevel) = window.toplevel() else { return true };
|
||||
let (title, app_id) = with_states(toplevel.wl_surface(), |states| {
|
||||
states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.map(|d| {
|
||||
let d = d.lock().unwrap();
|
||||
(d.title.clone().unwrap_or_default(), d.app_id.clone().unwrap_or_default().to_lowercase())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let browser = app_id.contains("chrom") || app_id.contains("edge");
|
||||
let url_like = !title.contains(' ') && (title.contains('/') || title.contains('.') || title.contains(':'));
|
||||
!browser || !(title.is_empty() || title.contains("about:blank") || url_like)
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn new(event_loop: &mut EventLoop<'static, App>, display: Display<State>) -> anyhow::Result<Self> {
|
||||
let dh = display.handle();
|
||||
let compositor_state = CompositorState::new::<Self>(&dh);
|
||||
let xdg_shell_state = XdgShellState::new::<Self>(&dh);
|
||||
let shm_state = ShmState::new::<Self>(&dh, vec![]);
|
||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&dh);
|
||||
let mut seat_state = SeatState::new();
|
||||
let data_device_state = DataDeviceState::new::<Self>(&dh);
|
||||
let viewporter_state = ViewporterState::new::<Self>(&dh);
|
||||
let decoration_state = XdgDecorationState::new::<Self>(&dh);
|
||||
let output_mgmt = OutputMgmtState::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.
|
||||
seat.add_keyboard(XkbConfig::default(), 600, 25)
|
||||
.map_err(|e| anyhow::anyhow!("keyboard: {e:?}"))?;
|
||||
|
||||
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())) {
|
||||
tracing::warn!("client: {e}");
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("socket source: {e}"))?;
|
||||
handle
|
||||
.insert_source(Generic::new(display, Interest::READ, Mode::Level), |_, display, app: &mut App| {
|
||||
// SAFETY: the display is not dropped while the source lives.
|
||||
unsafe {
|
||||
display.get_mut().dispatch_clients(&mut app.state).ok();
|
||||
}
|
||||
Ok(PostAction::Continue)
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("display source: {e}"))?;
|
||||
|
||||
Ok(State {
|
||||
dh,
|
||||
handle,
|
||||
loop_signal: event_loop.get_signal(),
|
||||
socket_name,
|
||||
start: Instant::now(),
|
||||
compositor_state,
|
||||
xdg_shell_state,
|
||||
shm_state,
|
||||
output_manager_state,
|
||||
seat_state,
|
||||
data_device_state,
|
||||
dmabuf_state: DmabufState::new(),
|
||||
dmabuf_global: None,
|
||||
viewporter_state,
|
||||
decoration_state,
|
||||
output_mgmt,
|
||||
pending_configs: vec![],
|
||||
popups: PopupManager::default(),
|
||||
seat,
|
||||
space: Space::default(),
|
||||
session: None,
|
||||
output: None,
|
||||
wins: vec![],
|
||||
registered: Default::default(),
|
||||
serial: 0,
|
||||
target: Target::Launcher,
|
||||
target_at: Instant::now(),
|
||||
held: None,
|
||||
hold_poll: false,
|
||||
visible: None,
|
||||
transition: None,
|
||||
osd: None,
|
||||
osd_bg: SolidColorBuffer::default(),
|
||||
osd_track: SolidColorBuffer::default(),
|
||||
osd_fill: SolidColorBuffer::default(),
|
||||
screen_on: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn output_size(&self) -> Size<i32, Physical> {
|
||||
self.output
|
||||
.as_ref()
|
||||
.and_then(|o| o.current_mode())
|
||||
.map(|m| m.size)
|
||||
.unwrap_or_else(|| (1920, 1080).into())
|
||||
}
|
||||
|
||||
/// A new or changed output: everyone gets its size.
|
||||
pub fn set_output(&mut self, output: Option<Output>) {
|
||||
if let Some(old) = self.output.take() {
|
||||
self.space.unmap_output(&old);
|
||||
}
|
||||
if let Some(o) = &output {
|
||||
self.space.map_output(o, (0, 0));
|
||||
}
|
||||
self.output = output;
|
||||
self.reconfigure_all();
|
||||
self.output_mgmt_refresh();
|
||||
}
|
||||
|
||||
pub fn reconfigure_all(&mut self) {
|
||||
let wins: Vec<Window> = self.wins.iter().map(|w| w.window.clone()).collect();
|
||||
for w in wins {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
/// Full screen at the output size; activated if visible.
|
||||
fn configure(&self, window: &Window) {
|
||||
let Some(toplevel) = window.toplevel() else { return };
|
||||
let size = self.output_size();
|
||||
let active = self.visible.as_ref() == Some(window);
|
||||
toplevel.with_pending_state(|s| {
|
||||
s.size = Some((size.w, size.h).into());
|
||||
s.states.set(xdg_toplevel::State::Fullscreen);
|
||||
if active {
|
||||
s.states.set(xdg_toplevel::State::Activated);
|
||||
} else {
|
||||
s.states.unset(xdg_toplevel::State::Activated);
|
||||
}
|
||||
s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
|
||||
});
|
||||
if toplevel.is_initial_configure_sent() {
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
}
|
||||
|
||||
fn win_of(&self, window: &Window) -> Option<&Win> {
|
||||
self.wins.iter().find(|w| &w.window == window)
|
||||
}
|
||||
|
||||
pub fn app_of_window(&self, window: &Window) -> Option<String> {
|
||||
self.win_of(window).and_then(|w| w.app.clone())
|
||||
}
|
||||
|
||||
fn find_visible(&self) -> Option<Window> {
|
||||
let pick = |pred: &dyn Fn(&Win) -> bool| {
|
||||
self.wins.iter().filter(|w| w.mapped && pred(w)).max_by_key(|w| w.serial).map(|w| w.window.clone())
|
||||
};
|
||||
let launcher = || pick(&|w| w.app.is_none());
|
||||
match &self.target {
|
||||
Target::App(id) => pick(&|w| w.app.as_deref() == Some(id.as_str())).or_else(launcher),
|
||||
Target::Launcher => launcher(),
|
||||
}
|
||||
.or_else(|| pick(&|_| true))
|
||||
}
|
||||
|
||||
/// sf-core started an app in process group `pgid`. Windows that showed
|
||||
/// up before this arrived are reassigned.
|
||||
pub fn register(&mut self, pgid: i32, app: String) {
|
||||
self.registered.retain(|g, _| std::path::Path::new(&format!("/proc/{g}")).exists());
|
||||
self.registered.insert(pgid, app.clone());
|
||||
let mut changed = false;
|
||||
for w in self.wins.iter_mut() {
|
||||
if w.app.is_none() && w.pid.and_then(pgid_of) == Some(pgid) {
|
||||
tracing::info!("window of pid {:?} belongs to {app}", w.pid);
|
||||
w.app = Some(app.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.update_visible();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_target(&mut self, target: Target) {
|
||||
tracing::info!("focus {target:?}");
|
||||
if target != self.target {
|
||||
self.target_at = Instant::now();
|
||||
}
|
||||
self.target = target;
|
||||
self.update_visible();
|
||||
}
|
||||
|
||||
/// Recomputes the visible window; animates the change.
|
||||
pub fn update_visible(&mut self) {
|
||||
let new = self.find_visible();
|
||||
if self.held.is_some() && self.held != new {
|
||||
self.held = None;
|
||||
}
|
||||
if new == self.visible {
|
||||
return;
|
||||
}
|
||||
if let Some(wait) = new.as_ref().and_then(|n| self.reveal_wait(n)) {
|
||||
// Not yet: the launcher's splash stays up (and keeps the focus,
|
||||
// so Back still cancels). The app gets frame callbacks meanwhile.
|
||||
self.held = new;
|
||||
self.poll_held(wait.min(HOLD_POLL));
|
||||
return;
|
||||
}
|
||||
self.held = None;
|
||||
let old = self.visible.take();
|
||||
let to_launcher = new.as_ref().is_some_and(|w| self.app_of_window(w).is_none());
|
||||
let from_app = old.as_ref().is_some_and(|w| self.app_of_window(w).is_some());
|
||||
self.transition = match (&old, &new) {
|
||||
// Home: the app shrinks away, revealing the launcher.
|
||||
(Some(o), Some(n)) if to_launcher && from_app && o.alive() => Some(Transition {
|
||||
over: o.clone(),
|
||||
under: Some(n.clone()),
|
||||
start: Instant::now(),
|
||||
duration: LEAVE,
|
||||
entering: false,
|
||||
}),
|
||||
(o, Some(n)) => Some(Transition {
|
||||
over: n.clone(),
|
||||
under: o.clone().filter(|w| w.alive()),
|
||||
start: Instant::now(),
|
||||
duration: ENTER,
|
||||
entering: true,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
self.visible = new.clone();
|
||||
tracing::info!(
|
||||
"visible: {}",
|
||||
match &new {
|
||||
Some(w) => self.app_of_window(w).unwrap_or_else(|| "launcher".into()),
|
||||
None => "nothing".into(),
|
||||
}
|
||||
);
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let focus = new.as_ref().and_then(|w| w.toplevel()).map(|t| t.wl_surface().clone());
|
||||
if let Some(kb) = self.seat.get_keyboard() {
|
||||
kb.set_focus(self, focus, serial);
|
||||
}
|
||||
for w in [old, new].into_iter().flatten() {
|
||||
w.set_activated(self.visible.as_ref() == Some(&w));
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long an app window should stay hidden: until the launcher's morph
|
||||
/// is done (when it comes up over the launcher), it has drawn for a
|
||||
/// moment, and its page has loaded (or that timed out).
|
||||
fn reveal_wait(&self, window: &Window) -> Option<Duration> {
|
||||
let win = self.win_of(window)?;
|
||||
win.app.as_ref()?;
|
||||
let mapped_at = win.mapped_at?;
|
||||
let over_launcher = self.visible.as_ref().is_some_and(|v| self.app_of_window(v).is_none());
|
||||
let mut ready_at = mapped_at + SETTLE;
|
||||
if over_launcher {
|
||||
ready_at = ready_at.max(self.target_at + MORPH);
|
||||
}
|
||||
if !page_loaded(window) {
|
||||
ready_at = ready_at.max(mapped_at + LOAD_TIMEOUT);
|
||||
}
|
||||
let now = Instant::now();
|
||||
(ready_at > now).then(|| ready_at - now)
|
||||
}
|
||||
|
||||
fn poll_held(&mut self, after: Duration) {
|
||||
if self.hold_poll {
|
||||
return;
|
||||
}
|
||||
self.hold_poll = true;
|
||||
let _ = self.handle.insert_source(Timer::from_duration(after), |_, _, app: &mut App| {
|
||||
app.state.hold_poll = false;
|
||||
if app.state.held.is_some() {
|
||||
app.state.update_visible();
|
||||
}
|
||||
TimeoutAction::Drop
|
||||
});
|
||||
}
|
||||
|
||||
fn surface_window(&self, surface: &WlSurface) -> Option<Window> {
|
||||
self.wins.iter().find(|w| w.window.toplevel().is_some_and(|t| t.wl_surface() == surface)).map(|w| w.window.clone())
|
||||
}
|
||||
|
||||
// ---- input ----------------------------------------------------------
|
||||
|
||||
pub fn handle_input<B: InputBackend>(&mut self, event: InputEvent<B>) {
|
||||
let InputEvent::Keyboard { event } = event else { return };
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let time = Event::time_msec(&event);
|
||||
let pressed = event.state() == KeyState::Pressed;
|
||||
let Some(kb) = self.seat.get_keyboard() else { return };
|
||||
enum Action {
|
||||
Home,
|
||||
Volume(i32),
|
||||
Mute,
|
||||
Vt(i32),
|
||||
Quit,
|
||||
/// 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 code = key.raw_code().raw();
|
||||
let sym = key.modified_sym().raw();
|
||||
let hit = match code {
|
||||
KEY_HOMEPAGE => Some(Action::Home),
|
||||
KEY_VOLUMEUP => Some(Action::Volume(5)),
|
||||
KEY_VOLUMEDOWN => Some(Action::Volume(-5)),
|
||||
KEY_MUTE => Some(Action::Mute),
|
||||
_ if (keysyms::KEY_XF86Switch_VT_1..=keysyms::KEY_XF86Switch_VT_12).contains(&sym) => {
|
||||
Some(Action::Vt((sym - keysyms::KEY_XF86Switch_VT_1 + 1) as i32))
|
||||
}
|
||||
_ if mods.ctrl && mods.alt && sym == keysyms::KEY_BackSpace => Some(Action::Quit),
|
||||
_ => None,
|
||||
};
|
||||
match hit {
|
||||
Some(a) if pressed => FilterResult::Intercept(a),
|
||||
// Swallow the release (and repeats) of keys we handle.
|
||||
Some(_) => FilterResult::Intercept(Action::Swallow),
|
||||
None => FilterResult::Forward,
|
||||
}
|
||||
});
|
||||
match action {
|
||||
Some(Action::Home) => send_home(),
|
||||
Some(Action::Volume(d)) => self.change_volume(Some(d)),
|
||||
Some(Action::Mute) => self.change_volume(None),
|
||||
Some(Action::Vt(n)) => {
|
||||
if let Some(s) = self.session.as_mut() {
|
||||
if let Err(e) = s.change_vt(n) {
|
||||
tracing::warn!("change vt {n}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Action::Quit) => {
|
||||
tracing::info!("ctrl+alt+backspace: quitting");
|
||||
self.loop_signal.stop();
|
||||
}
|
||||
Some(Action::Swallow) | None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)>();
|
||||
std::thread::spawn(move || {
|
||||
let sink = "@DEFAULT_AUDIO_SINK@";
|
||||
let _ = match delta {
|
||||
Some(d) => {
|
||||
let arg = format!("{}%{}", d.abs(), if d > 0 { "+" } else { "-" });
|
||||
std::process::Command::new("wpctl").args(["set-mute", sink, "0"]).status().ok();
|
||||
std::process::Command::new("wpctl").args(["set-volume", "-l", "1.0", sink, &arg]).status()
|
||||
}
|
||||
None => std::process::Command::new("wpctl").args(["set-mute", sink, "toggle"]).status(),
|
||||
};
|
||||
let out = std::process::Command::new("wpctl").args(["get-volume", sink]).output();
|
||||
let text = out.map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();
|
||||
// "Volume: 0.45" or "Volume: 0.45 [MUTED]"
|
||||
let level = text.split_whitespace().nth(1).and_then(|v| v.parse::<f32>().ok()).unwrap_or(0.0);
|
||||
let _ = tx.send((level, text.contains("MUTED")));
|
||||
});
|
||||
let _ = self.handle.insert_source(rx, |ev, _, app: &mut App| {
|
||||
if let smithay::reexports::calloop::channel::Event::Msg((level, muted)) = ev {
|
||||
app.state.osd = Some(Osd { level, muted, until: Instant::now() + OSD_TIME });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- rendering ------------------------------------------------------
|
||||
|
||||
fn window_elements(&self, renderer: &mut GlesRenderer, window: &Window, alpha: f32) -> Vec<WaylandSurfaceRenderElement<GlesRenderer>> {
|
||||
let origin: Point<i32, Logical> = (0, 0).into();
|
||||
let loc: Point<i32, Physical> = (origin - window.geometry().loc).to_physical_precise_round(1.0);
|
||||
window.render_elements(renderer, loc, Scale::from(1.0), alpha)
|
||||
}
|
||||
|
||||
/// Render elements, front to back.
|
||||
pub fn elements(&mut self, renderer: &mut GlesRenderer) -> Vec<SfElement> {
|
||||
let mut out: Vec<SfElement> = vec![];
|
||||
if !self.screen_on {
|
||||
return out;
|
||||
}
|
||||
let size = self.output_size();
|
||||
let now = Instant::now();
|
||||
|
||||
// Volume OSD: a pill near the bottom with a level bar.
|
||||
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());
|
||||
} else {
|
||||
self.osd = None;
|
||||
}
|
||||
}
|
||||
|
||||
let done = self.transition.as_ref().is_some_and(|t| now - t.start >= t.duration || !t.over.alive());
|
||||
if done {
|
||||
self.transition = None;
|
||||
}
|
||||
let center: Point<i32, Physical> = (size.w / 2, size.h / 2).into();
|
||||
match &self.transition {
|
||||
Some(t) => {
|
||||
let x = (now - t.start).as_secs_f32() / t.duration.as_secs_f32();
|
||||
let (fade, grow) = (ease_in_out(x), ease_out(x));
|
||||
let (alpha, scale) = if t.entering { (fade, 0.965 + 0.035 * grow) } else { (1.0 - fade, 1.0 - 0.05 * grow) };
|
||||
let over = t.over.clone();
|
||||
let under = t.under.clone();
|
||||
for el in self.window_elements(renderer, &over, alpha) {
|
||||
out.push(RescaleRenderElement::from_element(el, center, scale as f64).into());
|
||||
}
|
||||
if let Some(u) = under.filter(|u| u.alive()) {
|
||||
out.extend(self.window_elements(renderer, &u, 1.0).into_iter().map(SfElement::from));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(v) = self.visible.clone() {
|
||||
out.extend(self.window_elements(renderer, &v, 1.0).into_iter().map(SfElement::from));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Frame callbacks for what is on screen (hidden apps get none, so they idle).
|
||||
pub fn send_frames(&self) {
|
||||
let Some(output) = self.output.as_ref() else { return };
|
||||
let time = self.start.elapsed();
|
||||
// The held-back app draws too, so its page is ready when it shows.
|
||||
let mut shown: Vec<&Window> = self.visible.iter().chain(self.held.iter()).collect();
|
||||
if let Some(t) = &self.transition {
|
||||
shown.push(&t.over);
|
||||
shown.extend(t.under.iter());
|
||||
}
|
||||
for w in shown {
|
||||
w.send_frame(output, time, Some(Duration::ZERO), |_, _| Some(output.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output_mgmt_refresh(&mut self) {
|
||||
let info = crate::output_mgmt::HeadInfo::from_state(self);
|
||||
self.output_mgmt.update(&self.dh, info);
|
||||
}
|
||||
|
||||
fn unconstrain_popup(&self, popup: &PopupSurface) {
|
||||
let Ok(root) = find_popup_root_surface(&PopupKind::Xdg(popup.clone())) else { return };
|
||||
let Some(window) = self.surface_window(&root) else { return };
|
||||
let size = self.output_size();
|
||||
let mut target = Rectangle::new((0, 0).into(), (size.w, size.h).into());
|
||||
target.loc -= get_popup_toplevel_coords(&PopupKind::Xdg(popup.clone()));
|
||||
target.loc += window.geometry().loc;
|
||||
popup.with_pending_state(|state| {
|
||||
state.geometry = state.positioner.get_unconstrained_geometry(target);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher decides what Home means (it tells sf-core).
|
||||
pub fn send_home() {
|
||||
std::thread::spawn(|| {
|
||||
let path = sf_ipc::paths::launcher_socket();
|
||||
match std::os::unix::net::UnixStream::connect(&path) {
|
||||
Ok(mut s) => {
|
||||
let _ = s.write_all(b"home\n");
|
||||
}
|
||||
Err(e) => tracing::warn!("home: {}: {e}", path.display()),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- protocol handlers ------------------------------------------------------
|
||||
|
||||
impl CompositorHandler for State {
|
||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||
&mut self.compositor_state
|
||||
}
|
||||
|
||||
fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
|
||||
&client.get_data::<ClientState>().unwrap().compositor_state
|
||||
}
|
||||
|
||||
fn commit(&mut self, surface: &WlSurface) {
|
||||
on_commit_buffer_handler::<Self>(surface);
|
||||
if !is_sync_subsurface(surface) {
|
||||
let mut root = surface.clone();
|
||||
while let Some(parent) = get_parent(&root) {
|
||||
root = parent;
|
||||
}
|
||||
if let Some(window) = self.surface_window(&root) {
|
||||
window.on_commit();
|
||||
}
|
||||
}
|
||||
|
||||
// Toplevels: initial configure, then "mapped" once a buffer arrives.
|
||||
if let Some(window) = self.surface_window(surface) {
|
||||
let toplevel = window.toplevel().unwrap();
|
||||
let initial_sent = with_states(surface, |states| {
|
||||
states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.map(|d| d.lock().unwrap().initial_configure_sent)
|
||||
.unwrap_or(true)
|
||||
});
|
||||
if !initial_sent {
|
||||
self.configure(&window);
|
||||
toplevel.send_configure();
|
||||
}
|
||||
let has_buffer = window.bbox().size.w > 0;
|
||||
let newly_mapped = match self.wins.iter_mut().find(|w| w.window == window) {
|
||||
Some(w) if !w.mapped && has_buffer => {
|
||||
w.mapped = true;
|
||||
w.mapped_at = Some(Instant::now());
|
||||
Some(w.app.clone())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(app) = newly_mapped {
|
||||
tracing::info!("mapped: {}", app.as_deref().unwrap_or("launcher"));
|
||||
match app {
|
||||
// A new app window comes to the front (like cage).
|
||||
Some(id) => self.set_target(Target::App(id)),
|
||||
None => self.update_visible(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.popups.commit(surface);
|
||||
if let Some(PopupKind::Xdg(xdg)) = self.popups.find_popup(surface) {
|
||||
if !xdg.is_initial_configure_sent() {
|
||||
let _ = xdg.send_configure();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BufferHandler for State {
|
||||
fn buffer_destroyed(&mut self, _buffer: &wl_buffer::WlBuffer) {}
|
||||
}
|
||||
|
||||
impl ShmHandler for State {
|
||||
fn shm_state(&self) -> &ShmState {
|
||||
&self.shm_state
|
||||
}
|
||||
}
|
||||
|
||||
impl XdgShellHandler for State {
|
||||
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
|
||||
&mut self.xdg_shell_state
|
||||
}
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
let pid = surface.wl_surface().client().and_then(|c| c.get_credentials(&self.dh).ok()).map(|c| c.pid);
|
||||
let app = pid.and_then(|p| app_of_pid(p, &self.registered));
|
||||
tracing::info!("new window: pid {pid:?}, app {}", app.as_deref().unwrap_or("launcher"));
|
||||
let window = Window::new_wayland_window(surface);
|
||||
self.space.map_element(window.clone(), (0, 0), false);
|
||||
self.serial += 1;
|
||||
self.wins.push(Win { window: window.clone(), app, pid, mapped: false, mapped_at: None, serial: self.serial });
|
||||
self.configure(&window);
|
||||
}
|
||||
|
||||
fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
|
||||
let Some(window) = self.surface_window(surface.wl_surface()) else { return };
|
||||
tracing::info!("window closed: {}", self.app_of_window(&window).unwrap_or_else(|| "launcher".into()));
|
||||
self.space.unmap_elem(&window);
|
||||
self.wins.retain(|w| w.window != window);
|
||||
if self.transition.as_ref().is_some_and(|t| t.over == window || t.under.as_ref() == Some(&window)) {
|
||||
self.transition = None;
|
||||
}
|
||||
if self.held.as_ref() == Some(&window) {
|
||||
self.held = None;
|
||||
}
|
||||
if self.visible.as_ref() == Some(&window) {
|
||||
self.visible = None;
|
||||
// The app is gone: back to the launcher unless sf-core says otherwise.
|
||||
if let Target::App(id) = &self.target {
|
||||
if !self.wins.iter().any(|w| w.mapped && w.app.as_deref() == Some(id.as_str())) {
|
||||
self.target = Target::Launcher;
|
||||
}
|
||||
}
|
||||
self.update_visible();
|
||||
}
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) {
|
||||
self.unconstrain_popup(&surface);
|
||||
let _ = self.popups.track_popup(PopupKind::Xdg(surface));
|
||||
}
|
||||
|
||||
fn reposition_request(&mut self, surface: PopupSurface, positioner: PositionerState, token: u32) {
|
||||
surface.with_pending_state(|state| {
|
||||
state.geometry = positioner.get_geometry();
|
||||
state.positioner = positioner;
|
||||
});
|
||||
self.unconstrain_popup(&surface);
|
||||
surface.send_repositioned(token);
|
||||
}
|
||||
|
||||
fn grab(&mut self, _surface: PopupSurface, _seat: wl_seat::WlSeat, _serial: Serial) {}
|
||||
|
||||
fn fullscreen_request(&mut self, surface: ToplevelSurface, _output: Option<wl_output::WlOutput>) {
|
||||
if let Some(w) = self.surface_window(surface.wl_surface()) {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
fn unfullscreen_request(&mut self, surface: ToplevelSurface) {
|
||||
if let Some(w) = self.surface_window(surface.wl_surface()) {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
fn maximize_request(&mut self, surface: ToplevelSurface) {
|
||||
if let Some(w) = self.surface_window(surface.wl_surface()) {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl XdgDecorationHandler for State {
|
||||
fn new_decoration(&mut self, toplevel: ToplevelSurface) {
|
||||
toplevel.with_pending_state(|s| s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide));
|
||||
}
|
||||
fn request_mode(&mut self, toplevel: ToplevelSurface, _mode: zxdg_toplevel_decoration_v1::Mode) {
|
||||
toplevel.with_pending_state(|s| s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide));
|
||||
if toplevel.is_initial_configure_sent() {
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
}
|
||||
fn unset_mode(&mut self, toplevel: ToplevelSurface) {
|
||||
self.request_mode(toplevel, zxdg_toplevel_decoration_v1::Mode::ServerSide);
|
||||
}
|
||||
}
|
||||
|
||||
impl SeatHandler for State {
|
||||
type KeyboardFocus = WlSurface;
|
||||
type PointerFocus = WlSurface;
|
||||
type TouchFocus = WlSurface;
|
||||
|
||||
fn seat_state(&mut self) -> &mut SeatState<State> {
|
||||
&mut self.seat_state
|
||||
}
|
||||
|
||||
fn focus_changed(&mut self, seat: &Seat<Self>, focused: Option<&WlSurface>) {
|
||||
let client = focused.and_then(|s| self.dh.get_client(s.id()).ok());
|
||||
set_data_device_focus(&self.dh, seat, client);
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectionHandler for State {
|
||||
type SelectionUserData = ();
|
||||
}
|
||||
|
||||
impl DataDeviceHandler for State {
|
||||
fn data_device_state(&self) -> &DataDeviceState {
|
||||
&self.data_device_state
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientDndGrabHandler for State {}
|
||||
impl ServerDndGrabHandler for State {}
|
||||
|
||||
impl OutputHandler for State {}
|
||||
|
||||
impl DmabufHandler for State {
|
||||
fn dmabuf_state(&mut self) -> &mut DmabufState {
|
||||
&mut self.dmabuf_state
|
||||
}
|
||||
|
||||
fn dmabuf_imported(
|
||||
&mut self,
|
||||
_global: &DmabufGlobal,
|
||||
_dmabuf: smithay::backend::allocator::dmabuf::Dmabuf,
|
||||
notifier: ImportNotifier,
|
||||
) {
|
||||
// Formats come from the renderer; a bad buffer shows up when drawn.
|
||||
let _ = notifier.successful::<State>();
|
||||
}
|
||||
}
|
||||
|
||||
delegate_compositor!(State);
|
||||
delegate_shm!(State);
|
||||
delegate_xdg_shell!(State);
|
||||
delegate_xdg_decoration!(State);
|
||||
delegate_seat!(State);
|
||||
delegate_data_device!(State);
|
||||
delegate_output!(State);
|
||||
delegate_dmabuf!(State);
|
||||
delegate_viewporter!(State);
|
||||
391
crates/sf-compositor/src/udev.rs
Normal file
391
crates/sf-compositor/src/udev.rs
Normal file
@@ -0,0 +1,391 @@
|
||||
//! DRM/KMS backend for the TV: libseat session, one GPU, the first
|
||||
//! connected output (HDMI), libinput keyboards. Handles HDMI hotplug, VT
|
||||
//! switching, mode changes and turning the screen off (wlr-randr).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
|
||||
use smithay::backend::drm::compositor::FrameFlags;
|
||||
use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter;
|
||||
use smithay::backend::drm::output::{DrmOutput, DrmOutputManager, DrmOutputRenderElements};
|
||||
use smithay::backend::drm::{DrmDevice, DrmDeviceFd, DrmEvent, DrmNode};
|
||||
use smithay::backend::egl::{EGLContext, EGLDevice, EGLDisplay};
|
||||
use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface};
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::{ImportDma, ImportMemWl};
|
||||
use smithay::backend::session::libseat::LibSeatSession;
|
||||
use smithay::backend::session::{Event as SessionEvent, Session};
|
||||
use smithay::backend::udev::{UdevBackend, UdevEvent, all_gpus, primary_gpu};
|
||||
use smithay::output::{Mode as WlMode, Output, PhysicalProperties, Subpixel};
|
||||
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::reexports::drm::control::{Device as ControlDevice, ModeTypeFlags, connector, crtc};
|
||||
use smithay::reexports::input::Libinput;
|
||||
use smithay::reexports::rustix::fs::OFlags;
|
||||
use smithay::reexports::wayland_server::backend::GlobalId;
|
||||
use smithay::utils::DeviceFd;
|
||||
use smithay::wayland::dmabuf::DmabufFeedbackBuilder;
|
||||
|
||||
use crate::output_mgmt::{ModeInfo, OutputModes, PendingConfig, match_mode};
|
||||
use crate::state::{App, Backend, SfElement, State};
|
||||
|
||||
type Allocator = GbmAllocator<DrmDeviceFd>;
|
||||
type Exporter = GbmFramebufferExporter<DrmDeviceFd>;
|
||||
|
||||
const FORMATS: &[Fourcc] = &[Fourcc::Argb8888, Fourcc::Abgr8888, Fourcc::Xrgb8888];
|
||||
|
||||
struct Out {
|
||||
drm_output: DrmOutput<Allocator, Exporter, (), DrmDeviceFd>,
|
||||
connector: connector::Handle,
|
||||
crtc: crtc::Handle,
|
||||
modes: Vec<smithay::reexports::drm::control::Mode>,
|
||||
output: Output,
|
||||
global: Option<GlobalId>,
|
||||
frame_pending: bool,
|
||||
/// The CRTC is off (DPMS) after wlr-randr --off.
|
||||
cleared: bool,
|
||||
}
|
||||
|
||||
pub struct UdevData {
|
||||
/// Keeps the seat session (and device access) alive.
|
||||
_session: LibSeatSession,
|
||||
libinput: Libinput,
|
||||
manager: DrmOutputManager<Allocator, Exporter, (), DrmDeviceFd>,
|
||||
renderer: GlesRenderer,
|
||||
out: Option<Out>,
|
||||
active: bool,
|
||||
/// A render is queued on a timer (no damage last time).
|
||||
retry_scheduled: bool,
|
||||
}
|
||||
|
||||
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")?;
|
||||
tracing::info!("GPU {}", path.display());
|
||||
let mut session_for_open = session.clone();
|
||||
let fd = session_for_open
|
||||
.open(&path, OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK)
|
||||
.map_err(|e| anyhow!("opening {}: {e}", path.display()))?;
|
||||
let fd = DrmDeviceFd::new(DeviceFd::from(fd));
|
||||
let (drm, drm_notifier) = DrmDevice::new(fd.clone(), true).map_err(|e| anyhow!("drm: {e}"))?;
|
||||
let gbm = GbmDevice::new(fd).context("gbm")?;
|
||||
let node = DrmNode::from_path(&path).map_err(|e| anyhow!("drm node: {e}"))?;
|
||||
|
||||
let egl = unsafe { EGLDisplay::new(gbm.clone()) }.map_err(|e| anyhow!("egl display: {e}"))?;
|
||||
let render_node = EGLDevice::device_for_display(&egl)
|
||||
.ok()
|
||||
.and_then(|d| d.try_get_render_node().ok().flatten())
|
||||
.unwrap_or(node);
|
||||
let ctx = EGLContext::new(&egl).map_err(|e| anyhow!("egl context: {e}"))?;
|
||||
let renderer = unsafe { GlesRenderer::new(ctx) }.map_err(|e| anyhow!("gles: {e}"))?;
|
||||
|
||||
state.shm_state.update_formats(renderer.shm_formats());
|
||||
let dmabuf_formats = renderer.dmabuf_formats();
|
||||
let feedback = DmabufFeedbackBuilder::new(render_node.dev_id(), dmabuf_formats.clone())
|
||||
.build()
|
||||
.map_err(|e| anyhow!("dmabuf feedback: {e}"))?;
|
||||
state.dmabuf_global = Some(state.dmabuf_state.create_global_with_default_feedback::<State>(&state.dh, &feedback));
|
||||
|
||||
let render_formats = renderer.egl_context().dmabuf_render_formats().clone();
|
||||
let allocator = GbmAllocator::new(gbm.clone(), GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT);
|
||||
let exporter = GbmFramebufferExporter::new(gbm.clone(), Some(render_node));
|
||||
let manager = DrmOutputManager::new(drm, allocator, exporter, Some(gbm), FORMATS.iter().copied(), render_formats);
|
||||
|
||||
// Input.
|
||||
let mut libinput = Libinput::new_with_udev::<LibinputSessionInterface<LibSeatSession>>(session.clone().into());
|
||||
libinput.udev_assign_seat(&seat).map_err(|_| anyhow!("libinput: assigning seat {seat}"))?;
|
||||
let handle = event_loop.handle();
|
||||
handle
|
||||
.insert_source(LibinputInputBackend::new(libinput.clone()), |event, _, app: &mut App| {
|
||||
app.state.handle_input(event);
|
||||
})
|
||||
.map_err(|e| anyhow!("libinput source: {e}"))?;
|
||||
|
||||
// Vblanks.
|
||||
handle
|
||||
.insert_source(drm_notifier, |event, _, app: &mut App| match event {
|
||||
DrmEvent::VBlank(_crtc) => {
|
||||
if let Backend::Udev(u) = &mut app.backend {
|
||||
u.frame_done(&mut app.state);
|
||||
}
|
||||
}
|
||||
DrmEvent::Error(e) => tracing::error!("drm: {e:?}"),
|
||||
})
|
||||
.map_err(|e| anyhow!("drm source: {e}"))?;
|
||||
|
||||
// VT switches.
|
||||
handle
|
||||
.insert_source(notifier, |event, _, app: &mut App| {
|
||||
let Backend::Udev(u) = &mut app.backend else { return };
|
||||
match event {
|
||||
SessionEvent::PauseSession => {
|
||||
tracing::info!("session paused");
|
||||
u.libinput.suspend();
|
||||
u.manager.pause();
|
||||
u.active = false;
|
||||
}
|
||||
SessionEvent::ActivateSession => {
|
||||
tracing::info!("session active");
|
||||
if u.libinput.resume().is_err() {
|
||||
tracing::error!("libinput resume failed");
|
||||
}
|
||||
if let Err(e) = u.manager.activate(false) {
|
||||
tracing::error!("drm activate: {e}");
|
||||
}
|
||||
u.active = true;
|
||||
if let Some(out) = u.out.as_mut() {
|
||||
out.frame_pending = false;
|
||||
out.drm_output.reset_buffers();
|
||||
}
|
||||
u.render(&mut app.state);
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow!("session source: {e}"))?;
|
||||
|
||||
// HDMI hotplug: rescan connectors when the GPU reports a change.
|
||||
let udev = UdevBackend::new(&seat)?;
|
||||
handle
|
||||
.insert_source(udev, |event, _, app: &mut App| {
|
||||
if let UdevEvent::Changed { .. } = event {
|
||||
if let Backend::Udev(u) = &mut app.backend {
|
||||
u.scan(&mut app.state);
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow!("udev source: {e}"))?;
|
||||
|
||||
let mut data = UdevData { _session: session, libinput, manager, renderer, out: None, active: true, retry_scheduled: false };
|
||||
data.scan(state);
|
||||
if data.out.is_none() {
|
||||
tracing::warn!("no connected display yet; waiting for hotplug");
|
||||
}
|
||||
Ok(Backend::Udev(data))
|
||||
}
|
||||
|
||||
fn mode_info(m: &smithay::reexports::drm::control::Mode) -> ModeInfo {
|
||||
let wl = WlMode::from(*m);
|
||||
ModeInfo {
|
||||
width: wl.size.w,
|
||||
height: wl.size.h,
|
||||
refresh: wl.refresh,
|
||||
preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED),
|
||||
}
|
||||
}
|
||||
|
||||
impl UdevData {
|
||||
/// First connected connector and a CRTC for it.
|
||||
fn find_connector(&self) -> Option<(connector::Info, crtc::Handle)> {
|
||||
let dev = self.manager.device();
|
||||
let res = dev.resource_handles().ok()?;
|
||||
for handle in res.connectors() {
|
||||
let Ok(info) = dev.get_connector(*handle, false) else { continue };
|
||||
if info.state() != connector::State::Connected || info.modes().is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Keep the CRTC we already drive for this connector.
|
||||
if let Some(out) = &self.out {
|
||||
if out.connector == *handle {
|
||||
return Some((info, out.crtc));
|
||||
}
|
||||
}
|
||||
for enc in info.encoders() {
|
||||
let Ok(enc) = dev.get_encoder(*enc) else { continue };
|
||||
if let Some(crtc) = res.filter_crtcs(enc.possible_crtcs()).into_iter().next() {
|
||||
return Some((info, crtc));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn scan(&mut self, state: &mut State) {
|
||||
let found = self.find_connector();
|
||||
let same = match (&found, &self.out) {
|
||||
(Some((info, _)), Some(out)) => info.handle() == out.connector,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if same {
|
||||
return;
|
||||
}
|
||||
if let Some(out) = self.out.take() {
|
||||
tracing::info!("display disconnected: {}", out.output.name());
|
||||
if let Some(g) = out.global {
|
||||
state.dh.remove_global::<State>(g);
|
||||
}
|
||||
state.set_output(None);
|
||||
}
|
||||
let Some((info, crtc)) = found else { return };
|
||||
if let Err(e) = self.setup_output(state, &info, crtc) {
|
||||
tracing::error!("display setup: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_output(&mut self, state: &mut State, info: &connector::Info, crtc: crtc::Handle) -> Result<()> {
|
||||
let name = format!("{}-{}", info.interface().as_str(), info.interface_id());
|
||||
let modes = info.modes().to_vec();
|
||||
let mode = *modes.iter().find(|m| m.mode_type().contains(ModeTypeFlags::PREFERRED)).unwrap_or(&modes[0]);
|
||||
let wl_mode = WlMode::from(mode);
|
||||
let (pw, ph) = info.size().unwrap_or((0, 0));
|
||||
let output = Output::new(
|
||||
name.clone(),
|
||||
PhysicalProperties {
|
||||
size: (pw as i32, ph as i32).into(),
|
||||
subpixel: Subpixel::Unknown,
|
||||
make: "TV".into(),
|
||||
model: name.clone(),
|
||||
},
|
||||
);
|
||||
let global = output.create_global::<State>(&state.dh);
|
||||
output.set_preferred(wl_mode);
|
||||
output.change_current_state(Some(wl_mode), None, None, Some((0, 0).into()));
|
||||
*output.user_data().get_or_insert(OutputModes::default).0.lock().unwrap() = modes.iter().map(mode_info).collect();
|
||||
|
||||
let drm_output = self
|
||||
.manager
|
||||
.initialize_output::<_, SfElement>(
|
||||
crtc,
|
||||
mode,
|
||||
&[info.handle()],
|
||||
&output,
|
||||
None,
|
||||
&mut self.renderer,
|
||||
&DrmOutputRenderElements::default(),
|
||||
)
|
||||
.map_err(|e| anyhow!("initializing {name}: {e:?}"))?;
|
||||
tracing::info!("display {name}: {}x{}@{:.2}", wl_mode.size.w, wl_mode.size.h, wl_mode.refresh as f32 / 1000.0);
|
||||
self.out = Some(Out {
|
||||
drm_output,
|
||||
connector: info.handle(),
|
||||
crtc,
|
||||
modes,
|
||||
output: output.clone(),
|
||||
global: Some(global),
|
||||
frame_pending: false,
|
||||
cleared: false,
|
||||
});
|
||||
state.set_output(Some(output));
|
||||
self.render(state);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called after every dispatch: start rendering if nothing is in flight.
|
||||
pub fn kick(&mut self, state: &mut State) {
|
||||
let idle = self.out.as_ref().is_some_and(|o| !o.frame_pending);
|
||||
if idle && !self.retry_scheduled {
|
||||
self.render(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn frame_done(&mut self, state: &mut State) {
|
||||
let Some(out) = self.out.as_mut() else { return };
|
||||
if let Err(e) = out.drm_output.frame_submitted() {
|
||||
tracing::warn!("frame_submitted: {e:?}");
|
||||
}
|
||||
out.frame_pending = false;
|
||||
state.send_frames();
|
||||
self.render(state);
|
||||
}
|
||||
|
||||
fn render(&mut self, state: &mut State) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
let Some(out) = self.out.as_mut() else { return };
|
||||
if out.frame_pending {
|
||||
return;
|
||||
}
|
||||
if !state.screen_on {
|
||||
if !out.cleared {
|
||||
if let Err(e) = out.drm_output.with_compositor(|c| c.clear()) {
|
||||
tracing::warn!("screen off: {e}");
|
||||
}
|
||||
out.cleared = true;
|
||||
tracing::info!("screen off");
|
||||
}
|
||||
// Apps still get (slow) frame callbacks so they don't hang.
|
||||
self.schedule_retry(state, Duration::from_millis(250));
|
||||
return;
|
||||
}
|
||||
if out.cleared {
|
||||
out.cleared = false;
|
||||
out.drm_output.reset_buffers();
|
||||
tracing::info!("screen on");
|
||||
}
|
||||
let elements = state.elements(&mut self.renderer);
|
||||
let rendered = match out.drm_output.render_frame(&mut self.renderer, &elements, [0.0, 0.0, 0.0, 1.0], FrameFlags::DEFAULT) {
|
||||
Ok(r) => !r.is_empty,
|
||||
Err(e) => {
|
||||
tracing::warn!("render: {e:?}");
|
||||
false
|
||||
}
|
||||
};
|
||||
if rendered {
|
||||
match out.drm_output.queue_frame(()) {
|
||||
Ok(()) => out.frame_pending = true,
|
||||
Err(e) => tracing::warn!("queue_frame: {e:?}"),
|
||||
}
|
||||
} else {
|
||||
// Nothing changed: send frame callbacks, look again in a frame.
|
||||
state.send_frames();
|
||||
let frame = out.output.current_mode().map(|m| 1_000_000 / m.refresh.max(1) as u64).unwrap_or(16);
|
||||
self.schedule_retry(state, Duration::from_millis(frame.max(4)));
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_retry(&mut self, state: &mut State, after: Duration) {
|
||||
if self.retry_scheduled {
|
||||
return;
|
||||
}
|
||||
self.retry_scheduled = true;
|
||||
let _ = state.handle.insert_source(Timer::from_duration(after), |_, _, app: &mut App| {
|
||||
if let Backend::Udev(u) = &mut app.backend {
|
||||
u.retry_scheduled = false;
|
||||
if !app.state.screen_on {
|
||||
app.state.send_frames();
|
||||
}
|
||||
u.render(&mut app.state);
|
||||
}
|
||||
TimeoutAction::Drop
|
||||
});
|
||||
}
|
||||
|
||||
pub fn apply_config(&mut self, state: &mut State, cfg: &PendingConfig) -> Result<()> {
|
||||
let Some(out) = self.out.as_mut() else { bail!("no display connected") };
|
||||
let infos: Vec<ModeInfo> = out.modes.iter().map(mode_info).collect();
|
||||
let target = match &cfg.mode {
|
||||
Some(want) => {
|
||||
let (idx, _) = match_mode(&infos, want, cfg.any_refresh)
|
||||
.with_context(|| format!("{}x{}@{} is not offered by the display", want.width, want.height, want.refresh))?;
|
||||
Some(out.modes[idx])
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if cfg.test_only {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(mode) = target {
|
||||
let wl = WlMode::from(mode);
|
||||
if out.output.current_mode() != Some(wl) {
|
||||
out.drm_output
|
||||
.use_mode::<_, SfElement>(mode, &mut self.renderer, &DrmOutputRenderElements::default())
|
||||
.map_err(|e| anyhow!("mode change: {e:?}"))?;
|
||||
out.output.change_current_state(Some(wl), None, None, None);
|
||||
tracing::info!("mode {}x{}@{:.2}", wl.size.w, wl.size.h, wl.refresh as f32 / 1000.0);
|
||||
state.reconfigure_all();
|
||||
}
|
||||
}
|
||||
state.screen_on = cfg.enabled;
|
||||
out.frame_pending = false;
|
||||
self.render(state);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
110
crates/sf-compositor/src/winit.rs
Normal file
110
crates/sf-compositor/src/winit.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
//! Nested backend: the compositor runs in a window of a desktop session
|
||||
//! (WSLg, a Linux desktop). For development only.
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use smithay::backend::renderer::ImportDma;
|
||||
use smithay::backend::renderer::ImportMemWl;
|
||||
use smithay::backend::renderer::damage::OutputDamageTracker;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::winit::{self, WinitEvent, WinitGraphicsBackend};
|
||||
use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::utils::Transform;
|
||||
|
||||
use crate::output_mgmt::{ModeInfo, OutputModes, PendingConfig};
|
||||
use crate::state::{App, Backend, State};
|
||||
|
||||
pub struct WinitData {
|
||||
backend: WinitGraphicsBackend<GlesRenderer>,
|
||||
damage: OutputDamageTracker,
|
||||
output: Output,
|
||||
}
|
||||
|
||||
fn set_modes(output: &Output, mode: Mode) {
|
||||
let modes = output.user_data().get_or_insert(OutputModes::default);
|
||||
*modes.0.lock().unwrap() =
|
||||
vec![ModeInfo { width: mode.size.w, height: mode.size.h, refresh: mode.refresh, preferred: true }];
|
||||
}
|
||||
|
||||
pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result<Backend> {
|
||||
let (mut backend, winit_loop) = winit::init::<GlesRenderer>().map_err(|e| anyhow!("winit: {e:?}"))?;
|
||||
let mode = Mode { size: backend.window_size(), refresh: 60_000 };
|
||||
let output = Output::new(
|
||||
"WINIT-1".into(),
|
||||
PhysicalProperties { size: (0, 0).into(), subpixel: Subpixel::Unknown, make: "Fennec OS".into(), model: "Nested".into() },
|
||||
);
|
||||
let _global = output.create_global::<State>(&state.dh);
|
||||
output.change_current_state(Some(mode), Some(Transform::Flipped180), None, Some((0, 0).into()));
|
||||
output.set_preferred(mode);
|
||||
set_modes(&output, mode);
|
||||
|
||||
state.shm_state.update_formats(backend.renderer().shm_formats());
|
||||
let formats = backend.renderer().dmabuf_formats();
|
||||
state.dmabuf_global = Some(state.dmabuf_state.create_global::<State>(&state.dh, formats));
|
||||
state.set_output(Some(output.clone()));
|
||||
|
||||
let damage = OutputDamageTracker::from_output(&output);
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(winit_loop, |event, _, app: &mut App| match event {
|
||||
WinitEvent::Resized { size, .. } => {
|
||||
let Backend::Winit(w) = &mut app.backend else { return };
|
||||
let mode = Mode { size, refresh: 60_000 };
|
||||
w.output.change_current_state(Some(mode), None, None, None);
|
||||
w.output.set_preferred(mode);
|
||||
set_modes(&w.output, mode);
|
||||
app.state.reconfigure_all();
|
||||
app.state.output_mgmt_refresh();
|
||||
}
|
||||
WinitEvent::Input(event) => app.state.handle_input(event),
|
||||
WinitEvent::Redraw => render(app),
|
||||
WinitEvent::CloseRequested => app.state.loop_signal.stop(),
|
||||
_ => {}
|
||||
})
|
||||
.map_err(|e| anyhow!("winit source: {e}"))?;
|
||||
|
||||
Ok(Backend::Winit(WinitData { backend, damage, output }))
|
||||
}
|
||||
|
||||
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() {
|
||||
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]) {
|
||||
Ok(r) => r.damage.cloned(),
|
||||
Err(e) => {
|
||||
tracing::warn!("render: {e:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("bind: {e:?}");
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(damage) = damage {
|
||||
if let Err(e) = w.backend.submit(Some(&damage)) {
|
||||
tracing::warn!("submit: {e:?}");
|
||||
}
|
||||
}
|
||||
app.state.send_frames();
|
||||
w.backend.window().request_redraw();
|
||||
}
|
||||
|
||||
impl WinitData {
|
||||
pub fn apply_config(&mut self, state: &mut State, cfg: &PendingConfig) -> Result<()> {
|
||||
if let Some(m) = &cfg.mode {
|
||||
let cur = self.backend.window_size();
|
||||
if (m.width, m.height) != (cur.w, cur.h) {
|
||||
bail!("the nested window is {}x{}", cur.w, cur.h);
|
||||
}
|
||||
}
|
||||
if !cfg.test_only {
|
||||
state.screen_on = cfg.enabled;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user