First commit. Version 0.1.0

This commit is contained in:
2026-05-10 09:58:23 +02:00
parent af105b7f7d
commit bbab5e238d
635 changed files with 53627 additions and 175 deletions

102
src/draw/chrome.rs Normal file
View File

@@ -0,0 +1,102 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! Surface chrome: the client-side title bar and the Wayland input
//! region. Both are backend-agnostic — the software and GPU draw
//! paths call them with a `&mut Canvas` / a `&WlSurface` and get back
//! the geometry they need for hit testing + commit.
use smithay_client_toolkit::compositor::{ CompositorState, Region };
use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface;
use crate::render::Canvas;
use crate::types::{ Color, Rect };
/// Paint the client-side title bar (close button, divider, title text).
///
/// Returns the close button rect in physical pixels so the caller can
/// store it for hit testing. Returns `Rect::default()` when `tb_h <=
/// 0` — overlays / layer-shell surfaces have no title bar.
pub( crate ) fn draw_titlebar( canvas: &mut Canvas, title: &str, pw: u32, tb_h: f32, sf: f32 ) -> Rect
{
if tb_h <= 0.0 { return Rect::default(); }
let tb_rect = Rect { x: 0.0, y: 0.0, width: pw as f32, height: tb_h };
canvas.fill_rect( tb_rect, Color::rgb( 0.15, 0.15, 0.18 ), 0.0 );
let title_size = 15.0;
// `Canvas::draw_text` interprets `y` as the baseline. Match the
// vertical-centring formula used by `Button::draw_text_button` so
// chrome and content text lines line up at the same optical height.
let title_y = ( tb_h + title_size * sf ) / 2.0 - 2.0;
let title_w = canvas.measure_text( title, title_size );
let title_x = ( pw as f32 - title_w ) / 2.0;
canvas.draw_text( title, title_x, title_y, title_size, Color::WHITE );
let btn_size = tb_h - 8.0 * sf;
let btn_x = pw as f32 - btn_size - 8.0 * sf;
let btn_y = 4.0 * sf;
let close_rect_phys = Rect { x: btn_x, y: btn_y, width: btn_size, height: btn_size };
canvas.fill_rect( close_rect_phys, Color::rgba( 1.0, 1.0, 1.0, 0.1 ), 4.0 * sf );
let cx = btn_x + btn_size / 2.0;
let cy = btn_y + btn_size / 2.0;
let arm = btn_size * 0.25;
canvas.draw_line( cx - arm, cy - arm, cx + arm, cy + arm, Color::WHITE, 2.0 * sf );
canvas.draw_line( cx + arm, cy - arm, cx - arm, cy + arm, Color::WHITE, 2.0 * sf );
canvas.draw_line( 0.0, tb_h - 0.5, pw as f32, tb_h - 0.5, Color::rgba( 1.0, 1.0, 1.0, 0.15 ), 1.0 );
close_rect_phys
}
/// Stamp a red warning banner at the top of the surface when the
/// active theme came from the in-memory B/W fallback (i.e.
/// [`crate::theme::is_fallback_active`] returned `true`). Gives the
/// user a clear visual cue that `ltk-theme-default` is missing.
///
/// Paints a thin red strip across the top of the surface (24 px
/// logical) with the install-instruction text. When the fallback is
/// not active this is a no-op.
pub( crate ) fn draw_fallback_banner(
canvas: &mut Canvas,
pw: u32,
sf: f32,
)
{
if !crate::theme::is_fallback_active() { return; }
let banner_h = 24.0 * sf;
let rect = Rect { x: 0.0, y: 0.0, width: pw as f32, height: banner_h };
canvas.fill_rect( rect, Color::rgb( 0.75, 0.10, 0.10 ), 0.0 );
let msg = "ltk: fallback theme — install `ltk-theme-default`";
let size = 12.0;
let msg_w = canvas.measure_text( msg, size );
let x = ( ( pw as f32 - msg_w ) / 2.0 ).max( 6.0 * sf );
let y = ( banner_h - size * sf ) / 2.0;
canvas.draw_text( msg, x, y, size, Color::WHITE );
}
/// Apply or clear the surface's input region (set by
/// `App::input_region`). `None` restores the default of "receive
/// input everywhere"; `Some(&[])` makes the surface pointer-through.
pub( crate ) fn apply_input_region(
wl_surface: &WlSurface,
compositor: &CompositorState,
input_region: Option<&[Rect]>,
)
{
if let Some( regions ) = input_region
{
if let Ok( region ) = Region::new( compositor )
{
for r in regions
{
region.add( r.x as i32, r.y as i32, r.width as i32, r.height as i32 );
}
wl_surface.set_input_region( Some( region.wl_region() ) );
}
} else {
wl_surface.set_input_region( None );
}
}

511
src/draw/damage.rs Normal file
View File

