Files
ltk/src/draw/paint.rs
T
admin 02ab10b3ef
CI / build + test (push) Canceled after 0s
CI / cargo audit (push) Canceled after 0s
State restored on an ordinary launch for apps that ask, focus that follows its widget's id, buttons that do not take the focus when pressed, a focus ring only after the keyboard, and a browser app's surfaces copied rather than transferred, which WebKit got wrong
Restore on launch. `restore_state` follows Android's saved-instance-state contract: the saved bytes come back after a crash or a session restore, and a launch from the launcher starts fresh. Some apps keep state their users expect to find however the last run ended, as an Android browser keeps its tabs in its own storage even when closed from the app switcher. `App::restore_on_launch`, false by default, has the runtime restore on a plain launch too; `SessionRuntime::bootstrap` asks it before deciding. Saving, the file layout and the window geometry are the same either way. Its documentation explains when it is asked, that it is not when persistence is off, that `restore_state` must then merge what the launch itself asks for, such as a URL on the command line, and that what `save_state` returns now outlives every exit; it carries a compiled example. `restore_state`'s documentation, `docs/onboarding.md` and the cookbook's session state recipe mention it.
Focus on a press. `Button::focusable( false )` and `WindowButton` kept out of the Tab cycle but still took the focus when pressed, and Enter then pressed them again, which closed a browser's tab when the user pressed Enter in a page after closing another tab. `LaidOutWidget` gains `focus_on_press`, from `Element::focus_on_press`: a button's `focusable`, a `WindowButton`'s, a pressable's new `Pressable::focus_on_press`, true by default, and true for every other widget. `focus_pressed` replaces `set_focus` for pointer and touch presses and leaves the focus where it was when the widget does not take it. Enter's fallback to the widget under the pointer, which `hovered_idx` follows, skips such widgets too, and a rebuild that leaves the focus on one drops it (`drop_misplaced_focus`). The close buttons of `tab_strip`, on the desktop and on the phone's cards, are not focusable; `symbol_button` takes whether its button is.
Focus by id. The focus was held as the index of a widget in the laid-out tree, so a rebuild that inserted or removed widgets before it moved it to whatever widget took that index. `WidgetId` becomes a name and a key, `WidgetId::keyed( name, key )` telling apart widgets of the same kind, such as the tabs of a strip; `WidgetId( "name" )` still builds one, through a `const fn` of that name, so the calls in every app compile unchanged, and only code that read `.0`, the toasts, the combo and the tooltip here, moves to the derived `Hash` or `name()`. After each layout `follow_focused_id` finds the focused id and moves the focus to its new index with the field's pending text, cursor, selection and scroll; it drops the focus when the widget is gone, keeps it when a scroll only clipped it, and leaves it when the widget at the old index still has the id. `draw_surface` returns whether the focus moved, and its callers draw the surface again rather than marking it done, since the frame just drawn showed the focus in the old place. Widgets without an id keep the index. Each tab and each card of `tab_strip` carries `WidgetId::keyed` with the tab's key, so a chosen tab keeps the focus while others close.
Focus ring. A press that focused a button, a toggle or a list item left its ring drawn, which browsers have not done since `:focus-visible`. `SurfaceState::focus_visible` is set by Tab and Shift+Tab and cleared by a press that moves the focus, `show_focus_ring` redrawing the whole surface when it changes, since the partial redraw only sees indices. The draw is given the focused index only while the ring shows or the widget is a text field, which draws its cursor however it was focused; the focus itself is unchanged, so Enter and Space still press the widget.
Key repeat. A key repeated by the platform rather than by ltk's own timer reached the focused widget even while `App::claims_keyboard` was true; `key_repeated` checks it as `key_press` does.
Browser surfaces. Every surface is painted through the app's one WebGL context on one `OffscreenCanvas`, and was handed to its own canvas, a `bitmaprenderer`, with `transferToImageBitmap`. WebKit reuses the buffer of a bitmap it was handed, so in a WebKit browser each surface showed another's frame, or none, and only the last one painted was right: forge/web's background, dock and windows came and went in a WPE browser while Chromium showed them all. A test page with two canvases fed from one offscreen canvas showed their colours swapped in WPE and right with a copy. Each surface's canvas is now a `2d` one, and `present_copy` copies the offscreen canvas with `drawImage` in `copy` composition, set before every copy since resizing a canvas resets its context, so a transparent frame replaces the last rather than leaving trails behind an animation. Subsurfaces go the same way. `WebSurfaceState` loses `bitmap` and `new` its `gpu` argument, and web-sys loses the `ImageBitmap` and `ImageBitmapRenderingContext` features.
CHANGELOG records each of these.
Not done. The tests that build `LaidOutWidget` by hand set the new field, but no test covers a press on a non-focusable button, the focus following an id or the ring. For one frame after a rebuild moves the focused widget, its ring and its cursor may show in the old place.
2026-11-01 09:19:23 +01:00

