Files
ltk/src/event_loop/context_menu.rs
Pedro M. de Echanove Pasquin d4d7ee742e
Some checks failed
CI / build + test (push) Has been cancelled
CI / cargo audit (push) Has been cancelled
Bump to 0.2.0: SW/GLES paint parity, shared font resolution, FrameState refactor, docs and packaging fixes
Rendering parity (software ↔ GLES). The software backend now rounds glyph pen positions and image destinations to the nearest integer pixel, matching what the GLES backend already did; previously it truncated, so text and 1:1 images could land up to half a pixel off between the two backends and the bilinear sample read ~1 px softer than the source. Gradients and shadows are deliberately left unimplemented on the software backend, and the GLES multi-rect `glScissor` clip is left coarse on purpose: making it exact would need stencil bits the EGL config does not carry, or routing the partial-redraw path through the offscreen clip layer, which would break its `fill` / `clear_rects_transparent` scissor semantics. Adds software-backend pixel tests covering the snapping.
Font resolution unification. The system-font candidate chain, `find_font_opt` and `load_default_font_bytes` lived in two copies (`render/helpers` and `gles_render/helpers`) that had already diverged — one resolved through `find_font_opt`, the other inlined the candidate loop — and now live once in `system_fonts`. The two per-backend `OnceLock` default-font caches and `primary_handle` collapse into a single `system_fonts::default_handle`. Module docs and the `font_registry` caller are updated accordingly.
Shared image validation and rect inflation. `draw_image_data`'s dimension check and its one-line warning were byte-duplicated across both backends and are now `render::helpers::validate_rgba_dims`. The six manual symmetric `Rect`-inflate literals in the GLES primitives reuse the existing `Rect::expand`.
FrameState and DrawCtx de-duplication. The eleven `SurfaceState` fields the draw pass owns and threads through `DrawCtx` — `widget_rects`, the cursor / selection maps, the scroll state, `accessible_extras`, `prev_focused` / `prev_hovered` / `prev_pressed` — move into a `FrameState` sub-struct. The per-frame `build_draw_ctx` / `commit_draw_ctx` helpers can then borrow `&mut ss.frame`, disjoint from `ss.canvas` and `ss.pool`, so the four frame paths (software / GLES × full / partial) replace their duplicated `DrawCtx` construction and write-back with a single helper call each. A whole-`SurfaceState` borrow could not express this (partial borrows do not cross function boundaries), which is why the helpers take the sub-struct. `content_dirty` stays on `SurfaceState` — it is an invalidation flag, not frame state — and is reset at the call site.
rich_text tests. Adds the previously-missing `tests.rs` for the `RichText` widget: one hit rect per visual line a link spans (the widget's core invariant), the single-line and no-link cases, preferred-size growth with hard line breaks, and `map_msg` range preservation — all headless against a software `Canvas`, with line counts forced by `\n` so they do not depend on any system font's measured width.
Documentation. Fills the rustdoc gaps on the embedder-facing surface: `core::UiSurface` accessors, the `egl_context` public API, the `GlesCanvas` methods, `theme::typography` and `theme::error`, and the `RichText` / `Text` builders; adds a crate-level "Rendering backends" overview. `CHANGELOG.md` is added (0.2.0 / 0.1.0), and `docs/widgets.md` / `docs/cookbook.md` gain `rich_text`, `external`, and the CPU-draw / path-clip / externally-laid-out-tree recipes. `debian/changelog` gets the 0.2.0-1 entry. Private intra-doc links to `system_fonts` are demoted to code spans so `cargo doc` is warning-free.
Packaging. The `libltk-dev` registry crate shipped a `Cargo.toml` declaring the `lookup` bench while the `Makefile` install copied only `src/`, so Cargo refused to parse the manifest over a missing `benches/lookup.rs`; the install now ships `benches/` as well (the file alone satisfies the parse — criterion is a dev-dependency and is not resolved when the crate is consumed as a library). `Cargo.toml` is bumped to 0.2.0 to match the package version and the `ltk-0.2.0` registry directory.
2026-06-25 12:43:40 +02:00

190 lines
6.9 KiB
Rust

// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
use super::app_data::AppData;
use super::surface::SurfaceFocus;
use crate::app::App;
use crate::tree::find_handlers;
use crate::types::{ Point, Rect };
/// Built-in context menu for text editing — Copy / Cut / Paste rows
/// drawn on top of the surface content. Shown on a right-click (or
/// long-press) in a [`crate::widget::text_edit::TextEdit`]; dismissed
/// by clicking outside or selecting an action. Lives on
/// [`super::surface::SurfaceState`] so a press inside an overlay shows
/// its own menu in overlay-local coordinates.
#[ derive( Clone, Debug ) ]
pub( crate ) struct ContextMenu
{
/// `widget_rects` index of the TextEdit the menu targets. Used by
/// the action dispatch so we operate on the right field even
/// after focus has moved.
pub widget_idx: usize,
/// Menu rect in surface-local physical pixels.
pub rect: Rect,
pub has_selection: bool,
pub can_paste: bool,
/// Byte offset within the target TextEdit's value that
/// corresponds to the original press point that opened the menu.
/// Paste uses this so the clipboard contents land exactly where
/// the user right-clicked / long-pressed, regardless of where
/// the cursor was beforehand. `None` only when the open path
/// could not snapshot the position (e.g. canvas missing).
pub paste_offset: Option<usize>,
}
/// Number of rows in the built-in clipboard context menu — Copy /
/// Cut / Paste / Delete. Bumped from three when Delete was added so
/// the user has a parallel UI affordance to the Backspace / Delete
/// keys for clearing a selection without touching the clipboard.
pub( crate ) const CONTEXT_MENU_ROWS: usize = 4;
impl ContextMenu
{
/// Vertical band offsets inside [`Self::rect`] for each row. The
/// returned vector always has [`CONTEXT_MENU_ROWS`] entries; the
/// last element is the per-row height. Used by both hit-testing
/// and the renderer so the two stay in sync.
pub fn row_ys( &self ) -> ( Vec<f32>, f32 )
{
let row_h = self.rect.height / CONTEXT_MENU_ROWS as f32;
let ys = ( 0..CONTEXT_MENU_ROWS )
.map( |i| self.rect.y + i as f32 * row_h )
.collect();
( ys, row_h )
}
/// Which row, if any, contains `pos`. Returns `0..CONTEXT_MENU_ROWS`
/// (Copy / Cut / Paste / Delete) or `None` if `pos` is outside the
/// menu rect.
pub fn row_at( &self, pos: Point ) -> Option<usize>
{
if !self.rect.contains( pos ) { return None; }
let row_h = self.rect.height / CONTEXT_MENU_ROWS as f32;
let i = ( ( pos.y - self.rect.y ) / row_h ).floor() as i32;
if ( 0..CONTEXT_MENU_ROWS as i32 ).contains( &i ) { Some( i as usize ) } else { None }
}
}
impl<A: App> AppData<A>
{
/// Open the built-in Copy / Cut / Paste context menu near `pos`,
/// targeting the TextEdit at `widget_idx`. Clamps the menu rect
/// to the surface so it never goes off-screen on a near-edge
/// click. Idempotent — replaces any existing menu.
pub( crate ) fn show_context_menu( &mut self, focus: SurfaceFocus, widget_idx: usize, pos: Point )
{
const W: f32 = 180.0;
const H: f32 = 44.0 * CONTEXT_MENU_ROWS as f32;
let has_selection = self.focused_selection_text( focus ).is_some();
let can_paste = !self.clipboard.is_empty();
// Snapshot the byte offset the press fell on so a later
// "Paste" lands exactly at the right-click point, even though
// the menu deliberately preserves the existing cursor /
// selection (so Copy / Cut still operate on the prior
// selection).
let paste_offset = self.text_input_geometry( focus, widget_idx )
.and_then( |( rect, value, multiline, secure, align, font_size )|
{
let cursor_pos = self.surface( focus ).frame.cursor_state.get( &widget_idx ).copied().unwrap_or( 0 );
let canvas = self.surface( focus ).canvas.as_ref()?;
Some( crate::widget::text_edit::byte_offset_at(
canvas, rect, pos, &value, multiline, secure, cursor_pos, align, font_size,
) )
} );
let ss = self.surface( focus );
let sw = ss.width as f32 * ss.scale_factor.max( 1 ) as f32;
let sh = ss.height as f32 * ss.scale_factor.max( 1 ) as f32;
let mut x = pos.x;
let mut y = pos.y;
// Clamp inside the surface with a small breathing margin.
x = x.min( sw - W - 4.0 ).max( 4.0 );
y = y.min( sh - H - 4.0 ).max( 4.0 );
let rect = Rect { x, y, width: W, height: H };
let menu = ContextMenu { widget_idx, rect, has_selection, can_paste, paste_offset };
let ss = self.surface_mut( focus );
ss.context_menu = Some( menu );
ss.request_redraw();
}
/// Dismiss the context menu on the given surface (no-op when
/// none is shown).
pub( crate ) fn hide_context_menu( &mut self, focus: SurfaceFocus )
{
let ss = self.surface_mut( focus );
if ss.context_menu.is_some()
{
ss.context_menu = None;
ss.request_redraw();
}
}
/// Handle a primary-button press while the context menu is open.
/// Returns `true` when the click was consumed by the menu (either
/// a row activation or an outside-click dismissal); the pointer
/// dispatch then skips the regular gesture path for this press.
pub( crate ) fn handle_context_menu_press( &mut self, focus: SurfaceFocus, pos: Point ) -> bool
{
let menu = match self.surface( focus ).context_menu.clone()
{
Some( m ) => m,
None => return false,
};
// Click outside the menu rect → dismiss only.
let row = match menu.row_at( pos )
{
Some( r ) => r,
None =>
{
self.hide_context_menu( focus );
return true;
}
};
// Action gating: rows are clickable only when their
// underlying operation makes sense.
match row
{
0 => if menu.has_selection { self.handle_copy( focus ); } else { return true; }
1 => if menu.has_selection { self.handle_cut( focus ); } else { return true; }
2 =>
{
if !menu.can_paste { return true; }
// Paste lands at the click position the menu was
// opened from, not at whatever the cursor happens to
// be (which may sit at the end of the value because
// the user just focused the field). Move cursor +
// anchor to the snapshotted offset (collapsing any
// prior selection there) and then run the regular
// paste path.
if let Some( ofs ) = menu.paste_offset
{
let ss = self.surface_mut( focus );
ss.frame.cursor_state.insert( menu.widget_idx, ofs );
ss.frame.selection_anchor.insert( menu.widget_idx, ofs );
}
self.handle_paste( focus );
}
3 =>
{
// Delete row — clears the current selection without
// touching the clipboard (the difference vs. Cut).
// Disabled with no selection: nothing to delete.
if !menu.has_selection { return true; }
if let Some( new_value ) = self.delete_selection( focus )
{
let msg = find_handlers( &self.surface( focus ).frame.widget_rects, menu.widget_idx )
.and_then( |h| h.text_change_msg( &new_value ) );
if let Some( m ) = msg { self.pending_msgs.push( m ); }
}
}
_ => return true,
}
self.hide_context_menu( focus );
true
}
}