@@ -0,0 +1,511 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! Damage tracking: what rects need to be repainted this frame, and
//! what rects need to be declared to Wayland.
//!
//! Two entry points with different jobs:
//!
//! * [`compute_interaction_dirty_rects`] — called on the partial-redraw
//! path BEFORE painting. Takes the previous and current interaction
//! snapshots (focus / hover / pressed) and emits the union of the
//! `paint_rect`s of the widgets whose state transitioned. The caller
//! uses these to install a clip mask before the partial repaint and
//! to stamp `wl_surface.damage_buffer` afterwards.
//! * [`compute_damage`] — called on the full-redraw path AFTER painting.
//! Compares the previous-frame widget rects with the just-produced
//! ones; if layout moved or changed, returns an empty vec (meaning
//! "damage the whole surface"), otherwise returns a tight list of
//! rects for the widgets whose interaction state changed.
//!
//! The 50%-of-screen heuristic is shared by both: if the accumulated
//! damage covers more than half the surface, the single full-surface
//! damage rect is cheaper than the per-region list.
use crate::types::Rect;
use crate::widget::LaidOutWidget;
/// Intersect `r` with `bounds`, returning a rect that is entirely
/// inside `bounds`. Returns a zero-size rect if they do not overlap.
pub( super ) fn clamp_rect_to( r: Rect, bounds: Rect ) -> Rect
{
let x0 = r.x.max( bounds.x );
let y0 = r.y.max( bounds.y );
let x1 = ( r.x + r.width ).min( bounds.x + bounds.width );
let y1 = ( r.y + r.height ).min( bounds.y + bounds.height );
if x1 <= x0 || y1 <= y0
{
Rect { x: x0, y: y0, width: 0.0, height: 0.0 }
} else {
Rect { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }
}
}
/// Build the dirty-rect list for an interaction-only frame: union of
/// the `paint_rect`s of the widgets whose focus / hover / pressed
/// transitioned. Each widget's `paint_rect` already encloses its hover
/// halo, focus ring, and any other overdraw, so no extra padding is
/// needed here.
pub( crate ) fn compute_interaction_dirty_rects<Msg: Clone>(
widget_rects: &[ LaidOutWidget<Msg> ],
prev_focused: Option<usize>, prev_hovered: Option<usize>, prev_pressed: Option<usize>,
new_focused: Option<usize>, new_hovered: Option<usize>, new_pressed: Option<usize>,
pw: u32,
ph: u32,
) -> Vec<Rect>
{
let mut rects: Vec<Rect> = Vec::new();
let visit = |idx_opt: Option<usize>, sink: &mut Vec<Rect>|
{
if let Some( idx ) = idx_opt
{
if let Some( w ) = widget_rects.iter().find( |w| w.flat_idx == idx )
{
if !w.handlers.is_slider()
{
sink.push( w.paint_rect );
}
}
}
};
if prev_focused != new_focused
{
visit( prev_focused, &mut rects );
visit( new_focused, &mut rects );
}
if prev_hovered != new_hovered
{
visit( prev_hovered, &mut rects );
visit( new_hovered, &mut rects );
}
if prev_pressed != new_pressed
{
visit( prev_pressed, &mut rects );
visit( new_pressed, &mut rects );
}
// Snap to integer pixel boundaries before clamping. The clip mask is
// rasterized with anti_alias=false (binary, sampled at pixel centers), and
// `Canvas::clear_rects_transparent` uses `as i32` floor on the min and
// `.ceil() as i32` on the max. If `paint_rect` carries fractional coords
// (e.g. from `expand( 14.5 )` on icon-button hover halos), those two paths
// can disagree by 1 px at the edge — leaving a pixel cleared to transparent
// black but not repainted on the next frame. Floor min / ceil max here so
// both paths see the same whole-pixel rect.
let sw = pw as f32;
let sh = ph as f32;
for r in &mut rects
{
let x0 = r.x.floor().max( 0.0 );
let y0 = r.y.floor().max( 0.0 );
let x1 = ( r.x + r.width ).ceil().min( sw );
let y1 = ( r.y + r.height ).ceil().min( sh );
r.x = x0;
r.y = y0;
r.width = ( x1 - x0 ).max( 0.0 );
r.height = ( y1 - y0 ).max( 0.0 );
}
rects.retain( |r| r.width > 0.0 && r.height > 0.0 );
rects
}
/// Compare previous and current widget rects + interaction state to
/// find damaged regions. Returns a list of damage rects, or empty vec
/// if everything changed (full redraw).
pub( crate ) fn compute_damage<Msg: Clone>(
old_rects: &[ LaidOutWidget<Msg> ],
new_rects: &[ LaidOutWidget<Msg> ],
old_focused: Option<usize>,
old_hovered: Option<usize>,
old_pressed: Option<usize>,
new_focused: Option<usize>,
new_hovered: Option<usize>,
new_pressed: Option<usize>,
screen_w: u32,
screen_h: u32,
) -> Vec<Rect>
{
// Widget tree structure changed: full redraw.
if old_rects.len() != new_rects.len()
{
return Vec::new();
}
let mut damage = Vec::new();
let changed_indices: Vec<usize> = [
old_focused, new_focused,
old_hovered, new_hovered,
old_pressed, new_pressed,
].iter().filter_map( |&idx| idx ).collect();
for &idx in &changed_indices
{
// Each widget's declared `paint_rect` already encloses its overdraw.
if let Some( w ) = old_rects.iter().find( |w| w.flat_idx == idx )
{
damage.push( w.paint_rect );
}
if let Some( w ) = new_rects.iter().find( |w| w.flat_idx == idx )
{
damage.push( w.paint_rect );
}
}
// Layout shift: any rect moved or resized => full redraw.
for ( i, old_w ) in old_rects.iter().enumerate()
{
if let Some( new_w ) = new_rects.get( i )
{
let old_r = old_w.rect;
let new_r = new_w.rect;
if ( old_r.x - new_r.x ).abs() > 0.5
|| ( old_r.y - new_r.y ).abs() > 0.5
|| ( old_r.width - new_r.width ).abs() > 0.5
|| ( old_r.height - new_r.height ).abs() > 0.5
{
return Vec::new();
}
}
}
// No interaction changes but a redraw was requested => content changed
// (e.g. clock tick) and a full redraw is the right answer.
if damage.is_empty()
{
return Vec::new();
}
// Dilate every damage rect by 1 px on each side. The GPU rect/gradient
// shaders draw their quads expanded by 1 px so the outer half of the
// SDF antialiasing band has fragments to cover; under a partial
// redraw the scissor would otherwise clip that band at the widget's
// `paint_rect` boundary, re-introducing the aliased step on the
// straight edges of pills / rounded rects. The cost is negligible
// (one extra pixel of clear + repaint per damage rect).
for r in &mut damage
{
r.x -= 1.0;
r.y -= 1.0;
r.width += 2.0;
r.height += 2.0;
}
let sw = screen_w as f32;
let sh = screen_h as f32;
for r in &mut damage
{
r.x = r.x.max( 0.0 );
r.y = r.y.max( 0.0 );
r.width = r.width.min( sw - r.x );
r.height = r.height.min( sh - r.y );
}
// Total damage > 50% of screen: full redraw is no slower and emits a
// single damage rect instead of many.
let total_damage: f32 = damage.iter().map( |r| r.width * r.height ).sum();
if total_damage > sw * sh * 0.5
{
return Vec::new();
}
damage
}
#[ cfg( test ) ]
mod tests
{
use super::*;
use crate::widget::WidgetHandlers;
fn r( x: f32, y: f32, w: f32, h: f32 ) -> Rect
{
Rect { x, y, width: w, height: h }
}
fn lw( idx: usize, rect: Rect, paint: Rect ) -> LaidOutWidget<()>
{
LaidOutWidget
{
rect,
flat_idx: idx,
id: None,
paint_rect: paint,
handlers: WidgetHandlers::None,
keyboard_focusable: true,
cursor: crate::types::CursorShape::Default,
}
}
// ── clamp_rect_to ─────────────────────────────────────────────────────────
#[ test ]
fn clamp_rect_to_returns_intersection()
{
let bounds = r( 0.0, 0.0, 100.0, 100.0 );
let inside = r( 10.0, 10.0, 20.0, 20.0 );
assert_eq!( clamp_rect_to( inside, bounds ), inside );
}
#[ test ]
fn clamp_rect_to_clips_to_bounds()
{
let bounds = r( 0.0, 0.0, 100.0, 100.0 );
let bleed = r( 80.0, 80.0, 50.0, 50.0 );
assert_eq!( clamp_rect_to( bleed, bounds ), r( 80.0, 80.0, 20.0, 20.0 ) );
}
#[ test ]
fn clamp_rect_to_disjoint_returns_zero_size()
{
let bounds = r( 0.0, 0.0, 100.0, 100.0 );
let off = r( 200.0, 200.0, 50.0, 50.0 );
let out = clamp_rect_to( off, bounds );
assert_eq!( ( out.width, out.height ), ( 0.0, 0.0 ) );
}
// ── compute_interaction_dirty_rects ───────────────────────────────────────
#[ test ]
fn no_state_change_yields_empty_dirty_rects()
{
let widgets = vec![ lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ) ];
let rects = compute_interaction_dirty_rects(
&widgets,
Some( 1 ), None, None,
Some( 1 ), None, None,
800, 600,
);
assert!( rects.is_empty() );
}
#[ test ]
fn focus_change_emits_both_old_and_new_paint_rects()
{
let widgets = vec![
lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ),
lw( 2, r( 100.0, 0.0, 50.0, 50.0 ), r( 100.0, 0.0, 50.0, 50.0 ) ),
];
let rects = compute_interaction_dirty_rects(
&widgets,
Some( 1 ), None, None,
Some( 2 ), None, None,
800, 600,
);
assert_eq!( rects.len(), 2 );
}
#[ test ]
fn hover_change_emits_paint_rects_independent_of_focus()
{
let widgets = vec![
lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ),
lw( 2, r( 100.0, 0.0, 50.0, 50.0 ), r( 100.0, 0.0, 50.0, 50.0 ) ),
];
let rects = compute_interaction_dirty_rects(
&widgets,
Some( 1 ), Some( 1 ), None,
Some( 1 ), Some( 2 ), None,
800, 600,
);
assert_eq!( rects.len(), 2 );
}
#[ test ]
fn dirty_rects_are_snapped_and_clamped_to_screen()
{
let widgets = vec![
lw( 1, r( -10.0, -10.0, 30.5, 40.5 ), r( -10.0, -10.0, 30.5, 40.5 ) ),
];
let rects = compute_interaction_dirty_rects(
&widgets,
None, None, None,
Some( 1 ), None, None,
100, 100,
);
assert_eq!( rects.len(), 1 );
// Floor of -10 is -10 → max(0) = 0; ceil of -10+30.5=20.5 → 21.
assert_eq!( rects[ 0 ].x, 0.0 );
assert_eq!( rects[ 0 ].y, 0.0 );
assert_eq!( rects[ 0 ].width, 21.0 );
assert_eq!( rects[ 0 ].height, 31.0 );
}
#[ test ]
fn dirty_rects_outside_screen_are_dropped()
{
let widgets = vec![
lw( 1, r( 1000.0, 1000.0, 50.0, 50.0 ), r( 1000.0, 1000.0, 50.0, 50.0 ) ),
];
let rects = compute_interaction_dirty_rects(
&widgets,
None, None, None,
Some( 1 ), None, None,
100, 100,
);
assert!( rects.is_empty() );
}
#[ test ]
fn missing_widget_idx_silently_skipped()
{
let widgets = vec![ lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ) ];
// Old focus references an idx that no longer exists in widget_rects —
// this happens during a layout where a widget disappeared between
// frames. The function must not panic; it just emits whatever new
// state's rect it can find.
let rects = compute_interaction_dirty_rects(
&widgets,
Some( 99 ), None, None,
Some( 1 ), None, None,
800, 600,
);
assert_eq!( rects.len(), 1 );
}
// ── compute_damage ────────────────────────────────────────────────────────
#[ test ]
fn tree_size_change_returns_full_redraw()
{
let old = vec![ lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ) ];
let new = vec![
lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ),
lw( 2, r( 0.0, 60.0, 50.0, 50.0 ), r( 0.0, 60.0, 50.0, 50.0 ) ),
];
let damage = compute_damage(
&old, &new,
None, None, None,
None, None, None,
800, 600,
);
assert!( damage.is_empty(), "tree size change must signal full redraw via empty vec" );
}
#[ test ]
fn layout_shift_returns_full_redraw()
{
let old = vec![ lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ) ];
let new = vec![ lw( 1, r( 0.0, 60.0, 50.0, 50.0 ), r( 0.0, 60.0, 50.0, 50.0 ) ) ];
let damage = compute_damage(
&old, &new,
Some( 1 ), None, None,
Some( 1 ), None, None,
800, 600,
);
assert!( damage.is_empty() );
}
#[ test ]
fn focus_change_emits_partial_damage()
{
let widgets = vec![
lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ),
lw( 2, r( 100.0, 0.0, 50.0, 50.0 ), r( 100.0, 0.0, 50.0, 50.0 ) ),
];
let damage = compute_damage(
&widgets, &widgets,
Some( 1 ), None, None,
Some( 2 ), None, None,
800, 600,
);
assert!( !damage.is_empty(), "focus change must produce non-empty damage list" );
assert!(
damage.len() >= 2,
"both old and new focused widgets contribute their paint_rects"
);
}
#[ test ]
fn no_change_with_redraw_request_returns_full_redraw()
{
// `damage.is_empty()` after the changed_indices loop means nothing
// interaction-level changed but the caller still asked to redraw —
// content tick (e.g. clock). The function returns the empty vec to
// signal "redraw everything" rather than nothing.
let widgets = vec![ lw( 1, r( 0.0, 0.0, 50.0, 50.0 ), r( 0.0, 0.0, 50.0, 50.0 ) ) ];
let damage = compute_damage(
&widgets, &widgets,
None, None, None,
None, None, None,
800, 600,
);
assert!( damage.is_empty() );
}
#[ test ]
fn damage_rects_are_dilated_by_one_pixel_each_side()
{
// Every damage rect grows by 1 px on each side to cover the SDF
// antialiasing band; the rect is then clamped to the surface.
let widgets = vec![ lw( 1, r( 100.0, 100.0, 50.0, 50.0 ), r( 100.0, 100.0, 50.0, 50.0 ) ) ];
let damage = compute_damage(
&widgets, &widgets,
None, None, None,
Some( 1 ), None, None,
800, 600,
);
assert_eq!( damage.len(), 2 );
for d in &damage
{
assert_eq!( d.x, 99.0 );
assert_eq!( d.y, 99.0 );
assert_eq!( d.width, 52.0 );
assert_eq!( d.height, 52.0 );
}
}
#[ test ]
fn damage_above_fifty_percent_collapses_to_full_redraw()
{
// Widget covers 60 % of a 100×100 surface. The dilated rect easily
// exceeds the 50 % threshold and the function falls back to full
// redraw.
let widgets = vec![
lw( 1, r( 0.0, 0.0, 80.0, 80.0 ), r( 0.0, 0.0, 80.0, 80.0 ) ),
];
let damage = compute_damage(
&widgets, &widgets,
None, None, None,
Some( 1 ), None, None,
100, 100,
);
assert!( damage.is_empty(), "damage > 50 % of surface must signal full redraw" );
}
#[ test ]
fn damage_below_fifty_percent_returns_partial()
{
// 10×10 widget on a 100×100 surface → ~1 % per rect, well under 50 %.
let widgets = vec![
lw( 1, r( 5.0, 5.0, 10.0, 10.0 ), r( 5.0, 5.0, 10.0, 10.0 ) ),
];
let damage = compute_damage(
&widgets, &widgets,
None, None, None,
Some( 1 ), None, None,
100, 100,
);
assert!( !damage.is_empty() );
}
#[ test ]
fn damage_clamped_to_surface_extents()
{
// Widget paint_rect at the right edge — dilation can push it past the
// surface; the clamp must keep width/height within the surface.
let widgets = vec![
lw( 1, r( 90.0, 90.0, 5.0, 5.0 ), r( 90.0, 90.0, 5.0, 5.0 ) ),
];
let damage = compute_damage(
&widgets, &widgets,
None, None, None,
Some( 1 ), None, None,
100, 100,
);
for d in &damage
{
assert!( d.x + d.width <= 100.0 + f32::EPSILON );
assert!( d.y + d.height <= 100.0 + f32::EPSILON );
}
}
}

