Files
ltk/examples/showcase.rs
Pedro M. de Echanove Pasquin bfe27b6fef event_loop, widget, input: pointer-dwell tooltips, global drag coords, foreign-toplevel name cascade
`Button::tooltip( text )` registers a hint string that fires after a 600 ms pointer dwell. `LaidOutWidget` gains a `tooltip: Option<String>` field, `Element::tooltip()` exposes it to the input layer, and the existing pointer-hover path now calls `arm_tooltip` on hover-enter and `cancel_tooltip` on hover-leave / touch. The deadline is polled alongside `next_long_press_wakeup` in `try_run` so an idle pointer still gets a wake-up at the firing instant; on fire, `tooltip_overlay()` synthesises an `OverlaySpec` — a rounded `text_primary @ 95%` pill drawn with `bg` text — anchored above the hovered widget, flipping below or clamping inside the screen if it would clip, and pushed alongside the app's own overlays both in the redraw path and in `reconcile_overlays` so the layer surface is created the same frame the tooltip becomes visible. Pointer-only by design: touch events explicitly cancel because a tap-and-release should never linger into a hint. The `showcase` example wires `.tooltip(..)` on the three button variants as a smoke test.
The drag pipeline now reports positions in main-surface (global) coordinates instead of per-surface. `surface_offset_for( focus )` derives the top-left of an overlay surface from `SurfaceState::layer_anchor` — newly stored at `reconcile_overlays` time from `OverlaySpec::anchor` — combined with the main surface's dimensions; `on_drag_move`, `on_drop`, the synthetic move emitted on drag-promotion in `pointer.rs`, and the `pending_drag_inits` push site in `gesture::start_drag` all translate before handing coordinates to the app. The motion and release paths additionally `request_redraw()` every overlay so a dock-style drop target painted on an `Anchor::Bottom` layer surface gets repainted as the drag moves — without that, the visible drop indicator only updates when the cursor re-enters the main surface. Drops still target whichever surface fired the release; only the coordinates are unified.
`ForeignToplevelListHandler` previously read `app_id` directly via `ForeignToplevelList::info()`. Clients that never set `app_id` (some winit-windowed compositors, simple test clients) were silently invisible to crustace-style docks because the empty string fell through `unwrap_or_default()` and the dock then keyed entries off `""`. `toplevel_display_id()` cascades: prefer `app_id` for desktop-entry matching, fall back to `title` for human-readable identification, and finally to the protocol-issued `identifier` which is always present and unique per handle. Applied to both `new_toplevel` and `update_toplevel`.
`theme::system_fontdb()` lazily loads the system font database once via `OnceLock` and reuses the `Arc` for every `decode_svg_bytes` call. resvg's default `Options::fontdb` is empty, so any SVG containing `<text>` rendered with the built-in fallback font or no font at all; with the system DB attached, icons and decorative SVGs with embedded labels now resolve glyphs correctly. Cached because `load_system_fonts()` walks every font path on the system and is comfortably tens of milliseconds on a cold cache — not something to repeat per icon decode.
`themes/default/theme.json` tweaks one variant's slot palette: `surface-alt` from `@indigo/D9` to `@white/D9` and `text-primary` from `@white` to `@navy`, plus a cosmetic re-alignment of the `"value"` columns in the same slots block.
2026-05-14 22:36:17 +02:00

256 lines
7.6 KiB
Rust

