ltk/event_loop/surface.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
use std::collections::HashMap;
use crate::app::{ OverlayId, SurfaceTarget };
use crate::input::GestureState;
use crate::platform::NativeSurface;
use crate::render::Canvas;
use crate::types::{ Point, Rect, WidgetId };
use crate::widget::LaidOutWidget;
/// Identifies which surface an event, focus, or draw call belongs to.
///
/// `Main` refers to the application's main surface (xdg window or layer
/// shell). `Overlay( id )` refers to an auxiliary layer-shell surface created
/// from an entry in [`crate::app::App::overlays`].
#[ derive( Debug, Clone, Copy, PartialEq, Eq, Hash ) ]
pub( crate ) enum SurfaceFocus
{
Main,
#[ allow( dead_code ) ]
Overlay( OverlayId ),
}
impl SurfaceFocus
{
pub( crate ) fn target( self ) -> SurfaceTarget
{
match self
{
SurfaceFocus::Main => SurfaceTarget::Main,
SurfaceFocus::Overlay( id ) => SurfaceTarget::Overlay( id ),
}
}
}
/// The subset of per-surface state the draw pass owns and threads through
/// [`crate::draw::DrawCtx`]: the laid-out widget rects it produces, the scroll /
/// text-edit / a11y state carried across frames, and the previous frame's
/// interaction indices for damage tracking. Grouped into its own struct so the
/// draw helpers can borrow it as one unit, disjoint from `canvas` / `pool`.
pub( crate ) struct FrameState<Msg: Clone>
{
pub widget_rects: Vec<LaidOutWidget<Msg>>,
pub cursor_state: HashMap<usize, usize>,
/// Selection anchor (byte offset). When equal to the cursor, there is no
/// active selection. Mutated jointly with `cursor_state`: plain arrow keys
/// collapse the selection by setting anchor = cursor; Shift+arrow extends by
/// leaving anchor put while moving cursor; pointer drags set both ends.
pub selection_anchor: HashMap<usize, usize>,
/// Where each multiline field was last scrolled by hand, by `flat_idx`.
pub text_scroll: HashMap<usize, crate::widget::text_edit::TextScroll>,
pub accessible_extras: Vec<crate::a11y::tree::AccessibleExtra>,
/// Per-scroll-viewport offset, indexed by `flat_idx` of the `Scroll` widget.
/// Tuple is `(x, y)` in physical pixels: x is applied only when the widget's
/// axis allows horizontal scroll (and stays at `0` otherwise), y mirrors the
/// historic single-f32 behaviour for vertical scrolls.
pub scroll_offsets: HashMap<usize, ( f32, f32 )>,
pub scroll_rects: Vec<( Rect, usize, crate::widget::scroll::ScrollAxis )>,
pub scroll_canvases: HashMap<usize, Canvas>,
pub viewport_canvases: HashMap<usize, Canvas>,
/// Per-scroll list of `(flat_idx, content_y, height)` entries for every
/// interactive item the scroll's child laid out, in document order. Includes
/// items currently scrolled off-screen so keyboard arrow handlers can step
/// `hovered_idx` item-by-item without regenerating the layout pass. Y is in
/// pre-translation, pre-offset content coordinates.
pub scroll_navigable_items: HashMap<usize, Vec<( usize, f32, f32 )>>,
/// Widgets with a [`WidgetId`] clipped out of `widget_rects` by a scroll
/// viewport this frame: `(id, scroll flat_idx, rect)` in content coordinates.
pub scroll_clipped: Vec<( WidgetId, usize, Rect )>,
/// Previous frame interaction state for damage tracking.
pub prev_focused: Option<usize>,
pub prev_hovered: Option<usize>,
pub prev_pressed: Option<usize>,
/// `blur_behind` containers of the last frame, and whether they changed since reported.
pub blur_regions: Vec<( Rect, f32 )>,
pub blur_changed: bool,
}
impl<Msg: Clone> FrameState<Msg>
{
pub( crate ) fn new() -> Self
{
Self
{
widget_rects: Vec::new(),
cursor_state: HashMap::new(),
selection_anchor: HashMap::new(),
text_scroll: HashMap::new(),
accessible_extras: Vec::new(),
scroll_offsets: HashMap::new(),
scroll_rects: Vec::new(),
scroll_canvases: HashMap::new(),
viewport_canvases: HashMap::new(),
scroll_navigable_items: HashMap::new(),
scroll_clipped: Vec::new(),
prev_focused: None,
prev_hovered: None,
prev_pressed: None,
blur_regions: Vec::new(),
blur_changed: false,
}
}
}
/// Logical pixels along each edge of a surface that the system covers: status and navigation bars, a keyboard.
#[ derive( Clone, Copy, Debug, Default, PartialEq ) ]
pub( crate ) struct Insets
{
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}
/// Per-surface render + interaction state.
///
/// Each Wayland surface managed by the event loop (main surface and any
/// active overlays) owns an instance of this struct, so multiple surfaces
/// can coexist without interfering.
pub( crate ) struct SurfaceState<Msg: Clone, S = NativeSurface>
{
/// The platform's half: on Wayland the role object, the SHM pool or EGL window surface, and what the compositor was last told.
pub platform: S,
pub canvas: Option<Canvas>,
pub width: u32,
pub height: u32,
pub configured: bool,
pub needs_redraw: bool,
/// Set to `true` when the app's view may have changed in a way that rects
/// don't capture (text content, progress value, slider thumb position, etc).
/// Interaction-only transitions (hover in/out, pressed in/out) leave this
/// `false` so the draw path can take the partial-redraw fast path.
/// Always reset to `false` at the end of a successful draw.
pub content_dirty: bool,
pub last_draw: crate::time::Instant,
pub focused_idx: Option<usize>,
pub focused_id: Option<WidgetId>,
/// The keyboard moved the focus last, so the focused widget shows its ring; a press does not.
pub focus_visible: bool,
pub hovered_idx: Option<usize>,
pub pending_text_values: HashMap<usize, String>,
/// Per-frame draw state: laid-out rects, carried scroll / text-edit / a11y
/// state, and the previous frame's interaction indices. Grouped so the draw
/// helpers can borrow it as one unit, disjoint from `canvas` / `pool`.
pub frame: FrameState<Msg>,
/// Built-in Copy / Cut / Paste context menu when shown on this
/// surface. `None` means no menu is up.
pub context_menu: Option<super::context_menu::ContextMenu>,
/// The built-in on-screen keyboard while a text field of this surface has the focus and no input method serves it.
pub osk: Option<crate::osk::Panel>,
/// Per-surface gesture state machine. Owns the press →
/// (long-press? / drag? / scroll? / swipe?) → release lifecycle,
/// driven by both pointer and touch handlers. The input layer
/// (`src/input/`) calls the lifecycle methods; the long-press
/// deadline poller reaches into `gesture.long_press_*` directly.
pub gesture: GestureState<Msg>,
/// `wl_touch.id` of the finger currently driving the single-slot
/// gesture machine. `None` when no finger is down on this surface.
/// Subsequent fingers landing while this is `Some` route through
/// the auxiliary multi-touch path ([`App::on_touch_down`] etc.)
/// instead of being absorbed into the primary slot.
pub primary_touch_id: Option<i32>,
/// Auxiliary touch slots: every non-primary finger's last known
/// position, keyed by `wl_touch.id`. Used by the touch handler to
/// generate `on_touch_up` with the correct release point (Wayland
/// `wl_touch.up` does not carry a position) and to keep state
/// across `motion` events between dispatchers.
pub touch_slots: HashMap<i32, crate::types::Point>,
/// Height of the client-side title bar (0 for layer-shell surfaces).
pub titlebar_height: f32,
/// Where the view is not laid out because the system covers it; the background still fills it.
pub insets: Insets,
/// Title text shown in the client-side title bar.
pub titlebar_title: String,
/// Rect of the close button in the title bar (for hit testing).
pub titlebar_close_rect: Rect,
/// Physical pixels per logical pixel, set by the backend: whole on
/// Wayland and Android, the browser's `devicePixelRatio` on the web.
/// Used to size the buffers and set `dpi_scale` on the canvas.
pub scale_factor: f32,
pub layer_anchor: Option<crate::app::Anchor>,
/// `true` after the surface has been committed and we are waiting for the
/// matching `wl_surface.frame` callback to fire. Drawing is gated on this
/// being `false`: even if `needs_redraw` flips back to `true` we sit on
/// the next frame until the compositor signals it's time to commit again,
/// so the per-surface pacing follows the compositor (and the display
/// refresh / VRR / "screen is off") instead of a fixed-period timer.
pub frame_pending: bool,
/// Set by the frame callback while the app animates by moving
/// subsurfaces only; the subsurface reconcile keeps the cadence
/// with a bare frame request + commit when nothing moved.
pub frame_tick_due: bool,
}
impl<Msg: Clone, S> SurfaceState<Msg, S>
{
pub( crate ) fn new( platform: S, titlebar_height: f32, titlebar_title: String ) -> Self
{
Self {
platform,
canvas: None,
width: 0,
height: 0,
configured: false,
needs_redraw: false,
content_dirty: true,
last_draw: crate::time::Instant::now().checked_sub( std::time::Duration::from_millis( 100 ) ).unwrap_or_else( crate::time::Instant::now ),
focused_idx: None,
focused_id: None,
focus_visible: false,
hovered_idx: None,
pending_text_values: HashMap::new(),
frame: FrameState::new(),
primary_touch_id: None,
touch_slots: HashMap::new(),
context_menu: None,
osk: None,
gesture: GestureState::new(),
titlebar_height,
insets: Insets::default(),
titlebar_title,
titlebar_close_rect: Rect::default(),
scale_factor: 1.0,
layer_anchor: None,
frame_pending: false,
frame_tick_due: false,
}
}
/// Convert a logical (surface-local) position to physical pixel coordinates.
pub( crate ) fn to_physical( &self, x: f64, y: f64 ) -> Point
{
let sf = self.scale_factor;
Point { x: x as f32 * sf, y: y as f32 * sf }
}
/// Surface width in physical pixels (logical × scale, rounded). Matches the
/// coordinate space used by pointer/touch callbacks and layout, so swipe
/// thresholds can be compared against physical `dx` / `start.x` without
/// unit mixing.
pub( crate ) fn physical_width( &self ) -> u32
{
( self.width as f32 * self.scale_factor ).round() as u32
}
/// Surface height in physical pixels. See [`Self::physical_width`].
pub( crate ) fn physical_height( &self ) -> u32
{
( self.height as f32 * self.scale_factor ).round() as u32
}
/// The scale as a whole number, for protocols that take no other: Wayland's buffer scale.
pub( crate ) fn buffer_scale( &self ) -> i32
{
( self.scale_factor.round() as i32 ).max( 1 )
}
/// Request a redraw and mark the surface's content as dirty.
///
/// Use this from every site that potentially changes what the app's view
/// returns (text edits, scroll offset, slider value, app messages, animation
/// tick, configure). Pure hover/pressed transitions should leave
/// `content_dirty` alone and only set `needs_redraw` directly so the draw
/// pass can take the cheap partial-redraw path.
pub( crate ) fn request_redraw( &mut self )
{
self.needs_redraw = true;
self.content_dirty = true;
}
/// Take `w × h` logical pixels as the surface's size once the backend has resized its buffers, and redraw it whole.
pub( crate ) fn set_size( &mut self, w: u32, h: u32 )
{
self.width = w;
self.height = h;
self.configured = true;
self.request_redraw();
}
}