253
src/draw/gles.rs Normal file
View File

@@ -0,0 +1,253 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! GLES (EGL + FBO) draw paths.
//!
//! The GPU counterparts to [`super::software::draw_surface_full`] and
//! [`super::software::draw_surface_partial`]. Same DrawCtx flow; the
//! differences are:
//!
//! * Canvas is `Canvas::new_gles` backed by a persistent FBO rather
//! than a CPU pixmap → FBO pixels survive across frames naturally,
//! so the partial path only needs a scissor.
//! * Presentation goes through `egl_ctx.swap_buffers_with_damage`
//! which attaches + damages + commits atomically. The partial path
//! translates the top-left dirty rects into EGL's bottom-left
//! convention before passing them in.
//! * No `wl_shm` pool; no `pick_shm_format`; no byte-order swap.
//!
//! The Y-flip for the swap-with-damage call lives here (only the GPU
//! path needs it — SHM buffers are already top-down).
use std::sync::Arc;
use smithay_client_toolkit::compositor::CompositorState;
use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface;
use crate::egl_context::EglContext;
use crate::event_loop::SurfaceState;
use crate::render::Canvas;
use crate::types::{ Color, Rect };
use crate::widget::Element;
use super::{ DrawCtx, layout_and_draw };
use super::chrome::{ apply_input_region, draw_fallback_banner, draw_titlebar };
/// GPU full-redraw path. Mirrors [`super::software::draw_surface_full`]
/// but writes into the EGL surface's persistent FBO instead of an SHM
/// buffer:
///
/// 1. `eglMakeCurrent` so subsequent GL calls hit this surface.
/// 2. (Lazily) build the [`Canvas::Gles`], or resize its FBO if the
/// surface dimensions changed.
/// 3. Clear, run layout+draw, blit the FBO to the default framebuffer.
/// 4. Set buffer_scale + input_region (state attached to the implicit
/// commit done by `eglSwapBuffers`).
/// 5. `eglSwapBuffers` — performs the wl attach/damage/commit atomically.
pub( crate ) fn draw_surface_full_gpu<Msg: Clone>(
ss: &mut SurfaceState<Msg>,
compositor: &CompositorState,
egl_ctx: &Arc<EglContext>,
view: &Element<Msg>,
bg: Color,
input_region: Option<&[Rect]>,
debug_layout: bool,
pw: u32,
ph: u32,
scale: u32,
request_frame: &dyn Fn( &WlSurface ),
)
{
let Some( es ) = ss.egl_surface.as_ref() else { return };
if egl_ctx.make_current( es ).is_err() { return; }
let canvas = ss.canvas.get_or_insert_with( ||
{
let mut c = Canvas::new_gles(
Arc::clone( egl_ctx.gl() ), egl_ctx.version, pw, ph,
);
c.set_dpi_scale( scale as f32 );
if let Some( reg ) = crate::theme::build_font_registry()
{
c.set_font_registry( Arc::new( reg ) );
}
c
} );
if canvas.size() != ( pw, ph )
{
canvas.resize( pw, ph );
canvas.set_dpi_scale( scale as f32 );
}
canvas.clear_clip();
let sf = scale as f32;
let tb_h = ss.titlebar_height * sf;
let screen_rect = Rect { x: 0.0, y: tb_h, width: pw as f32, height: ( ph as f32 - tb_h ).max( 0.0 ) };
if bg.a > 0.0 { canvas.fill( bg ); } else { canvas.clear(); }
ss.titlebar_close_rect = draw_titlebar( canvas, &ss.titlebar_title, pw, tb_h, sf );
let mut ctx: DrawCtx<Msg> = DrawCtx
{
focused_idx: ss.focused_idx,
hovered_idx: ss.hovered_idx,
pressed_idx: ss.gesture.pressed_idx,
cursor_state: std::mem::take( &mut ss.cursor_state ),
selection_anchor: std::mem::take( &mut ss.selection_anchor ),
widget_rects: Vec::new(),
debug_layout,
scroll_offsets: std::mem::take( &mut ss.scroll_offsets ),
scroll_rects: Vec::new(),
scroll_canvases: std::mem::take( &mut ss.scroll_canvases ),
scroll_navigable_items: std::mem::take( &mut ss.scroll_navigable_items ),
previous_widget_rects: ss.widget_rects.clone(),
};
layout_and_draw::<Msg>( view, canvas, screen_rect, &mut ctx, 0 );
if ctx.debug_layout
{
for w in &ctx.widget_rects
{
canvas.stroke_rect( w.rect, Color::rgb( 1.0, 0.0, 0.0 ), 1.5, 0.0 );
}
}
if let Some( ref menu ) = ss.context_menu
{
super::draw_context_menu( canvas, menu );
}
// Fallback-theme warning. Painted last so it sits on top of every
// widget; no-op when the real theme is loaded.
draw_fallback_banner( canvas, pw, sf );
canvas.present();
ss.prev_focused = ss.focused_idx;
ss.prev_hovered = ss.hovered_idx;
ss.prev_pressed = ss.gesture.pressed_idx;
ss.widget_rects = ctx.widget_rects;
ss.scroll_rects = ctx.scroll_rects;
ss.scroll_canvases = std::mem::take( &mut ctx.scroll_canvases );
ss.cursor_state = ctx.cursor_state;
ss.selection_anchor = ctx.selection_anchor;
ss.scroll_offsets = ctx.scroll_offsets;
ss.scroll_navigable_items = ctx.scroll_navigable_items;
ss.content_dirty = false;
let wl_surface = ss.surface.wl_surface();
apply_input_region( wl_surface, compositor, input_region );
// Frame callback request must precede the implicit commit done by
// `swap_buffers_with_damage`, so the compositor can attach it to this
// frame and not the previous one.
request_frame( wl_surface );
// Full-surface damage. (0,0,w,h) is identical in EGL bottom-left and
// top-left coords, so no Y-flip needed.
let _ = egl_ctx.swap_buffers_with_damage( es, &[ ( 0, 0, pw as i32, ph as i32 ) ] );
ss.frame_pending = true;
}
/// GPU partial-redraw path. Same flow as
/// [`super::software::draw_surface_partial`] (clip mask → repaint
/// background + widgets → present), but the clip is implemented with
/// `glScissor` (bbox union) inside the canvas, and presentation goes
/// through `eglSwapBuffers`. The FBO is preserved between frames so
/// the unclipped pixels naturally carry over.
pub( crate ) fn draw_surface_partial_gpu<Msg: Clone>(
ss: &mut SurfaceState<Msg>,
compositor: &CompositorState,
egl_ctx: &Arc<EglContext>,
view: &Element<Msg>,
bg: Color,
input_region: Option<&[Rect]>,
dirty_rects: Vec<Rect>,
pw: u32,
ph: u32,
scale: u32,
request_frame: &dyn Fn( &WlSurface ),
)
{
let Some( es ) = ss.egl_surface.as_ref() else { return };
if egl_ctx.make_current( es ).is_err() { return; }
let canvas = ss.canvas.as_mut().expect( "partial path requires existing canvas" );
if canvas.size() != ( pw, ph )
{
canvas.resize( pw, ph );
canvas.set_dpi_scale( scale as f32 );
}
canvas.set_clip_rects( &dirty_rects );
let sf = scale as f32;
let tb_h = ss.titlebar_height * sf;
let screen_rect = Rect { x: 0.0, y: tb_h, width: pw as f32, height: ( ph as f32 - tb_h ).max( 0.0 ) };
if bg.a > 0.0 { canvas.fill( bg ); }
else
{
canvas.clear_rects_transparent( &dirty_rects );
}
ss.titlebar_close_rect = draw_titlebar( canvas, &ss.titlebar_title, pw, tb_h, sf );
let mut ctx: DrawCtx<Msg> = DrawCtx
{
focused_idx: ss.focused_idx,
hovered_idx: ss.hovered_idx,
pressed_idx: ss.gesture.pressed_idx,
cursor_state: std::mem::take( &mut ss.cursor_state ),
selection_anchor: std::mem::take( &mut ss.selection_anchor ),
widget_rects: Vec::new(),
debug_layout: false,
scroll_offsets: std::mem::take( &mut ss.scroll_offsets ),
scroll_rects: Vec::new(),
scroll_canvases: std::mem::take( &mut ss.scroll_canvases ),
scroll_navigable_items: std::mem::take( &mut ss.scroll_navigable_items ),
previous_widget_rects: ss.widget_rects.clone(),
};
layout_and_draw::<Msg>( view, canvas, screen_rect, &mut ctx, 0 );
if let Some( ref menu ) = ss.context_menu
{
super::draw_context_menu( canvas, menu );
}
// Fallback-theme warning. Painted last so it sits on top of every
// widget; no-op when the real theme is loaded.
draw_fallback_banner( canvas, pw, sf );
canvas.clear_clip();
canvas.present();
ss.prev_focused = ss.focused_idx;
ss.prev_hovered = ss.hovered_idx;
ss.prev_pressed = ss.gesture.pressed_idx;
ss.widget_rects = ctx.widget_rects;
ss.scroll_rects = ctx.scroll_rects;
ss.scroll_canvases = std::mem::take( &mut ctx.scroll_canvases );
ss.cursor_state = ctx.cursor_state;
ss.selection_anchor = ctx.selection_anchor;
ss.scroll_offsets = ctx.scroll_offsets;
ss.scroll_navigable_items = ctx.scroll_navigable_items;
ss.content_dirty = false;
let wl_surface = ss.surface.wl_surface();
apply_input_region( wl_surface, compositor, input_region );
request_frame( wl_surface );
// Convert top-left dirty rects to EGL bottom-left coords for the
// swap-with-damage call.
let damage: Vec<( i32, i32, i32, i32 )> = dirty_rects.iter().map( |r|
{
let x = r.x.floor() as i32;
let w = r.width.ceil() as i32;
let h = r.height.ceil() as i32;
let y_top = r.y.floor() as i32;
let y_bottom = ph as i32 - y_top - h;
( x, y_bottom.max( 0 ), w.max( 0 ), h.max( 0 ) )
} ).collect();
let _ = egl_ctx.swap_buffers_with_damage( es, &damage );
ss.frame_pending = true;
}

