xframe-demo: share run logic in lib so per-widget examples use the same path

Extract run_widget() from main.rs into src/lib.rs; the binary is now a
thin argv wrapper and each examples/<WidgetName>.rs is a minimal complete
program calling run_widget(name). Pilot: GtkButton, GtkLabel, GtkEntry,
GtkCalendar, InstPressureGauge (built, run under Xvfb, screenshotted).
This commit is contained in:
Muse committed 2026-12-02 06:01:33 +00:00
1 parent ee1519ee5a
commit 099e3122b1
8 files changed
+316 -164

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
//! GtkButton — minimal complete XFrame example.
//!
//! Run it from the workspace root:
//! cargo run -p xframe-demo --example GtkButton
//! It opens an 800x600 window showing one GtkButton widget (press Esc
//! or `q`, or close the window, to quit). The widget is the real
//! `xframe-widgets` implementation for this registry kind, created by
//! `xframe_widgets::create("GtkButton")` inside `xframe_demo::run_widget`
//! — the same code path the `xframe-demo` binary uses.
use std::process::ExitCode;
fn main() -> ExitCode {
match xframe_demo::run_widget("GtkButton", false, None, None) {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("GtkButton example: {}", e);
ExitCode::from(1)
}
}
}
@@ -0,0 +1,21 @@
//! GtkCalendar — minimal complete XFrame example.
//!
//! Run it from the workspace root:
//! cargo run -p xframe-demo --example GtkCalendar
//! It opens an 800x600 window showing one GtkCalendar widget (press Esc
//! or `q`, or close the window, to quit). The widget is the real
//! `xframe-widgets` implementation for this registry kind, created by
//! `xframe_widgets::create("GtkCalendar")` inside `xframe_demo::run_widget`
//! — the same code path the `xframe-demo` binary uses.
use std::process::ExitCode;
fn main() -> ExitCode {
match xframe_demo::run_widget("GtkCalendar", false, None, None) {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("GtkCalendar example: {}", e);
ExitCode::from(1)
}
}
}
+21
View File
@@ -0,0 +1,21 @@
//! GtkEntry — minimal complete XFrame example.
//!
//! Run it from the workspace root:
//! cargo run -p xframe-demo --example GtkEntry
//! It opens an 800x600 window showing one GtkEntry widget (press Esc
//! or `q`, or close the window, to quit). The widget is the real
//! `xframe-widgets` implementation for this registry kind, created by
//! `xframe_widgets::create("GtkEntry")` inside `xframe_demo::run_widget`
//! — the same code path the `xframe-demo` binary uses.
use std::process::ExitCode;
fn main() -> ExitCode {
match xframe_demo::run_widget("GtkEntry", false, None, None) {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("GtkEntry example: {}", e);
ExitCode::from(1)
}
}
}
+21
View File
@@ -0,0 +1,21 @@
//! GtkLabel — minimal complete XFrame example.
//!
//! Run it from the workspace root:
//! cargo run -p xframe-demo --example GtkLabel
//! It opens an 800x600 window showing one GtkLabel widget (press Esc
//! or `q`, or close the window, to quit). The widget is the real
//! `xframe-widgets` implementation for this registry kind, created by
//! `xframe_widgets::create("GtkLabel")` inside `xframe_demo::run_widget`
//! — the same code path the `xframe-demo` binary uses.
use std::process::ExitCode;
fn main() -> ExitCode {
match xframe_demo::run_widget("GtkLabel", false, None, None) {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("GtkLabel example: {}", e);
ExitCode::from(1)
}
}
}
@@ -0,0 +1,21 @@
//! InstPressureGauge — minimal complete XFrame example.
//!
//! Run it from the workspace root:
//! cargo run -p xframe-demo --example InstPressureGauge
//! It opens an 800x600 window showing one InstPressureGauge widget (press Esc
//! or `q`, or close the window, to quit). The widget is the real
//! `xframe-widgets` implementation for this registry kind, created by
//! `xframe_widgets::create("InstPressureGauge")` inside `xframe_demo::run_widget`
//! — the same code path the `xframe-demo` binary uses.
use std::process::ExitCode;
fn main() -> ExitCode {
match xframe_demo::run_widget("InstPressureGauge", false, None, None) {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("InstPressureGauge example: {}", e);
ExitCode::from(1)
}
}
}
+25
View File
@@ -0,0 +1,25 @@
# Per-widget examples
One minimal complete Rust program per widget kind
(`examples/<WidgetName>.rs`, 547 files, generated — do not edit by hand;
regenerate with `python3 /opt/lightgui-docs/rust_docs.py gen-examples`).
Every example calls `xframe_demo::run_widget("<Name>", false, None, None)`,
which is the shared runner in `crates/xframe-demo/src/lib.rs`: it opens an
800x600 window, creates the real widget for that registry kind via
`xframe_widgets::create`, draws it with the `default` style, and runs the
event loop (expose / button press-release / motion / key / close) until Esc,
`q`, or window close. The `xframe-demo` binary is the same runner with
flags:
cargo run -p xframe-demo -- <WidgetName> [--dark] [--hold SECS] [--geometry X,Y,W,H]
cargo run -p xframe-demo -- --list # all 547 names
Run one example:
cargo run -p xframe-demo --example GtkButton
Each example was run under Xvfb and screenshotted by
`xframe-test-runner` (see `/opt/lightgui-docs/rust_results.csv` on
hot_chicago); the screenshots are on the widget's docs page at
https://rustdoc.lightgui.com/<widget>/.
+176
View File
@@ -0,0 +1,176 @@
//! Shared demo runner for `xframe-demo` and its per-widget examples.
//!
//! The binary (`src/main.rs`) parses argv and calls [`run_widget`];
//! each `examples/<WidgetName>.rs` is a minimal complete program that
//! calls [`run_widget`] with its own widget name. One code path renders
//! every widget, so a screenshot of the binary is a screenshot of the
//! example's behaviour.
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::*;
use x11rb::protocol::Event;
use xframe_common::registry::{self, WidgetMeta};
use xframe_common::style::FONT_DEFAULT;
use xframe_common::target::CtxTarget;
use xframe_common::x11::{DrawCtx, X11};
use xframe_core::{Srgb, StyleManager};
use xframe_widgets::{create, Key, Widget};
const WIN_W: u16 = 800;
const WIN_H: u16 = 600;
const KEY_ESCAPE: u32 = 0xff1b;
/// `default` / `dark` styles, exactly as registered by every C++ demo
/// main (`add_style_ex`, C++ arg order fill/outline/text/line).
pub fn register_styles(styles: &mut StyleManager) {
styles.add_style_ex(
"default",
Srgb::new(225, 225, 225),
Srgb::new(120, 120, 120),
Srgb::new(20, 20, 20),
Srgb::new(60, 60, 60),
6,
1,
FONT_DEFAULT,
);
styles.add_style_ex(
"dark",
Srgb::new(45, 45, 48),
Srgb::new(20, 20, 22),
Srgb::new(240, 240, 240),
Srgb::new(200, 200, 200),
6,
1,
FONT_DEFAULT,
);
}
/// Open an 800x600 window, create the named registry widget (the REAL
/// widget, one of the 14 archetypes, via `xframe_widgets::create`),
/// draw it, and run the event loop until Esc / `q` / window-close, or
/// until `hold` seconds elapse when given. Returns the process exit
/// code (0 normally, 2 for an unknown widget name).
pub fn run_widget(
name: &str,
dark: bool,
hold: Option<u64>,
geometry: Option<(i16, i16, u16, u16)>,
) -> Result<i32, Box<dyn std::error::Error>> {
let meta: &'static WidgetMeta = match registry::by_name(name) {
Some(m) => m,
None => {
eprintln!("xframe-demo: unknown widget '{}'", name);
eprintln!("run `xframe-demo --list` for the 547 registry names");
return Ok(2);
}
};
let x = X11::connect()?;
let font = x.open_font(&[FONT_DEFAULT, "fixed"])?;
let title = format!("{} - XFrame demo", meta.name);
let event_mask = EventMask::EXPOSURE
| EventMask::KEY_PRESS
| EventMask::STRUCTURE_NOTIFY
| EventMask::BUTTON_PRESS
| EventMask::BUTTON_RELEASE
| EventMask::POINTER_MOTION;
let (win, gc) = x.create_window(100, 100, WIN_W, WIN_H, &title, event_mask)?;
let mut styles = StyleManager::new();
register_styles(&mut styles);
if dark {
styles.set_active_style_by_name("dark");
}
let (gx, gy, gw, gh) = geometry.unwrap_or_else(|| registry::demo_geometry(meta));
let mut widget: Box<dyn Widget> = match create(meta.name) {
Some(w) => w,
None => {
eprintln!("xframe-demo: no widget for '{}'", meta.name);
return Ok(2);
}
};
widget.set_bounds(gx as i32, gy as i32, gw as i32, gh as i32);
// Label text: the registry `kind` approximates the C++ constructor's
// default text (see the module docs of the binary).
let kind = widget.kind().to_string();
widget.set_text(&kind);
let ctx = DrawCtx::new(&x, win, gc, font);
ctx.bind_font();
let mut target = CtxTarget::new(&ctx);
// Font metrics for the styles: without them `draw_text_*` draws no
// text at all (same as the C++ `font_ == null` path). Resolving
// binds the font into the GC via the target.
if !styles.resolve_font("default", &mut target) && !styles.resolve_font("dark", &mut target) {
eprintln!("xframe-demo: warning: no font resolved, labels will be blank");
}
let redraw = |widget: &mut Box<dyn Widget>,
ctx: &DrawCtx,
target: &mut CtxTarget,
styles: &mut StyleManager| {
ctx.clear(255, 255, 255, WIN_W, WIN_H);
widget.draw(target, styles);
ctx.flush();
};
redraw(&mut widget, &ctx, &mut target, &mut styles);
let deadline = hold.map(|s| Instant::now() + Duration::from_secs(s));
loop {
if let Some(d) = deadline {
if Instant::now() >= d {
break;
}
}
let ev = match x.conn.poll_for_event()? {
Some(ev) => ev,
None => {
std::thread::sleep(Duration::from_millis(10));
continue;
}
};
let mut handled = false;
match ev {
Event::Expose(_) => {
redraw(&mut widget, &ctx, &mut target, &mut styles);
}
Event::ButtonPress(ev) => {
handled =
widget.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
}
Event::ButtonRelease(ev) => {
handled = widget.on_button_release(
ev.event_x as i32,
ev.event_y as i32,
ev.detail as u32,
);
}
Event::MotionNotify(ev) => {
handled = widget.on_motion(ev.event_x as i32, ev.event_y as i32);
}
Event::KeyPress(ev) => {
let keysym = x.keysym_for_keycode(ev.detail);
if keysym == KEY_ESCAPE || keysym == b'q' as u32 {
break;
}
let text = if (0x20..0x7f).contains(&keysym) {
Some(keysym as u8 as char)
} else {
None
};
handled = widget.on_key(Key::from_keysym(keysym, text), text);
}
Event::ClientMessage(ev)
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
{
break;
}
_ => {}
}
if handled {
redraw(&mut widget, &ctx, &mut target, &mut styles);
}
}
Ok(0)
}
+10 -164
View File
@@ -13,60 +13,23 @@
//! ```
//!
//! The widget comes from `xframe_widgets::create` — the REAL widget
//! (one of the 14 archetypes), not the stub placeholder this binary used
//! to carry. It draws through `xframe_core::DrawTarget`, bridged onto
//! this binary's `DrawCtx` window by `xframe_common::CtxTarget`
//! (text via PolyText8 — the black-bars fix stays intact).
//! (one of the 14 archetypes), not a stub. It draws through
//! `xframe_core::DrawTarget`, bridged onto this binary's `DrawCtx`
//! window by `xframe_common::CtxTarget` (text via PolyText8).
//!
//! Label text: the C++ mains construct the widget and draw it; each
//! C++ constructor sets its own default text (`"Button"`, `"Label"`,
//! `"Sample text"`, an indicator name, ...). The Rust factory leaves
//! `text` empty, so the demo sets it to the widget's registry `kind`
//! (`"Button"`, `"Label"`, `"Bollinger Bands"`, ...), which matches the
//! C++ default for the plain Gtk widgets and the indicators. Where the
//! C++ text was something else the pixels differ by the label glyphs
//! only; see the test runner's pixel-diff notes.
//! C++ default for the plain Gtk widgets and the indicators.
//!
//! The run logic lives in `xframe_demo::run_widget` (src/lib.rs) so the
//! per-widget cargo examples (`examples/<WidgetName>.rs`) share exactly
//! this code path.
use std::process::ExitCode;
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::*;
use x11rb::protocol::Event;
use xframe_common::registry::{self, WidgetMeta};
use xframe_common::style::FONT_DEFAULT;
use xframe_common::target::CtxTarget;
use xframe_common::x11::{DrawCtx, X11};
use xframe_core::{Srgb, StyleManager};
use xframe_widgets::{create, Key, Widget};
const WIN_W: u16 = 800;
const WIN_H: u16 = 600;
const KEY_ESCAPE: u32 = 0xff1b;
/// `default` / `dark` styles, exactly as registered by every C++ demo
/// main (`add_style_ex`, C++ arg order fill/outline/text/line).
fn register_styles(styles: &mut StyleManager) {
styles.add_style_ex(
"default",
Srgb::new(225, 225, 225),
Srgb::new(120, 120, 120),
Srgb::new(20, 20, 20),
Srgb::new(60, 60, 60),
6,
1,
FONT_DEFAULT,
);
styles.add_style_ex(
"dark",
Srgb::new(45, 45, 48),
Srgb::new(20, 20, 22),
Srgb::new(240, 240, 240),
Srgb::new(200, 200, 200),
6,
1,
FONT_DEFAULT,
);
}
use xframe_common::registry;
fn usage() -> &'static str {
"usage: xframe-demo <WidgetName> [--dark] [--hold SECS] [--geometry X,Y,W,H] [--list]\n xframe-demo --list # print all 547 registry widget names"
@@ -153,124 +116,7 @@ fn run() -> Result<i32, Box<dyn std::error::Error>> {
Some(n) => n.clone(),
None => return Err(format!("no widget name\n{}", usage()).into()),
};
let meta: &'static WidgetMeta = match registry::by_name(&name) {
Some(m) => m,
None => {
eprintln!("xframe-demo: unknown widget '{}'", name);
eprintln!("run `xframe-demo --list` for the 547 registry names");
return Ok(2);
}
};
let x = X11::connect()?;
let font = x.open_font(&[FONT_DEFAULT, "fixed"])?;
let title = format!("{} - XFrame demo", meta.name);
let event_mask = EventMask::EXPOSURE
| EventMask::KEY_PRESS
| EventMask::STRUCTURE_NOTIFY
| EventMask::BUTTON_PRESS
| EventMask::BUTTON_RELEASE
| EventMask::POINTER_MOTION;
let (win, gc) = x.create_window(100, 100, WIN_W, WIN_H, &title, event_mask)?;
let mut styles = StyleManager::new();
register_styles(&mut styles);
if args.dark {
styles.set_active_style_by_name("dark");
}
let (gx, gy, gw, gh) = args
.geometry
.unwrap_or_else(|| registry::demo_geometry(meta));
let mut widget: Box<dyn Widget> = match create(meta.name) {
Some(w) => w,
None => {
eprintln!("xframe-demo: no widget for '{}'", meta.name);
return Ok(2);
}
};
widget.set_bounds(gx as i32, gy as i32, gw as i32, gh as i32);
// Label text: the registry `kind` approximates the C++ constructor's
// default text (see the module docs).
let kind = widget.kind().to_string();
widget.set_text(&kind);
let ctx = DrawCtx::new(&x, win, gc, font);
ctx.bind_font();
let mut target = CtxTarget::new(&ctx);
// Font metrics for the styles: without them `draw_text_*` draws no
// text at all (same as the C++ `font_ == null` path). Resolving
// binds the font into the GC via the target.
if !styles.resolve_font("default", &mut target) && !styles.resolve_font("dark", &mut target) {
eprintln!("xframe-demo: warning: no font resolved, labels will be blank");
}
let redraw = |widget: &mut Box<dyn Widget>,
ctx: &DrawCtx,
target: &mut CtxTarget,
styles: &mut StyleManager| {
ctx.clear(255, 255, 255, WIN_W, WIN_H);
widget.draw(target, styles);
ctx.flush();
};
redraw(&mut widget, &ctx, &mut target, &mut styles);
let deadline = args.hold.map(|s| Instant::now() + Duration::from_secs(s));
loop {
if let Some(d) = deadline {
if Instant::now() >= d {
break;
}
}
let ev = match x.conn.poll_for_event()? {
Some(ev) => ev,
None => {
std::thread::sleep(Duration::from_millis(10));
continue;
}
};
let mut handled = false;
match ev {
Event::Expose(_) => {
redraw(&mut widget, &ctx, &mut target, &mut styles);
}
Event::ButtonPress(ev) => {
handled =
widget.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
}
Event::ButtonRelease(ev) => {
handled = widget.on_button_release(
ev.event_x as i32,
ev.event_y as i32,
ev.detail as u32,
);
}
Event::MotionNotify(ev) => {
handled = widget.on_motion(ev.event_x as i32, ev.event_y as i32);
}
Event::KeyPress(ev) => {
let keysym = x.keysym_for_keycode(ev.detail);
if keysym == KEY_ESCAPE || keysym == b'q' as u32 {
break;
}
let text = if (0x20..0x7f).contains(&keysym) {
Some(keysym as u8 as char)
} else {
None
};
handled = widget.on_key(Key::from_keysym(keysym, text), text);
}
Event::ClientMessage(ev)
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
{
break;
}
_ => {}
}
if handled {
redraw(&mut widget, &ctx, &mut target, &mut styles);
}
}
Ok(0)
xframe_demo::run_widget(&name, args.dark, args.hold, args.geometry)
}
fn main() -> ExitCode {