multi-output support with shared GPU context, drop AUR check()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-08 21:16:22 +02:00
parent 1f9f01a238
commit c5668aee9f
3 changed files with 520 additions and 362 deletions
+284 -159
View File
@@ -1,5 +1,6 @@
//! Wayland state: output enumeration, layer surface creation, event dispatch.
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{bail, Context, Result};
@@ -23,43 +24,94 @@ use wayland_client::{
Connection, Proxy, QueueHandle,
};
use crate::renderer::Renderer;
use crate::renderer::{GpuContext, SurfaceRenderer};
use crate::shader::ShaderSource;
/// Application state held across the Wayland event loop.
pub struct AppState {
// SCTK required fields
registry_state: RegistryState,
output_state: OutputState,
// ---------------------------------------------------------------------------
// Per-output state
// ---------------------------------------------------------------------------
// Layer shell
layer: Option<LayerSurface>,
// Rendering
renderer: Option<Renderer>,
// Configuration that renderer needs at configure time
display_ptr: *mut std::ffi::c_void,
struct OutputSurface {
layer: LayerSurface,
renderer: Option<SurfaceRenderer>,
/// Raw wl_surface pointer passed to SurfaceRenderer.
surface_ptr: *mut std::ffi::c_void,
shader: ShaderSource,
fps: u32,
// Bookkeeping
configured: bool,
width: u32,
height: u32,
pub exit: bool,
// Frame callback: set true when compositor says it's ready for next frame
draw_ready: bool,
last_frame: Instant,
}
// Safety: we only use the raw pointers in single-threaded context
// Safety: raw pointer is only used from the single Wayland thread.
unsafe impl Send for OutputSurface {}
unsafe impl Sync for OutputSurface {}
// ---------------------------------------------------------------------------
// Application state
// ---------------------------------------------------------------------------
pub struct AppState {
registry_state: RegistryState,
output_state: OutputState,
compositor: CompositorState,
layer_shell: LayerShell,
outputs: Vec<OutputSurface>,
/// Created on first configure; shared by all SurfaceRenderers.
gpu: Option<Arc<GpuContext>>,
display_ptr: *mut std::ffi::c_void,
shader: ShaderSource,
fps: u32,
layer_kind: Layer,
/// "all" / "*" → create a surface per output; otherwise match by name.
target_output: String,
frame_duration: Option<Duration>,
pub exit: bool,
}
unsafe impl Send for AppState {}
unsafe impl Sync for AppState {}
/// Parse the layer CLI string into an SCTK Layer.
// ---------------------------------------------------------------------------
// Layer creation helper (also called from new_output for hotplug)
// ---------------------------------------------------------------------------
impl AppState {
fn attach_output(&mut self, qh: &QueueHandle<Self>, wl_out: Option<&wl_output::WlOutput>) {
let surface = self.compositor.create_surface(qh);
let surface_ptr = surface.id().as_ptr() as *mut std::ffi::c_void;
let layer = self.layer_shell.create_layer_surface(
qh,
surface,
self.layer_kind,
Some("gpupaper"),
wl_out,
);
layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
layer.set_exclusive_zone(-1);
layer.set_size(0, 0);
layer.set_keyboard_interactivity(KeyboardInteractivity::None);
layer.commit();
self.outputs.push(OutputSurface {
layer,
renderer: None,
surface_ptr,
width: 0,
height: 0,
draw_ready: false,
last_frame: Instant::now(),
});
}
}
// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------
pub fn parse_layer(s: &str) -> Result<Layer> {
match s.to_lowercase().as_str() {
"background" => Ok(Layer::Background),
@@ -70,7 +122,6 @@ pub fn parse_layer(s: &str) -> Result<Layer> {
}
}
/// Set up a Wayland connection and run the render loop for one output.
pub fn run(
target_output: String,
shader: ShaderSource,
@@ -89,127 +140,116 @@ pub fn run(
let layer_shell =
LayerShell::bind(&globals, &qh).context("zwlr_layer_shell_v1 not available")?;
let mut state = AppState {
registry_state: RegistryState::new(&globals),
output_state: OutputState::new(&globals, &qh),
layer: None,
renderer: None,
display_ptr,
surface_ptr: std::ptr::null_mut(),
shader,
fps,
configured: false,
width: 0,
height: 0,
exit: false,
draw_ready: false,
last_frame: Instant::now(),
};
// One roundtrip to discover outputs.
event_queue.roundtrip(&mut state).context("initial roundtrip")?;
// Find the matching wl_output.
let target_wl_output = find_output(&state.output_state, &target_output);
// Create the wl_surface and layer surface.
let surface = compositor.create_surface(&qh);
state.surface_ptr = surface.id().as_ptr() as *mut std::ffi::c_void;
let layer = layer_shell.create_layer_surface(
&qh,
surface,
layer_kind,
Some("gpupaper"),
target_wl_output.as_ref(),
);
// Stretch to fill the entire output.
layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
layer.set_exclusive_zone(-1);
layer.set_size(0, 0);
layer.set_keyboard_interactivity(KeyboardInteractivity::None);
layer.commit();
state.layer = Some(layer);
// Wait for the configure event which gives us the actual dimensions.
log::info!("waiting for configure…");
while !state.configured {
event_queue.blocking_dispatch(&mut state).context("event dispatch failed")?;
}
log::info!("configured: {}x{}", state.width, state.height);
// Create renderer now that we have confirmed dimensions.
state.renderer = Some(unsafe {
Renderer::new(
state.display_ptr,
state.surface_ptr,
state.width,
state.height,
&state.shader,
state.fps,
)
.context("failed to create renderer")?
});
// Render loop driven by wl_surface.frame callbacks.
// The compositor stops sending callbacks when the surface is fully occluded,
// so the loop naturally idles to zero CPU when another app is fullscreen.
let frame_duration = if fps > 0 {
Some(Duration::from_nanos(1_000_000_000 / fps as u64))
} else {
None
};
// Register the first frame callback then render immediately. On Wayland
// the compositor only fires frame callbacks for commits that contain a
// buffer; an empty commit would stall the loop forever on many compositors.
// Rendering here attaches the first buffer and commits it together with the
// frame callback so the compositor has something to display right away.
{
let wl_surface = state.layer.as_ref().unwrap().wl_surface();
wl_surface.frame(&qh, wl_surface.clone());
let mut state = AppState {
registry_state: RegistryState::new(&globals),
output_state: OutputState::new(&globals, &qh),
compositor,
layer_shell,
outputs: Vec::new(),
gpu: None,
display_ptr,
shader,
fps,
layer_kind,
target_output: target_output.clone(),
frame_duration,
exit: false,
};
// Discover available outputs.
event_queue.roundtrip(&mut state).context("initial roundtrip")?;
let is_all = target_output == "all" || target_output == "*";
if is_all {
let wl_outputs: Vec<_> = state.output_state.outputs().collect();
if wl_outputs.is_empty() {
// No outputs reported yet; let the compositor assign.
state.attach_output(&qh, None);
} else {
for wl_out in &wl_outputs {
state.attach_output(&qh, Some(wl_out));
}
}
} else {
let wl_out = find_output(&state.output_state, &target_output);
state.attach_output(&qh, wl_out.as_ref());
}
if let Some(r) = state.renderer.as_mut() {
r.render();
// Wait for every surface to receive its configure (and thus create a renderer).
log::info!("waiting for {} surface(s) to configure…", state.outputs.len());
while state.outputs.iter().any(|o| o.renderer.is_none()) {
event_queue
.blocking_dispatch(&mut state)
.context("event dispatch failed")?;
if state.exit {
return Ok(());
}
}
log::info!("{} surface(s) ready", state.outputs.len());
// Render the first frame on each surface immediately so the compositor has
// a buffer and will start sending frame callbacks.
if let Some(gpu) = state.gpu.as_ref().map(Arc::clone) {
let elapsed = gpu.start.elapsed().as_secs_f32();
for output in &mut state.outputs {
let wl_surface = output.layer.wl_surface();
wl_surface.frame(&qh, wl_surface.clone());
if let Some(r) = &mut output.renderer {
r.render(&gpu, elapsed);
}
}
}
conn.flush().ok();
// Main event loop — each output is driven by its own frame callbacks so
// monitors at different refresh rates pace themselves independently.
loop {
// Block the thread until the compositor sends us any event (including
// the frame callback). Zero CPU while occluded.
event_queue.blocking_dispatch(&mut state).context("event dispatch")?;
event_queue
.blocking_dispatch(&mut state)
.context("event dispatch")?;
conn.flush().ok();
if state.exit {
break;
}
if !state.draw_ready {
continue;
}
state.draw_ready = false;
let gpu = match state.gpu.as_ref().map(Arc::clone) {
Some(g) => g,
None => continue,
};
let elapsed = gpu.start.elapsed().as_secs_f32();
let frame_duration = state.frame_duration;
// Optional fps cap: sleep the remainder of the frame budget.
if let Some(dur) = frame_duration {
let elapsed = state.last_frame.elapsed();
if elapsed < dur {
std::thread::sleep(dur - elapsed);
for output in &mut state.outputs {
if !output.draw_ready {
continue;
}
}
state.last_frame = Instant::now();
output.draw_ready = false;
// Register the NEXT frame callback before present() so that the
// request is included in the same wl_surface.commit that wgpu
// issues inside present().
{
let wl_surface = state.layer.as_ref().unwrap().wl_surface();
wl_surface.frame(&qh, wl_surface.clone());
}
if let Some(dur) = frame_duration {
let since_last = output.last_frame.elapsed();
if since_last < dur {
std::thread::sleep(dur - since_last);
}
}
output.last_frame = Instant::now();
if let Some(r) = state.renderer.as_mut() {
r.render();
{
let wl_surface = output.layer.wl_surface();
wl_surface.frame(&qh, wl_surface.clone());
}
if let Some(r) = &mut output.renderer {
r.render(&gpu, elapsed);
}
}
conn.flush().ok();
@@ -218,12 +258,7 @@ pub fn run(
Ok(())
}
/// Try to find the wl_output whose name matches `target`.
/// If `target` is `"all"` or `"*"`, returns `None` (compositor picks).
fn find_output(output_state: &OutputState, target: &str) -> Option<wl_output::WlOutput> {
if target == "all" || target == "*" {
return None;
}
for output in output_state.outputs() {
if let Some(info) = output_state.info(&output) {
if let Some(name) = &info.name {
@@ -239,36 +274,61 @@ fn find_output(output_state: &OutputState, target: &str) -> Option<wl_output::Wl
}
// ---------------------------------------------------------------------------
// Trait implementations for AppState
// Trait implementations
// ---------------------------------------------------------------------------
impl CompositorHandler for AppState {
fn scale_factor_changed(
&mut self, _: &Connection, _: &QueueHandle<Self>,
_: &wl_surface::WlSurface, _: i32,
) {}
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_surface::WlSurface,
_: i32,
) {
}
fn transform_changed(
&mut self, _: &Connection, _: &QueueHandle<Self>,
_: &wl_surface::WlSurface, _: wl_output::Transform,
) {}
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_surface::WlSurface,
_: wl_output::Transform,
) {
}
fn frame(
&mut self, _: &Connection, _: &QueueHandle<Self>,
_: &wl_surface::WlSurface, _: u32,
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
surface: &wl_surface::WlSurface,
_: u32,
) {
self.draw_ready = true;
let id = surface.id();
for output in &mut self.outputs {
if output.layer.wl_surface().id() == id {
output.draw_ready = true;
break;
}
}
}
fn surface_enter(
&mut self, _: &Connection, _: &QueueHandle<Self>,
_: &wl_surface::WlSurface, _: &wl_output::WlOutput,
) {}
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_surface::WlSurface,
_: &wl_output::WlOutput,
) {
}
fn surface_leave(
&mut self, _: &Connection, _: &QueueHandle<Self>,
_: &wl_surface::WlSurface, _: &wl_output::WlOutput,
) {}
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_surface::WlSurface,
_: &wl_output::WlOutput,
) {
}
}
impl OutputHandler for AppState {
@@ -276,9 +336,35 @@ impl OutputHandler for AppState {
&mut self.output_state
}
fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
fn new_output(
&mut self,
_conn: &Connection,
qh: &QueueHandle<Self>,
output: wl_output::WlOutput,
) {
if self.target_output == "all" || self.target_output == "*" {
self.attach_output(qh, Some(&output));
}
}
fn update_output(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: wl_output::WlOutput,
) {
}
fn output_destroyed(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
output: wl_output::WlOutput,
) {
// Drop the surface renderer for the disconnected output.
self.outputs
.retain(|o| o.layer.wl_surface().id() != output.id());
}
}
impl LayerShellHandler for AppState {
@@ -291,25 +377,64 @@ impl LayerShellHandler for AppState {
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_layer: &LayerSurface,
layer: &LayerSurface,
configure: LayerSurfaceConfigure,
_serial: u32,
) {
let (w, h) = configure.new_size;
self.width = if w == 0 { 1920 } else { w };
self.height = if h == 0 { 1080 } else { h };
let layer_id = layer.wl_surface().id();
let Some(idx) = self.outputs.iter().position(|o| o.layer.wl_surface().id() == layer_id)
else {
return;
};
if !self.configured {
self.configured = true;
} else if let Some(r) = self.renderer.as_mut() {
r.resize(self.width, self.height);
let (w, h) = configure.new_size;
let w = if w == 0 { 1920 } else { w };
let h = if h == 0 { 1080 } else { h };
self.outputs[idx].width = w;
self.outputs[idx].height = h;
if self.outputs[idx].renderer.is_some() {
// Subsequent configure — just resize.
let gpu = self.gpu.as_ref().map(Arc::clone);
if let Some(gpu) = gpu {
if let Some(r) = self.outputs[idx].renderer.as_mut() {
r.resize(&gpu, w, h);
}
}
return;
}
log::debug!("configure: {}x{}", self.width, self.height);
// First configure for this surface — create the GPU context if needed.
if self.gpu.is_none() {
match unsafe { GpuContext::new(self.display_ptr) } {
Ok(gpu) => self.gpu = Some(Arc::new(gpu)),
Err(e) => {
log::error!("failed to create GPU context: {e}");
self.exit = true;
return;
}
}
}
let gpu = Arc::clone(self.gpu.as_ref().unwrap());
let surface_ptr = self.outputs[idx].surface_ptr;
let display_ptr = self.display_ptr;
let shader = &self.shader;
let fps = self.fps;
match unsafe { SurfaceRenderer::new(&gpu, display_ptr, surface_ptr, w, h, shader, fps) } {
Ok(renderer) => {
self.outputs[idx].renderer = Some(renderer);
log::info!("output {} configured: {}x{}", idx, w, h);
}
Err(e) => {
log::error!("failed to create surface renderer for output {idx}: {e}");
self.exit = true;
}
}
}
}
// Delegation macros
delegate_compositor!(AppState);
delegate_output!(AppState);
delegate_layer!(AppState);