379
src/draw/layout.rs Normal file
View File

@@ -0,0 +1,379 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! Element-tree recursive walker.
//!
//! [`layout_and_draw`] is the single bottom of the draw pipeline:
//! given an [`Element`] + its allocated rect, it lays out children,
//! paints leaves, threads scroll sub-canvases, and records the
//! [`LaidOutWidget`] entries the input layer will hit-test against.
//! Both software and GPU paths funnel every widget through this one
//! function.
use crate::render::Canvas;
use crate::types::Rect;
use crate::widget::{ Element, LaidOutWidget, WidgetHandlers };
use super::DrawCtx;
use super::damage::clamp_rect_to;
pub( crate ) fn layout_and_draw<Msg: Clone>(
element: &Element<Msg>,
canvas: &mut Canvas,
rect: Rect,
ctx: &mut DrawCtx<Msg>,
flat_idx: usize,
) -> usize
{
match element
{
Element::Column( col ) =>
{
let child_rects = col.layout( rect, canvas );
let mut idx = flat_idx;
for ( child_rect, child_i ) in child_rects
{
idx = layout_and_draw::<Msg>( &col.children[child_i], canvas, child_rect, ctx, idx );
}
idx
}
Element::Row( r ) =>
{
let child_rects = r.layout( rect, canvas );
let mut idx = flat_idx;
for ( child_rect, child_i ) in child_rects
{
idx = layout_and_draw::<Msg>( &r.children[child_i], canvas, child_rect, ctx, idx );
}
idx
}
Element::Stack( s ) =>
{
let child_rects = s.layout( rect, canvas );
let mut idx = flat_idx;
for ( child_rect, child_i ) in child_rects
{
idx = layout_and_draw::<Msg>( &s.children[ child_i ].0, canvas, child_rect, ctx, idx );
}
idx
}
Element::WrapGrid( g ) =>
{
let child_rects = g.layout( rect, canvas );
let mut idx = flat_idx;
for ( child_rect, child_i ) in child_rects
{
idx = layout_and_draw::<Msg>( &g.children[child_i], canvas, child_rect, ctx, idx );
}
idx
}
Element::Flex( f ) =>
{
// `Flex` is invisible chrome: it claimed leftover width up at
// `Row::layout`, here we just unwrap it and draw the child
// inside the allocated rect. No flat-index of its own.
layout_and_draw::<Msg>( f.child.as_ref(), canvas, rect, ctx, flat_idx )
}
Element::AnchoredOverlay( a ) =>
{
// Look up the anchor's rect from the previous frame's
// `widget_rects` snapshot. If found, place the child flush
// below the anchor at the child's intrinsic size; if not,
// fall back to the parent-supplied rect so the child still
// renders (modal-style, typically a one-frame artefact on
// the first frame after open).
let anchor_rect = ctx.previous_widget_rects.iter()
.find( |w| w.id == Some( a.anchor_id ) )
.map( |w| w.rect );
let target = match anchor_rect
{
Some( anchor ) =>
{
// Use the child's intrinsic preferred size so the
// popup keeps its design width / height regardless
// of how wide the trigger pill happens to be.
let ( w, h ) = a.child.preferred_size( rect.width, canvas );
Rect
{
x: anchor.x,
y: anchor.y + anchor.height + a.gap,
width: w,
height: h,
}
}
None => rect,
};
layout_and_draw::<Msg>( a.child.as_ref(), canvas, target, ctx, flat_idx )
}
Element::Pressable( p ) =>
{
// Push the wrapper's hit rect *before* recursing so that any
// interactive child pushed during recursion sits later in
// `widget_rects` and wins under `iter().rev()` hit testing.
let my_idx = flat_idx;
if p.has_handler()
{
ctx.widget_rects.push( LaidOutWidget
{
rect,
flat_idx: my_idx,
id: p.id,
paint_rect: rect,
handlers: WidgetHandlers::Button
{
on_press: p.on_press.clone(),
on_long_press: p.on_long_press.clone(),
on_drag_start: p.on_drag_start.clone(),
on_escape: p.on_escape.clone(),
repeating: false,
},
keyboard_focusable: false,
cursor: p.cursor.unwrap_or( crate::types::CursorShape::Pointer ),
} );
}
layout_and_draw::<Msg>( p.child.as_ref(), canvas, rect, ctx, my_idx + 1 )
}
Element::Container( c ) =>
{
let saved_alpha = canvas.global_alpha();
canvas.set_global_alpha( saved_alpha * c.opacity );
// Surface slot takes precedence over flat background; falls
// through to `c.background` when the slot is absent (third-
// party theme without the named surface — content still
// renders, just without the themed chrome).
let painted = match c.surface.as_deref()
{
Some( slot ) => match crate::theme::resolve_surface( slot )
{
Some( ( surf, outer ) ) =>
{
canvas.fill_surface
(
rect,
&surf.fill,
&outer,
&surf.inset_shadows,
c.corners,
);
true
}
None => false,
},
None => false,
};
if !painted
{
if let Some( bg ) = c.background
{
canvas.fill_rect( rect, bg, c.corners );
}
}
if let Some( ( color, width ) ) = c.border
{
canvas.stroke_rect( rect, color, width, c.corners );
}
let inner = crate::types::Rect
{
x: rect.x + c.pad_left,
y: rect.y + c.pad_top,
width: ( rect.width - c.pad_left - c.pad_right ).max( 0.0 ),
height: ( rect.height - c.pad_top - c.pad_bottom ).max( 0.0 ),
};
let result = layout_and_draw::<Msg>( c.child.as_ref(), canvas, inner, ctx, flat_idx );
canvas.set_global_alpha( saved_alpha );
result
}
Element::Scroll( s ) =>
{
let my_idx = flat_idx;
let offset_raw = ctx.scroll_offsets.get( &my_idx ).copied().unwrap_or( 0.0 );
let child_h = s.child.preferred_size( rect.width, canvas ).1;
let offset = crate::widget::scroll::clamp_offset( offset_raw, child_h, rect.height );
// Write the clamped offset back so input handlers (wheel /
// drag) cannot accumulate past the content extents. Without
// this, repeated wheel ticks past the bottom keep growing
// `offset_raw` and the user has to "undo" that excess before
// the content scrolls back up. The clamp is idempotent for
// in-range values, so the only effect is collapsing
// out-of-range entries to the legitimate maximum.
if offset != offset_raw
{
ctx.scroll_offsets.insert( my_idx, offset );
}
// Reuse the sub-canvas from the previous frame if its size matches;
// only reallocate when the viewport is resized.
let sw = (rect.width.ceil() as u32).max( 1 );
let sh = (rect.height.ceil() as u32).max( 1 );
let mut sub = ctx.scroll_canvases.remove( &my_idx )
.filter( |c| c.size() == ( sw, sh ) )
.unwrap_or_else( || canvas.sub_canvas( sw, sh ) );
sub.clear();
// Child content fills at least the full viewport height so that
// children with VAlign::Bottom are positioned correctly when the
// content is shorter than the viewport.
let effective_h = child_h.max( rect.height );
// Shift child up by offset so scrolled content appears at y=0 in
// the sub-canvas.
let child_rect = Rect { x: 0.0, y: -offset, width: rect.width, height: effective_h };
let rects_before = ctx.widget_rects.len();
let scroll_rects_before = ctx.scroll_rects.len();
let next_idx = layout_and_draw::<Msg>( s.child.as_ref(), &mut sub, child_rect, ctx, my_idx + 1 );
// Translate widget_rects from sub-canvas space to global space; drop
// clipped ones. Also clamp `paint_rect` to the scroll viewport so a
// widget painting outside the sub-canvas does not invalidate pixels
// it cannot actually reach (the sub-canvas is blitted as a whole,
// so nothing outside the viewport appears on screen anyway).
let new_rects: Vec<LaidOutWidget<Msg>> = ctx.widget_rects.drain( rects_before.. ).collect();
// Capture every interactive item the child laid out — including
// items that the visibility filter below will discard — so the
// keyboard handler can step `hovered_idx` item-by-item without
// caring about which items are currently scrolled into view.
// The recorded Y is in pre-translation, pre-offset coordinates
// (i.e. `child_y` relative to the start of the scroll content),
// recovered by undoing the `-offset` shift the child layout pass
// applied: `content_y = w.rect.y - child_rect.y = w.rect.y + offset`.
let navigable: Vec<( usize, f32, f32 )> = new_rects.iter()
.filter( |w| w.handlers.is_navigable_list_item() )
.map( |w| ( w.flat_idx, w.rect.y + offset, w.rect.height ) )
.collect();
if !navigable.is_empty()
{
ctx.scroll_navigable_items.insert( my_idx, navigable );
}
for mut w in new_rects
{
// Sub-canvas origin (0,0) maps to global (rect.x, rect.y).
w.rect.x += rect.x;
w.rect.y += rect.y;
w.paint_rect.x += rect.x;
w.paint_rect.y += rect.y;
w.paint_rect = clamp_rect_to( w.paint_rect, rect );
// Only keep widgets at least partially visible inside the viewport.
if w.rect.y + w.rect.height > rect.y && w.rect.y < rect.y + rect.height
{
ctx.widget_rects.push( w );
}
}
// Same translation for scroll_rects pushed by any nested
// scroll widgets — without this, the wheel handler hit-tests
// in surface coords against rects in sub-canvas coords and
// only matches when the sub-canvas happens to start at
// (0, 0) of the surface. Clamp to the outer scroll rect so
// the inner scroll only captures wheel events inside its
// visible region.
let new_scroll_rects: Vec<( Rect, usize )> =
ctx.scroll_rects.drain( scroll_rects_before.. ).collect();
for ( mut r, idx ) in new_scroll_rects
{
r.x += rect.x;
r.y += rect.y;
let clamped = clamp_rect_to( r, rect );
if clamped.width > 0.0 && clamped.height > 0.0
{
ctx.scroll_rects.push( ( clamped, idx ) );
}
}
ctx.scroll_rects.push( ( rect, my_idx ) );
canvas.blit( &sub, rect.x as i32, rect.y as i32 );
ctx.scroll_canvases.insert( my_idx, sub );
next_idx
}
Element::Viewport( v ) =>
{
let child_h = v.child.preferred_size( rect.width, canvas ).1;
let effective_h = child_h.max( rect.height );
let vw = ( rect.width.ceil() as u32 ).max( 1 );
let vh = ( rect.height.ceil() as u32 ).max( 1 );
let mut sub = canvas.sub_canvas( vw, vh );
sub.clear();
let child_rect = Rect { x: 0.0, y: 0.0, width: rect.width, height: effective_h };
let rects_before = ctx.widget_rects.len();
let scroll_rects_before = ctx.scroll_rects.len();
let next_idx = layout_and_draw::<Msg>( v.child.as_ref(), &mut sub, child_rect, ctx, flat_idx );
let new_rects: Vec<LaidOutWidget<Msg>> = ctx.widget_rects.drain( rects_before.. ).collect();
for mut w in new_rects
{
w.rect.x += rect.x;
w.rect.y += rect.y;
w.paint_rect.x += rect.x;
w.paint_rect.y += rect.y;
w.paint_rect = clamp_rect_to( w.paint_rect, rect );
if w.rect.y + w.rect.height > rect.y && w.rect.y < rect.y + rect.height
{
ctx.widget_rects.push( w );
}
}
// Translate scroll_rects pushed by nested scroll widgets
// from sub-canvas to surface space. Same reasoning as the
// scroll-inside-scroll case above.
let new_scroll_rects: Vec<( Rect, usize )> =
ctx.scroll_rects.drain( scroll_rects_before.. ).collect();
for ( mut r, idx ) in new_scroll_rects
{
r.x += rect.x;
r.y += rect.y;
let clamped = clamp_rect_to( r, rect );
if clamped.width > 0.0 && clamped.height > 0.0
{
ctx.scroll_rects.push( ( clamped, idx ) );
}
}
canvas.blit_fade_bottom( &sub, rect.x as i32, rect.y as i32, v.fade_bottom );
next_idx
}
other =>
{
// Gate the focus ring by `is_focusable`: a widget that opts out
// of keyboard focus (e.g. `Button::focusable(false)`) should not
// paint a ring even if it ends up in `focused_idx` after a tap.
let is_focused = ctx.focused_idx == Some( flat_idx ) && other.is_focusable();
let is_hovered = ctx.hovered_idx == Some( flat_idx );
let is_pressed = ctx.pressed_idx == Some( flat_idx );
let cursor_pos = ctx.cursor_state.get( &flat_idx ).copied().unwrap_or( 0 );
let sel_anchor = ctx.selection_anchor.get( &flat_idx ).copied().unwrap_or( cursor_pos );
let widget_id = match other
{
Element::Button( b ) => b.id,
Element::TextEdit( t ) => t.id,
Element::Toggle( t ) => t.id,
Element::Checkbox( c ) => c.id,
Element::Radio( r ) => r.id,
Element::ListItem( l ) => l.id,
Element::WindowButton( b ) => b.id,
_ => None,
};
other.draw( canvas, rect, is_focused, is_hovered, is_pressed, cursor_pos, sel_anchor );
if other.is_interactive()
{
ctx.widget_rects.push( LaidOutWidget
{
rect,
flat_idx,
id: widget_id,
paint_rect: other.paint_bounds( rect ),
handlers: other.handlers(),
keyboard_focusable: other.is_focusable(),
cursor: other.cursor_shape(),
} );
}
flat_idx + 1
}
}
}