186 lines
6.3 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! Painting a surface's view on its canvas, the same for every backend and renderer. The backend prepares the canvas before and presents it after; see [`crate::platform::Platform`].
use std::collections::HashMap;
use std::sync::Arc;
use crate::event_loop::SurfaceState;
use crate::render::Canvas;
use crate::types::{ Color, Rect };
use crate::widget::Element;
use super::{ build_draw_ctx, commit_draw_ctx, compute_damage, layout_and_draw, DrawCtx };
use super::chrome::{ draw_fallback_banner, draw_titlebar };
/// The canvas in `slot` at `pw × ph`, built by `create` with the theme's fonts and `scale` on first use.
pub( crate ) fn fit_canvas( slot: &mut Option<Canvas>, pw: u32, ph: u32, scale: f32, create: impl FnOnce() -> Canvas ) -> &mut Canvas
{
let canvas = slot.get_or_insert_with( ||
{
let mut c = create();
c.set_dpi_scale( scale );
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 );
}
canvas
}
/// Paint `view` over the whole of `canvas`, cleared to transparent, with no focus, hover or press, for a surface that takes no input such as a subsurface. `scroll` and `viewport` keep its sub-canvases between paints.
pub( crate ) fn paint_detached<Msg: Clone>( canvas: &mut Canvas, view: &Element<Msg>, scroll: &mut HashMap<usize, Canvas>, viewport: &mut HashMap<usize, Canvas> )
{
canvas.clear_clip();
canvas.clear();
let ( pw, ph ) = canvas.size();
let screen_rect = Rect { x: 0.0, y: 0.0, width: pw as f32, height: ph as f32 };
let mut ctx = DrawCtx
{
focused_idx: None,
hovered_idx: None,
pressed_idx: None,
cursor_state: HashMap::new(),
selection_anchor: HashMap::new(),
text_scroll: HashMap::new(),
widget_rects: Vec::new(),
debug_layout: false,
scroll_offsets: HashMap::new(),
scroll_rects: Vec::new(),
scroll_canvases: std::mem::take( scroll ),
viewport_canvases: std::mem::take( viewport ),
viewport_seq: 0,
scroll_navigable_items: HashMap::new(),
scroll_clipped: Vec::new(),
previous_widget_rects: Vec::new(),
accessible_extras: Vec::new(),
live_depth: 0,
origin: ( 0.0, 0.0 ),
blur_regions: Vec::new(),
};
layout_and_draw::<Msg>( view, canvas, screen_rect, &mut ctx, 0 );
*scroll = ctx.scroll_canvases;
*viewport = ctx.viewport_canvases;
}
/// Repaint the whole surface. Returns the rects that changed when `precise_damage` asks for them and the content did not change wholesale, else none, meaning the whole surface.
pub( crate ) fn paint_full<Msg: Clone, S>(
ss: &mut SurfaceState<Msg, S>,
view: &Element<Msg>,
bg: Color,
debug_layout: bool,
precise_damage: bool,
pw: u32,
ph: u32,
scale: f32,
) -> Vec<Rect>
{
let canvas = ss.canvas.as_mut().expect( "canvas prepared" );
canvas.clear_clip();
if bg.a > 0.0 { canvas.fill( bg ); } else { canvas.clear(); }
let ctx = paint_view( ss, view, debug_layout, pw, ph, scale );
let damage = if ss.content_dirty || !precise_damage
{
Vec::new()
} else {
compute_damage(
&ss.frame.widget_rects,
&ctx.widget_rects,
ss.frame.prev_focused,
ss.frame.prev_hovered,
ss.frame.prev_pressed,
ss.focused_idx,
ss.hovered_idx,
ss.gesture.pressed_idx,
pw, ph,
)
};
commit_draw_ctx( &mut ss.frame, ss.focused_idx, ss.hovered_idx, ss.gesture.pressed_idx, ctx );
ss.content_dirty = false;
damage
}
/// Repaint only under `dirty_rects`, keeping the rest of the previous frame's pixels, and return them as the damage.
pub( crate ) fn paint_partial<Msg: Clone, S>(
ss: &mut SurfaceState<Msg, S>,
view: &Element<Msg>,
bg: Color,
dirty_rects: Vec<Rect>,
pw: u32,
ph: u32,
scale: f32,
) -> Vec<Rect>
{
let canvas = ss.canvas.as_mut().expect( "canvas prepared" );
canvas.set_clip_rects( &dirty_rects );
// Start the dirty rects from the background rather than the previous widget's pixels.
if bg.a > 0.0 { canvas.fill( bg ); } else { canvas.clear_rects_transparent( &dirty_rects ); }
let ctx = paint_view( ss, view, false, pw, ph, scale );
if let Some( canvas ) = ss.canvas.as_mut() { canvas.clear_clip(); }
commit_draw_ctx( &mut ss.frame, ss.focused_idx, ss.hovered_idx, ss.gesture.pressed_idx, ctx );
ss.content_dirty = false;
dirty_rects
}
/// The title bar, the widget tree and what the runtime draws over it, on a canvas already cleared where needed.
fn paint_view<Msg: Clone, S>(
ss: &mut SurfaceState<Msg, S>,
view: &Element<Msg>,
debug_layout: bool,
pw: u32,
ph: u32,
scale: f32,
) -> DrawCtx<Msg>
{
let canvas = ss.canvas.as_mut().expect( "canvas prepared" );
let sf = scale;
let tb_h = ss.titlebar_height * sf;
let inset = ss.insets;
let osk_h = crate::event_loop::osk::place_osk( &mut ss.osk, pw, ph, sf, inset );
let top = tb_h + inset.top * sf;
let screen_rect = Rect
{
x: inset.left * sf,
y: top,
width: ( pw as f32 - ( inset.left + inset.right ) * sf ).max( 0.0 ),
height: ( ph as f32 - top - osk_h - inset.bottom * sf ).max( 0.0 ),
};
ss.titlebar_close_rect = draw_titlebar( canvas, &ss.titlebar_title, pw, tb_h, sf );
// A text field draws its cursor when focused however the focus came.
let drawn_focus = ss.focused_idx.filter( |&idx| ss.focus_visible || crate::tree::find_handlers( &ss.frame.widget_rects, idx ).is_some_and( |h| h.is_text_input() ) );
let mut ctx = build_draw_ctx( &mut ss.frame, drawn_focus, ss.hovered_idx, ss.gesture.pressed_idx, debug_layout );
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( panel ) = ss.osk.as_mut() { panel.draw( canvas ); }
if let Some( ref menu ) = ss.context_menu
{
super::draw_context_menu( canvas, menu );
}
// Last, so it sits over every widget. Outside a partial repaint's clip the previous frame's banner stays.
draw_fallback_banner( canvas, pw, sf );
ctx
}