//! `cargo run --example showcase`
//!
//! Shows button variants, container with background, a slider, plus the
//! newer additions: a tab strip, a spinner driven by the wall clock, a
//! multiline text edit, and on-demand toast / tooltip overlays.
//! Tab / Shift+Tab cycles keyboard focus. Enter or Space activates the
//! focused button. Esc exits.
//!
//! NOTE: ltk is a Wayland layer-shell toolkit. This example requires a running
//! Wayland compositor (e.g. sway, labwc, or a full desktop session).
use std::time::{ Duration, Instant };
use ltk::{
App, Element, Keysym, ButtonVariant, WidgetId,
OverlaySpec,
button, column, row, stack, text, text_edit, spacer, container, slider, scroll,
spinner, tabs, toast, tooltip,
};
// ── Messages ──────────────────────────────────────────────────────────────────
#[ derive( Clone ) ]
enum Message
{
Pressed( &'static str ),
SliderChanged( f32 ),
SelectTab( usize ),
NoteChanged( String ),
ShowToast,
ToggleTooltip,
HideToast,
}
// ── App state ─────────────────────────────────────────────────────────────────
struct ShowcaseApp
{
last_pressed: String,
slider_value: f32,
tab: usize,
note: String,
started_at: Instant,
toast_until: Option<Instant>,
tooltip_visible: bool,
}
impl ShowcaseApp
{
fn new() -> Self
{
Self
{
last_pressed: String::from( "" ),
slider_value: 0.5,
tab: 0,
note: String::new(),
started_at: Instant::now(),
toast_until: None,
tooltip_visible: false,
}
}
const SAVE_BUTTON_ID: WidgetId = WidgetId( "showcase/save" );
}
// ── App trait ─────────────────────────────────────────────────────────────────
impl App for ShowcaseApp
{
type Message = Message;
fn view( &self ) -> Element<Message>
{
// Pull text colours from the active theme — the runtime
// background defaults to `palette.bg`, so hard-coded white
// text would be unreadable in light mode.
let palette = ltk::theme_palette();
let primary = palette.text_primary;
let secondary = palette.text_secondary;
let status = format!( "Last pressed: {}", self.last_pressed );
// Tabs strip — the active tab just relabels a banner below.
let tabs_strip: Element<Message> = tabs( [ "Buttons", "Inputs", "Hints" ] )
.selected( self.tab )
.on_select( Message::SelectTab )
.into();
let tab_banner = format!(
"Active tab: {}",
[ "Buttons", "Inputs", "Hints" ][ self.tab.min( 2 ) ],
);
let buttons = row::<Message>()
.spacing( 16.0 )
.push(
button( "Primary" )
.variant( ButtonVariant::Primary )
.id( Self::SAVE_BUTTON_ID )
.tooltip( "Hover-dwell tooltip via .tooltip()" )
.on_press( Message::Pressed( "Primary" ) ),
)
.push(
button( "Secondary" )
.variant( ButtonVariant::Secondary )
.tooltip( "Secondary action" )
.on_press( Message::Pressed( "Secondary" ) ),
)
.push(
button( "Tertiary" )
.variant( ButtonVariant::Tertiary )
.tooltip( "Tertiary action" )
.on_press( Message::Pressed( "Tertiary" ) ),
);
let card = container::<Message>(
column::<Message>()
.spacing( 8.0 )
.push( text( "container() demo" ).size( 14.0 ).color( primary ) )
.push(
text( "Background color + padding + corner radius" )
.size( 12.0 )
.color( secondary ),
),
)
.background( palette.surface_alt )
.radius( 12.0 )
.padding( 16.0 );
let vol_label = format!( "Volume: {:.0}%", self.slider_value * 100.0 );
// Spinner — phase comes straight from the wall clock so the arc
// completes one revolution per second.
let phase = self.started_at.elapsed().as_secs_f32();
let spin_row: Element<Message> = row::<Message>()
.spacing( 12.0 )
.push( spinner().phase( phase ) )
.push( text( "Working…" ).size( 14.0 ).color( primary ) )
.into();
// Multiline text area.
let textarea = text_edit( "Type a note (multi-line)", &self.note )
.multiline( true )
.rows( 3 )
.on_change( Message::NoteChanged );
// Buttons that exercise the overlay-returning widgets.
let overlay_row = row::<Message>()
.spacing( 12.0 )
.push( button( "Show toast" ).on_press( Message::ShowToast ) )
.push(
button( if self.tooltip_visible { "Hide tooltip" } else { "Show tooltip" } )
.on_press( Message::ToggleTooltip )
);
let body = column::<Message>()
.padding( 32.0 )
.spacing( 16.0 )
.push( text( "ltk showcase" ).size( 24.0 ).color( primary ).align_center() )
.push( text( status ).size( 14.0 ).color( secondary ).align_center() )
.push( tabs_strip )
.push( text( tab_banner ).size( 12.0 ).color( secondary ).align_center() )
.push( spacer() )
.push( buttons )
.push( card )
.push( text( vol_label ).size( 13.0 ).color( secondary ) )
.push( slider( self.slider_value ).on_change( Message::SliderChanged ) )
.push( spin_row )
.push( textarea )
.push( overlay_row )
.push( spacer() )
.push(
text( "Tab = focus next · Enter / Space = press · Esc = quit" )
.size( 12.0 )
.color( secondary )
.align_center(),
);
// Toast lives inside the main view (works on every
// compositor — no `wlr-layer-shell` required). The Tooltip
// stays in `overlays()` because xdg-popup is universal.
let mut s = stack::<Message>().push( scroll( body ) );
if self.toast_until.is_some()
{
s = s.push( toast::<Message>( "Saved" ).view() );
}
s.into()
}
fn update( &mut self, msg: Message )
{
match msg
{
Message::Pressed( name ) => self.last_pressed = name.to_string(),
Message::SliderChanged( val ) => self.slider_value = val,
Message::SelectTab( i ) => self.tab = i,
Message::NoteChanged( s ) => self.note = s,
Message::ShowToast =>
{
self.toast_until = Some( Instant::now() + Duration::from_secs( 2 ) );
}
Message::HideToast => self.toast_until = None,
Message::ToggleTooltip => self.tooltip_visible = !self.tooltip_visible,
}
}
fn overlays( &self ) -> Vec<OverlaySpec<Message>>
{
// Tooltip is an xdg-popup → works on any xdg-shell compositor.
// Toast is rendered inline in `view()` (see the Stack at the
// bottom of the function) so it does not depend on
// `wlr-layer-shell` either.
if self.tooltip_visible
{
vec![ tooltip::<Message>( "Saves the document and closes the dialog", Self::SAVE_BUTTON_ID ).overlay() ]
} else {
vec![]
}
}
fn on_key( &mut self, keysym: Keysym ) -> Option<Message>
{
if keysym == Keysym::Escape
{
std::process::exit( 0 );
}
None
}
// Keep redrawing while the spinner is on screen and while a toast
// is pending so its expiry timestamp is checked every frame.
fn is_animating( &self ) -> bool { true }
// Auto-clear an expired toast.
fn poll_interval( &self ) -> Option<Duration>
{
Some( Duration::from_millis( 250 ) )
}
fn poll_external( &mut self ) -> Vec<Message>
{
match self.toast_until
{
Some( deadline ) if Instant::now() >= deadline => vec![ Message::HideToast ],
_ => vec![],
}
}
}
// ── Entry point ───────────────────────────────────────────────────────────────
fn main()
{
ltk::run( ShowcaseApp::new() );
}