327
src/draw/mod.rs Normal file
View File

@@ -0,0 +1,327 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! Per-frame drawing pipeline.
//!
//! The run loop hands each configured surface to [`draw_frame`] once per
//! vblank; this module walks it through a decision tree:
//!
//! * **Skip** — no content changed and no interaction state moved, so the
//! previously committed buffer is still correct.
//! * **Partial** — only focus / hover / pressed changed. Install a clip
//! mask covering the paint rects of the affected widgets, repaint only
//! under the clip, damage Wayland with exactly those rects.
//! * **Full** — something substantive changed (app message, animation
//! tick, configure, text edit, scroll, slider drag). Clear + redraw
//! the entire view, let damage tracking tighten the commit.
//!
//! Each of those paths has a software variant (CPU + SHM pool) and a
//! GLES variant (FBO + EGL swap). The four resulting functions live in
//! [`software`] and [`gles`]; this file is just the router plus the
//! small shared setup ([`DrawCtx`], [`pick_shm_format`]).
//!
//! # Submodule layout
//!
//! * [`software`] — `draw_surface_full` / `draw_surface_partial`
//! * [`gles`] — `draw_surface_full_gpu` / `draw_surface_partial_gpu`
//! * [`damage`] — `compute_interaction_dirty_rects`, `compute_damage`,
//! `clamp_rect_to`
//! * [`chrome`] — `draw_titlebar`, `apply_input_region`
//! * [`layout`] — `layout_and_draw` (the recursive element walker)
use std::collections::HashMap;
use std::sync::Arc;
use smithay_client_toolkit::reexports::client::protocol::{ wl_shm, wl_surface::WlSurface };
use smithay_client_toolkit::shm::Shm;
use crate::app::App;
use crate::event_loop::{ AppData, SurfaceFocus, SurfaceState };
use crate::render::Canvas;
use crate::types::{ Color, Rect };
use crate::widget::{ Element, LaidOutWidget };
pub( crate ) mod software;
pub( crate ) mod gles;
pub( crate ) mod damage;
pub( crate ) mod chrome;
pub( crate ) mod layout;
pub( crate ) use damage::{ compute_damage, compute_interaction_dirty_rects };
pub( crate ) use layout::layout_and_draw;
/// Pick the best wl_shm format for our RGBA-premultiplied pixmap.
///
/// Abgr8888 matches tiny-skia's byteorder on little-endian systems, so we can
/// copy with a plain memcpy. If the compositor doesn't advertise it, fall back
/// to Argb8888 (mandatory per wl_shm) which requires a per-channel swap.
///
/// Returns `(format, swap_rb)`.
pub( crate ) fn pick_shm_format( shm: &Shm ) -> ( wl_shm::Format, bool )
{
if shm.formats().contains( &wl_shm::Format::Abgr8888 )
{
( wl_shm::Format::Abgr8888, false )
} else {
( wl_shm::Format::Argb8888, true )
}
}
/// Per-frame draw state threaded through [`layout_and_draw`]. Captures
/// the interaction snapshot (focus / hover / pressed), scratch space
/// for the widget-rect list the frame will produce, and the scroll
/// offsets / sub-canvases carried across frames.
///
/// `scroll_canvases` arrives populated (the previous frame's
/// sub-canvases) so `layout_and_draw` can re-use them for Scroll
/// viewports whose size did not change. `scroll_rects` and
/// `widget_rects` start empty and get filled as the element tree is
/// walked.
pub( crate ) struct DrawCtx<Msg: Clone>
{
pub focused_idx: Option<usize>,
pub hovered_idx: Option<usize>,
pub pressed_idx: Option<usize>,
pub cursor_state: HashMap<usize, usize>,
pub selection_anchor: HashMap<usize, usize>,
pub widget_rects: Vec<LaidOutWidget<Msg>>,
pub debug_layout: bool,
pub scroll_offsets: HashMap<usize, f32>,
pub scroll_rects: Vec<(Rect, usize)>,
pub scroll_canvases: HashMap<usize, Canvas>,
/// Per-scroll navigation map: list of `(flat_idx, content_y, height)`
/// for every interactive item the scroll's child laid out, in
/// document order, **including items currently scrolled off-screen**.
/// Keyboard arrow handlers read this to step the runtime's
/// `hovered_idx` item-by-item without needing to know how the popup
/// content was composed. The Y is in pre-translation, pre-offset
/// coordinates (i.e. relative to the start of the scroll's child
/// content) so the keyboard auto-scroll can compute the offset
/// needed to bring an item into view without depending on the
/// current scroll position.
pub scroll_navigable_items: HashMap<usize, Vec<( usize, f32, f32 )>>,
/// Snapshot of the previous frame's `widget_rects`. Read by
/// [`crate::widget::anchored_overlay::AnchoredOverlay`] at draw time
/// to look up the rect of an anchor widget by [`crate::WidgetId`] and
/// re-position itself relative to that rect. Drivers populate this
/// before invoking the recursive layout / draw walk.
pub previous_widget_rects: Vec<LaidOutWidget<Msg>>,
}
/// Paint the built-in Copy / Cut / Paste context menu on top of the
/// finished surface content. Called from the software and GLES draw
/// paths right before `present()` so the menu sits above everything
/// the widget tree painted, matching the convention every other
/// toolkit follows for runtime-internal popups.
pub( crate ) fn draw_context_menu(
canvas: &mut crate::render::Canvas,
menu: &crate::event_loop::app_data::ContextMenu,
)
{
let palette = crate::theme::palette();
let bg = palette.surface;
let border = palette.divider;
let text = palette.text_primary;
let muted = palette.text_secondary;
let hi = palette.surface_alt;
let r = menu.rect;
canvas.fill_rect( r, bg, 8.0 );
canvas.stroke_rect( r, border, 1.0, 8.0 );
let ( ys, row_h ) = menu.row_ys();
// Row order: Copy / Cut / Paste / Delete. Labels go through
// `rust_i18n::t!()` so the menu picks up the active locale; the
// `enabled` flag mirrors the gating in `handle_context_menu_press`.
let labels: [ ( String, bool ); 4 ] =
[
( rust_i18n::t!( "context_menu.copy" ).to_string(), menu.has_selection ),
( rust_i18n::t!( "context_menu.cut" ).to_string(), menu.has_selection ),
( rust_i18n::t!( "context_menu.paste" ).to_string(), menu.can_paste ),
( rust_i18n::t!( "context_menu.delete" ).to_string(), menu.has_selection ),
];
// Subtle accent band on the row matching the *primary* action so
// the menu reads as "Paste is the default" when there is no
// selection (the common case for a paste-into-empty-field click)
// and "Copy is the default" when a selection is active. Just a
// hint, not a binding — every row still works on its own click.
let primary_idx = if menu.has_selection { 0 } else { 2 };
let primary_band = crate::types::Rect
{
x: r.x + 4.0, y: ys[ primary_idx ] + 2.0,
width: r.width - 8.0, height: row_h - 4.0,
};
canvas.fill_rect( primary_band, hi, 6.0 );
for ( i, ( label, enabled ) ) in labels.iter().enumerate()
{
let color = if *enabled { text } else { muted };
canvas.draw_text(
label,
r.x + 16.0,
ys[ i ] + row_h * 0.5 + 5.0,
14.0,
color,
);
}
// Thin separator between every pair of rows.
let sep_color = palette.divider;
for y in ys.iter().skip( 1 )
{
canvas.draw_line( r.x + 8.0, *y, r.x + r.width - 8.0, *y, sep_color, 1.0 );
}
}
pub( crate ) fn draw_frame<A: App>( data: &mut AppData<A> )
{
// Caches were refreshed by the run loop just before calling us; pull them
// by reference instead of re-invoking `App::view` / `App::overlays` each
// frame. The two `expect`s document the run loop's contract.
let main_view = data.cached_view.as_ref().expect( "view cache populated" );
let overlays = data.cached_overlays.as_ref().expect( "overlays cache populated" );
let main_bg = data.app.background_color();
let main_region = data.app.input_region();
let debug_layout = data.debug_layout;
let ( format, swap_rb ) = pick_shm_format( &data.shm );
let egl_ctx = data.egl_context.as_ref();
let qh = &data.qh;
if data.main.configured && data.main.needs_redraw && !data.main.frame_pending
{
let req_frame = | wl: &WlSurface | { let _ = wl.frame( qh, SurfaceFocus::Main ); };
draw_surface::<A::Message>(
&mut data.main,
&data.compositor_state,
egl_ctx,
main_view,
main_bg,
main_region.as_deref(),
debug_layout,
format,
swap_rb,
&req_frame,
);
data.main.needs_redraw = false;
data.main.last_draw = std::time::Instant::now();
}
for spec in overlays
{
if let Some( ss ) = data.overlays.get_mut( &spec.id )
{
if !ss.configured || !ss.needs_redraw || ss.frame_pending { continue; }
let focus = SurfaceFocus::Overlay( spec.id );
let req_frame = | wl: &WlSurface | { let _ = wl.frame( qh, focus ); };
let bg = Color::rgba( 0.0, 0.0, 0.0, 0.0 );
draw_surface::<A::Message>(
ss,
&data.compositor_state,
egl_ctx,
&spec.view,
bg,
spec.input_region.as_deref(),
debug_layout,
format,
swap_rb,
&req_frame,
);
ss.needs_redraw = false;
ss.last_draw = std::time::Instant::now();
}
}
}
/// Render one surface's current view. Picks between software and GLES,
/// and within each picks between full and partial redraw based on what
/// changed since the last committed frame.
///
/// The decision:
/// * **Skip** — `content_dirty` is false and no interaction state
/// changed. Previously committed buffer stays on screen.
/// * **Partial** — `content_dirty` is false but focus / hover / pressed
/// transitioned. Canvas is preserved across frames, so clip to the
/// dirty widgets and repaint only under the clip.
/// * **Full** — `content_dirty` is true. Clear + redraw + damage.
///
/// Partial eligibility also bails out when the total dirty area >50%
/// of the surface: at that ratio per-region clipping is no faster than
/// a plain full redraw, so the code prefers one big damage rect over
/// several small ones.
fn draw_surface<Msg: Clone>(
ss: &mut SurfaceState<Msg>,
compositor: &smithay_client_toolkit::compositor::CompositorState,
egl_ctx: Option<&Arc<crate::egl_context::EglContext>>,
view: &Element<Msg>,
bg: Color,
input_region: Option<&[Rect]>,
debug_layout: bool,
shm_format: wl_shm::Format,
swap_rb: bool,
request_frame: &dyn Fn( &WlSurface ),
)
{
let scale = ss.scale_factor.max( 1 ) as u32;
let w = ss.width;
let h = ss.height;
if w == 0 || h == 0 { return; }
let pw = w * scale;
let ph = h * scale;
// Decide partial-redraw eligibility BEFORE allocating a buffer. If we end
// up skipping the frame, we want to avoid touching the SHM pool at all.
let canvas_ready = ss.canvas.as_ref()
.map( |c| c.size() == ( pw, ph ) )
.unwrap_or( false );
let partial_eligible = !ss.content_dirty
&& canvas_ready
&& !ss.widget_rects.is_empty();
if partial_eligible
{
let dirty_rects = compute_interaction_dirty_rects(
&ss.widget_rects,
ss.prev_focused, ss.prev_hovered, ss.prev_pressed,
ss.focused_idx, ss.hovered_idx, ss.gesture.pressed_idx,
pw, ph,
);
if dirty_rects.is_empty()
{
// Nothing visible changed — keep the previously committed buffer.
return;
}
// Total dirty area > 50% of screen: a full redraw is no slower than
// per-region clipping but emits a single damage rect.
let total: f32 = dirty_rects.iter().map( |r| r.width * r.height ).sum();
if total < pw as f32 * ph as f32 * 0.5
{
if let ( Some( ctx ), true ) = ( egl_ctx, ss.egl_surface.is_some() )
{
gles::draw_surface_partial_gpu(
ss, compositor, ctx, view, bg, input_region,
dirty_rects, pw, ph, scale, request_frame,
);
} else {
software::draw_surface_partial(
ss, compositor, view, bg, input_region,
shm_format, swap_rb, dirty_rects, pw, ph, scale, request_frame,
);
}
return;
}
}
if let ( Some( ctx ), true ) = ( egl_ctx, ss.egl_surface.is_some() )
{
gles::draw_surface_full_gpu(
ss, compositor, ctx, view, bg, input_region, debug_layout,
pw, ph, scale, request_frame,
);
} else {
software::draw_surface_full(
ss, compositor, view, bg, input_region, debug_layout,
shm_format, swap_rb, pw, ph, scale, request_frame,
);
}
}

