gamescope (which hosts the Steam client) refuses to run nested without
wp_presentation, zwp_relative_pointer_manager_v1 and
zwp_pointer_constraints_v1 ("Couldn't create Wayland objects"), so Steam
quit right away.
- presentation-time with real feedback: on DRM with the page flip's
kernel timestamp and sequence, on winit when the frame is submitted;
- relative pointer and pointer constraints (the seat gets a wl_pointer;
no pointer device is attached, the cursor theme is blank).
Tested in the install VM: gamescope now gets past the Wayland setup; it
stops later only because the VM has no hardware Vulkan (llvmpipe lacks
VK_EXT_physical_device_drm). YouTube (Chromium, which uses presentation
feedback too) still renders and takes input.
Shell 0.3.1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1018 lines
40 KiB
Rust
1018 lines
40 KiB
Rust
//! Compositor state: Wayland protocol handlers, which window is visible,
|
|
//! the switch animation, the volume OSD and the render element list.
|
|
//!
|
|
//! Besides what a kiosk needs, it offers what nested compositors need:
|
|
//! gamescope (which hosts Steam) refuses to start without presentation-time,
|
|
//! relative pointer and pointer constraints (and dmabuf, viewporter).
|
|
|
|
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::utils::OutputPresentationFeedback;
|
|
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::pointer::PointerHandle;
|
|
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::wp::presentation_time::server::wp_presentation_feedback;
|
|
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::{Clock, IsAlive, Logical, Monotonic, 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::pointer_constraints::{PointerConstraintsHandler, PointerConstraintsState};
|
|
use smithay::wayland::presentation::PresentationState;
|
|
use smithay::wayland::relative_pointer::RelativePointerManagerState;
|
|
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_pointer_constraints,
|
|
delegate_presentation, delegate_relative_pointer, 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,
|
|
#[allow(dead_code)]
|
|
pub presentation_state: PresentationState,
|
|
#[allow(dead_code)]
|
|
pub relative_pointer_state: RelativePointerManagerState,
|
|
#[allow(dead_code)]
|
|
pub pointer_constraints_state: PointerConstraintsState,
|
|
/// The clock presentation feedback is given in (CLOCK_MONOTONIC).
|
|
pub clock: Clock<Monotonic>,
|
|
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 clock = Clock::<Monotonic>::new();
|
|
let presentation_state = PresentationState::new::<Self>(&dh, clock.id() as u32);
|
|
let relative_pointer_state = RelativePointerManagerState::new::<Self>(&dh);
|
|
let pointer_constraints_state = PointerConstraintsState::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:?}"))?;
|
|
// No pointer device is ever attached (the cursor theme is blank), but
|
|
// relative pointer and pointer constraints work on a wl_pointer.
|
|
seat.add_pointer();
|
|
|
|
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,
|
|
presentation_state,
|
|
relative_pointer_state,
|
|
pointer_constraints_state,
|
|
clock,
|
|
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
|
|
}
|
|
|
|
/// Windows that get frame callbacks: what is on screen, and the
|
|
/// held-back app (it draws, so its page is ready when it shows).
|
|
fn shown(&self) -> Vec<&Window> {
|
|
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());
|
|
}
|
|
shown
|
|
}
|
|
|
|
/// 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();
|
|
for w in self.shown() {
|
|
w.send_frame(output, time, Some(Duration::ZERO), |_, _| Some(output.clone()));
|
|
}
|
|
}
|
|
|
|
/// Presentation feedback requests of the frame being rendered; answered
|
|
/// when it is on screen (`presented`) or dropped if it never gets there.
|
|
pub fn presentation_feedback(&self) -> Option<OutputPresentationFeedback> {
|
|
let output = self.output.as_ref()?;
|
|
let mut feedback = OutputPresentationFeedback::new(output);
|
|
for w in self.shown() {
|
|
w.take_presentation_feedback(&mut feedback, |_, _| Some(output.clone()), |_, _| wp_presentation_feedback::Kind::Vsync);
|
|
}
|
|
Some(feedback)
|
|
}
|
|
|
|
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 PointerConstraintsHandler for State {
|
|
// There is no pointer to lock or confine; the requests are accepted.
|
|
fn new_constraint(&mut self, _surface: &WlSurface, _pointer: &PointerHandle<Self>) {}
|
|
fn cursor_position_hint(&mut self, _surface: &WlSurface, _pointer: &PointerHandle<Self>, _location: Point<f64, Logical>) {}
|
|
}
|
|
|
|
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);
|
|
delegate_presentation!(State);
|
|
delegate_relative_pointer!(State);
|
|
delegate_pointer_constraints!(State);
|