283
src/draw/software.rs Normal file
View File

@@ -0,0 +1,283 @@
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! Software (CPU + `wl_shm` pool) draw paths.
//!
//! Two functions, both symmetric with their GPU counterparts in
//! [`super::gles`]:
//!
//! * [`draw_surface_full`] — full redraw. Allocate a buffer, clear the
//! canvas, run layout+draw, write pixels to the SHM buffer, damage
//! the whole surface (or fine-grained rects from [`compute_damage`]),
//! commit.
//! * [`draw_surface_partial`] — clip-masked repaint. The canvas
//! pixmap from the previous frame is still valid; install a clip
//! covering only the dirty rects, repaint the background + title bar
//! + widget tree under the clip, and damage Wayland with exactly
//! those rects.
//!
//! Both paths share the DrawCtx / `layout_and_draw` / `draw_titlebar`
//! / `apply_input_region` helpers with the GPU path.
use std::sync::Arc;
use smithay_client_toolkit::compositor::CompositorState;
use smithay_client_toolkit::reexports::client::protocol::{ wl_shm, wl_surface::WlSurface };
use crate::event_loop::SurfaceState;
use crate::render::Canvas;
use crate::types::{ Color, Rect };
use crate::widget::Element;
use super::{ DrawCtx, compute_damage, layout_and_draw };
use super::chrome::{ apply_input_region, draw_fallback_banner, draw_titlebar };
/// Full redraw path: clear the canvas, run layout+draw for every widget, then
/// emit either tight per-widget damage or a single full-surface damage rect
/// depending on what [`compute_damage`] derives.
pub( crate ) fn draw_surface_full<Msg: Clone>(
ss: &mut SurfaceState<Msg>,
compositor: &CompositorState,
view: &Element<Msg>,
bg: Color,
input_region: Option<&[Rect]>,
debug_layout: bool,
shm_format: wl_shm::Format,
swap_rb: bool,
pw: u32,
ph: u32,
scale: u32,
request_frame: &dyn Fn( &WlSurface ),
)
{
let Some( pool ) = ss.pool.as_mut() else { return };
let stride = pw * 4;
let ( buffer, canvas_buf ) = match pool.create_buffer(
pw as i32, ph as i32, stride as i32, shm_format,
)
{
Ok( r ) => r,
Err( _ ) => return,
};
let canvas = ss.canvas.get_or_insert_with( || {
let mut c = Canvas::new( pw, ph );
c.set_dpi_scale( scale as f32 );
if let Some( reg ) = crate::theme::build_font_registry()
{
c.set_font_registry( Arc::new( reg ) );
}
c
} );
if canvas.size() != ( pw, ph )
{
canvas.resize( pw, ph );
canvas.set_dpi_scale( scale as f32 );
}
canvas.clear_clip();
let sf = scale as f32;
let tb_h = ss.titlebar_height * sf;
let screen_rect = Rect { x: 0.0, y: tb_h, width: pw as f32, height: (ph as f32 - tb_h).max( 0.0 ) };
if bg.a > 0.0 { canvas.fill( bg ); } else { canvas.clear(); }
ss.titlebar_close_rect = draw_titlebar( canvas, &ss.titlebar_title, pw, tb_h, sf );
let mut ctx: DrawCtx<Msg> = DrawCtx
{
focused_idx: ss.focused_idx,
hovered_idx: ss.hovered_idx,
pressed_idx: ss.gesture.pressed_idx,
cursor_state: std::mem::take( &mut ss.cursor_state ),
selection_anchor: std::mem::take( &mut ss.selection_anchor ),
widget_rects: Vec::new(),
debug_layout,
scroll_offsets: std::mem::take( &mut ss.scroll_offsets ),
scroll_rects: Vec::new(),
scroll_canvases: std::mem::take( &mut ss.scroll_canvases ),
scroll_navigable_items: std::mem::take( &mut ss.scroll_navigable_items ),
previous_widget_rects: ss.widget_rects.clone(),
};
layout_and_draw::<Msg>( view, canvas, screen_rect, &mut ctx, 0 );
if ctx.debug_layout
{
for w in &ctx.widget_rects
{
canvas.stroke_rect( w.rect, Color::rgb( 1.0, 0.0, 0.0 ), 1.5, 0.0 );
}
}
if let Some( ref menu ) = ss.context_menu
{
super::draw_context_menu( canvas, menu );
}
// Fallback-theme warning. Painted last so it sits on top of every
// widget; no-op when the real theme is loaded.
draw_fallback_banner( canvas, pw, sf );
let damage_rects = if ss.content_dirty
{
Vec::new()
} else {
compute_damage(
&ss.widget_rects,
&ctx.widget_rects,
ss.prev_focused,
ss.prev_hovered,
ss.prev_pressed,
ss.focused_idx,
ss.hovered_idx,
ss.gesture.pressed_idx,
pw, ph,
)
};
ss.prev_focused = ss.focused_idx;
ss.prev_hovered = ss.hovered_idx;
ss.prev_pressed = ss.gesture.pressed_idx;
ss.widget_rects = ctx.widget_rects;
ss.scroll_rects = ctx.scroll_rects;
ss.scroll_canvases = std::mem::take( &mut ctx.scroll_canvases );
ss.cursor_state = ctx.cursor_state;
ss.selection_anchor = ctx.selection_anchor;
ss.scroll_offsets = ctx.scroll_offsets;
ss.scroll_navigable_items = ctx.scroll_navigable_items;
ss.content_dirty = false;
canvas.write_to_wayland_buf( canvas_buf, swap_rb );
let wl_surface = ss.surface.wl_surface();
buffer.attach_to( wl_surface ).expect( "attach" );
if damage_rects.is_empty()
{
wl_surface.damage_buffer( 0, 0, pw as i32, ph as i32 );
} else {
for r in &damage_rects
{
wl_surface.damage_buffer( r.x as i32, r.y as i32, r.width as i32, r.height as i32 );
}
}
apply_input_region( wl_surface, compositor, input_region );
// Request a frame callback BEFORE commit so the compositor schedules it
// against this exact frame; sets `frame_pending` so the run loop won't
// try to draw this surface again until the callback fires.
request_frame( wl_surface );
wl_surface.commit();
ss.frame_pending = true;
}
/// Partial redraw: install a clip mask covering only `dirty_rects`, repaint
/// the background + title bar + widget tree under that mask (so unchanged
/// pixels from the previous frame stay), and damage Wayland with exactly
/// those rects.
pub( crate ) fn draw_surface_partial<Msg: Clone>(
ss: &mut SurfaceState<Msg>,
compositor: &CompositorState,
view: &Element<Msg>,
bg: Color,
input_region: Option<&[Rect]>,
shm_format: wl_shm::Format,
swap_rb: bool,
dirty_rects: Vec<Rect>,
pw: u32,
ph: u32,
scale: u32,
request_frame: &dyn Fn( &WlSurface ),
)
{
let Some( pool ) = ss.pool.as_mut() else { return };
let stride = pw * 4;
let ( buffer, canvas_buf ) = match pool.create_buffer(
pw as i32, ph as i32, stride as i32, shm_format,
)
{
Ok( r ) => r,
Err( _ ) => return,
};
// Canvas pixels from the previous frame are still valid for the unclipped
// region and serve as our background — do not call clear()/fill() here.
let canvas = ss.canvas.as_mut().expect( "partial path requires existing canvas" );
canvas.set_clip_rects( &dirty_rects );
let sf = scale as f32;
let tb_h = ss.titlebar_height * sf;
let screen_rect = Rect { x: 0.0, y: tb_h, width: pw as f32, height: (ph as f32 - tb_h).max( 0.0 ) };
// Repaint surface background under the clip so the dirty rects start from
// a known state instead of leaking the previous widget's pixels.
if bg.a > 0.0 { canvas.fill( bg ); }
else
{
canvas.clear_rects_transparent( &dirty_rects );
}
ss.titlebar_close_rect = draw_titlebar( canvas, &ss.titlebar_title, pw, tb_h, sf );
let mut ctx: DrawCtx<Msg> = DrawCtx
{
focused_idx: ss.focused_idx,
hovered_idx: ss.hovered_idx,
pressed_idx: ss.gesture.pressed_idx,
cursor_state: std::mem::take( &mut ss.cursor_state ),
selection_anchor: std::mem::take( &mut ss.selection_anchor ),
widget_rects: Vec::new(),
debug_layout: false,
scroll_offsets: std::mem::take( &mut ss.scroll_offsets ),
scroll_rects: Vec::new(),
scroll_canvases: std::mem::take( &mut ss.scroll_canvases ),
scroll_navigable_items: std::mem::take( &mut ss.scroll_navigable_items ),
previous_widget_rects: ss.widget_rects.clone(),
};
layout_and_draw::<Msg>( view, canvas, screen_rect, &mut ctx, 0 );
if let Some( ref menu ) = ss.context_menu
{
super::draw_context_menu( canvas, menu );
}
// Fallback-theme warning. Painted last so it sits on top of every
// widget; no-op when the real theme is loaded. If the banner's row
// happens to fall outside the partial-redraw clip, the previous
// frame's banner is still on the canvas (pixmap preserved), which
// is the correct behaviour.
draw_fallback_banner( canvas, pw, sf );
canvas.clear_clip();
ss.prev_focused = ss.focused_idx;
ss.prev_hovered = ss.hovered_idx;
ss.prev_pressed = ss.gesture.pressed_idx;
ss.widget_rects = ctx.widget_rects;
ss.scroll_rects = ctx.scroll_rects;
ss.scroll_canvases = std::mem::take( &mut ctx.scroll_canvases );
ss.cursor_state = ctx.cursor_state;
ss.selection_anchor = ctx.selection_anchor;
ss.scroll_offsets = ctx.scroll_offsets;
ss.scroll_navigable_items = ctx.scroll_navigable_items;
ss.content_dirty = false;
canvas.write_to_wayland_buf( canvas_buf, swap_rb );
let wl_surface = ss.surface.wl_surface();
buffer.attach_to( wl_surface ).expect( "attach" );
for r in &dirty_rects
{
wl_surface.damage_buffer( r.x as i32, r.y as i32, r.width as i32, r.height as i32 );
}
apply_input_region( wl_surface, compositor, input_region );
request_frame( wl_surface );
wl_surface.commit();
ss.frame_pending = true;
}