use crate::{Scene, SceneRegistry};
use mgui_components::{ButtonWidget, ColumnWidget, ContainerWidget, ListViewWidget, TextFieldWidget, TextWidget};
use mgui_core::layout::SizedBoxWidget;
use mgui_core::{single_width_signature, Color, InvalidationScope, MeasureKey, QueryCache, QueryKey, Size, WidgetNode};
use mgui_runtime::app::{CommandId, CommandOutcome, CommandRouter};
use mgui_text::{TextRuntime, TextRuntimeHandle};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
pub struct EmptyScene;
impl Scene for EmptyScene {
fn name(&self) -> &'static str {
"empty"
}
fn build(&self) -> WidgetNode {
WidgetNode::new(ContainerWidget::new())
}
}
pub struct ButtonScene;
impl Scene for ButtonScene {
fn name(&self) -> &'static str {
"button"
}
fn build(&self) -> WidgetNode {
WidgetNode::new(
ContainerWidget::new().child(ButtonWidget::new(Size::new(160.0, 48.0)).with_text("Hello", 16.0)),
)
}
}
pub struct FlagshipScene;
impl Scene for FlagshipScene {
fn name(&self) -> &'static str {
"flagship"
}
fn build(&self) -> WidgetNode {
let list =
ListViewWidget::builder(10_000, |i| WidgetNode::new(TextWidget::new(format!("row {i}")).with_size(14.0)))
.with_item_height(24.0)
.with_height(280.0);
let video_tile = WidgetNode::new(mgui_core::RRectWidget::new(
Size::new(420.0, 160.0),
Color::rgba(0.10, 0.12, 0.16, 1.0),
4.0,
));
let mut column = ColumnWidget::new(6.0);
column = column.push(TextWidget::new("mgui flagship skeleton").with_size(20.0));
column = column.push(ButtonWidget::new(Size::new(160.0, 40.0)).with_text("Open", 16.0));
column = column.push(video_tile);
column = column.push(SizedBoxWidget::sized(420.0, 280.0, list));
WidgetNode::new(ContainerWidget::new().child(column))
}
}
pub struct TextEditingScene;
impl Scene for TextEditingScene {
fn name(&self) -> &'static str {
"text_editing"
}
fn build(&self) -> WidgetNode {
let field = TextFieldWidget::new(360.0, 44.0).placeholder("IME replay").with_font_size(18.0);
WidgetNode::new(ContainerWidget::new().child(WidgetNode::new(field)))
}
}
pub struct CommandRouteScene {
router: RefCell<CommandRouter>,
shared: Rc<RefCell<RouteState>>,
}
#[derive(Default)]
struct RouteState {
revision: u64,
}
impl Default for CommandRouteScene {
fn default() -> Self {
let shared = Rc::new(RefCell::new(RouteState::default()));
let mut router = CommandRouter::new();
let increment_shared = Rc::clone(&shared);
router.register(CommandId::new(1), move |_| {
let mut state = increment_shared.borrow_mut();
state.revision = state.revision.wrapping_add(1);
CommandOutcome::Consumed
});
router.register(CommandId::new(2), |_| CommandOutcome::PassThrough);
Self { router: RefCell::new(router), shared }
}
}
impl Scene for CommandRouteScene {
fn name(&self) -> &'static str {
"command_route"
}
fn build(&self) -> WidgetNode {
let column = ColumnWidget::new(8.0)
.push(TextWidget::new("command route / shared state").with_size(16.0))
.push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("increment (menu id=1)", 13.0))
.push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("passthrough (id=2)", 13.0));
WidgetNode::new(ContainerWidget::new().child(column))
}
fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
Some(&self.router)
}
fn shared_state_summary(&self) -> Option<String> {
Some(format!("revision={}", self.shared.borrow().revision))
}
}
pub struct A11yJourneyScene {
activations: Rc<Cell<u32>>,
}
impl Default for A11yJourneyScene {
fn default() -> Self {
Self { activations: Rc::new(Cell::new(0)) }
}
}
impl Scene for A11yJourneyScene {
fn name(&self) -> &'static str {
"a11y_journey"
}
fn build(&self) -> WidgetNode {
let button = |label: &'static str, activations: &Rc<Cell<u32>>| {
let counter = Rc::clone(activations);
ButtonWidget::new(Size::new(240.0, 44.0))
.with_text(label, 14.0)
.with_a11y_label(label)
.on_press(move || counter.set(counter.get() + 1))
};
let column = ColumnWidget::new(8.0)
.push(button("Journey A", &self.activations))
.push(button("Journey B", &self.activations))
.push(button("Journey C", &self.activations));
WidgetNode::new(ContainerWidget::new().child(column))
}
fn shared_state_summary(&self) -> Option<String> {
Some(format!("activations={}", self.activations.get()))
}
}
pub struct TextRuntimeIsolationScene {
primary: TextRuntimeHandle,
secondary: TextRuntimeHandle,
router: RefCell<CommandRouter>,
}
impl Default for TextRuntimeIsolationScene {
fn default() -> Self {
let primary = TextRuntime::with_config("serif", 1.2);
let secondary = TextRuntime::with_config("sans-serif", 1.6);
let primary_for_command = primary.clone();
let mut router = CommandRouter::new();
router.register(CommandId::new(1), move |_| {
primary_for_command.set_line_height(1.8);
CommandOutcome::Consumed
});
Self { primary, secondary, router: RefCell::new(router) }
}
}
impl Scene for TextRuntimeIsolationScene {
fn name(&self) -> &'static str {
"text_runtime_isolation"
}
fn build(&self) -> WidgetNode {
let column = ColumnWidget::new(8.0)
.push(TextWidget::new("primary runtime / serif 1.2").with_size(16.0))
.push(TextWidget::new("secondary runtime / sans-serif 1.6").with_size(16.0));
WidgetNode::new(ContainerWidget::new().child(column))
}
fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
Some(&self.router)
}
fn shared_state_summary(&self) -> Option<String> {
Some(format!(
"primary_stack={} primary_line_height={:.2} primary_gen={} secondary_gen={}",
self.primary.font_stack(),
self.primary.line_height(),
self.primary.style_generation(),
self.secondary.style_generation(),
))
}
fn text_runtime_summary(&self) -> Option<String> {
Some(format!(
"primary_gen={} primary_dpr={:.2} secondary_gen={} secondary_dpr={:.2}",
self.primary.style_generation(),
self.primary.dpr(),
self.secondary.style_generation(),
self.secondary.dpr(),
))
}
}
pub struct QueryCacheScene {
cache: QueryCache<u32>,
router: RefCell<CommandRouter>,
}
impl Default for QueryCacheScene {
fn default() -> Self {
let cache = QueryCache::new(8, 1024, |_| 4);
cache.insert(QueryKey::new(1), std::rc::Rc::new(1), 7);
cache.insert(QueryKey::new(2), std::rc::Rc::new(2), 8);
let lookup_cache = cache.clone();
let invalidate_cache = cache.clone();
let mut router = CommandRouter::new();
router.register(CommandId::new(1), move |_| {
invalidate_cache.invalidate(InvalidationScope::Group(7));
CommandOutcome::Consumed
});
router.register(CommandId::new(2), move |_| {
let _ = lookup_cache.lookup(QueryKey::new(1));
CommandOutcome::Consumed
});
Self { cache, router: RefCell::new(router) }
}
}
impl Scene for QueryCacheScene {
fn name(&self) -> &'static str {
"query_cache_invalidation"
}
fn build(&self) -> WidgetNode {
let column = ColumnWidget::new(8.0)
.push(TextWidget::new("query cache / group invalidation").with_size(16.0))
.push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("invalidate group 7", 13.0));
WidgetNode::new(ContainerWidget::new().child(column))
}
fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
Some(&self.router)
}
fn shared_state_summary(&self) -> Option<String> {
let stats = self.cache.stats();
Some(format!(
"entries={} fresh_hits={} stale_hits={} invalidations={}",
self.cache.len(),
stats.fresh_hits,
stats.stale_hits,
stats.invalidations,
))
}
fn cache_scope_summary(&self) -> Option<String> {
let stats = self.cache.stats();
Some(format!("scope=Group(7) entries={} invalidations={}", self.cache.len(), stats.invalidations,))
}
}
pub struct AppServicesJourneyScene {
settings: Rc<RefCell<Vec<(String, String)>>>,
recent: Rc<RefCell<Vec<String>>>,
crashes: Rc<RefCell<Vec<String>>>,
router: RefCell<CommandRouter>,
}
impl Default for AppServicesJourneyScene {
fn default() -> Self {
let settings = Rc::new(RefCell::new(vec![("showcase.high_contrast".into(), "0".into())]));
let recent = Rc::new(RefCell::new(Vec::new()));
let crashes = Rc::new(RefCell::new(Vec::new()));
let toggle_settings = Rc::clone(&settings);
let push_recent = Rc::clone(&recent);
let record_crash = Rc::clone(&crashes);
let clear_recent = Rc::clone(&recent);
let clear_crashes = Rc::clone(&crashes);
let mut router = CommandRouter::new();
router
.register(CommandId::new(1), move |_| {
let mut settings = toggle_settings.borrow_mut();
let current = settings[0].1 == "1";
settings[0].1 = if current { "0" } else { "1" }.into();
CommandOutcome::Consumed
})
.register(CommandId::new(2), move |_| {
let mut recent = push_recent.borrow_mut();
if !recent.first().map(|p| p == "doc.rs").unwrap_or(false) {
recent.insert(0, "doc.rs".into());
}
CommandOutcome::Consumed
})
.register(CommandId::new(3), move |_| {
record_crash.borrow_mut().push("scene:summary".into());
CommandOutcome::Consumed
})
.register(CommandId::new(4), move |_| {
clear_recent.borrow_mut().clear();
CommandOutcome::Consumed
})
.register(CommandId::new(5), move |_| {
clear_crashes.borrow_mut().clear();
CommandOutcome::Consumed
});
Self { settings, recent, crashes, router: RefCell::new(router) }
}
}
impl AppServicesJourneyScene {
fn state_summary(&self) -> String {
let settings = self.settings.borrow();
let recent = self.recent.borrow();
let crashes = self.crashes.borrow();
let setting = settings.first().map(|(k, v)| format!("{k}={v}")).unwrap_or_else(|| "none".into());
format!("settings={setting} recent={} crashes={}", recent.len(), crashes.len())
}
}
impl Scene for AppServicesJourneyScene {
fn name(&self) -> &'static str {
"app_services_journey"
}
fn build(&self) -> WidgetNode {
let column = ColumnWidget::new(8.0)
.push(TextWidget::new("app services / typed user entries").with_size(16.0))
.push(TextWidget::new(self.state_summary()).with_size(13.0))
.push(ButtonWidget::new(Size::new(240.0, 44.0)).with_text("settings / recent / crashes", 13.0));
WidgetNode::new(ContainerWidget::new().child(column))
}
fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
Some(&self.router)
}
fn shared_state_summary(&self) -> Option<String> {
Some(self.state_summary())
}
fn persistence_summary(&self) -> Option<String> {
Some(format!("schema=1 owner=held recovery=none {}", self.state_summary()))
}
}
pub struct MultiDprWindowsScene {
window_a: TextRuntimeHandle,
window_b: TextRuntimeHandle,
revision: Cell<u64>,
}
impl Default for MultiDprWindowsScene {
fn default() -> Self {
let window_a = TextRuntime::with_config("serif", 1.2);
let window_b = TextRuntime::with_config("sans-serif", 1.6);
window_a.set_dpr(1.0);
window_b.set_dpr(1.5);
Self { window_a, window_b, revision: Cell::new(0) }
}
}
impl MultiDprWindowsScene {
fn measure_key(runtime: &TextRuntimeHandle, width: f32, revision: u64) -> MeasureKey {
MeasureKey::new(single_width_signature(width), runtime.style_generation(), runtime.dpr(), revision)
}
}
impl Scene for MultiDprWindowsScene {
fn name(&self) -> &'static str {
"multi_dpr_windows"
}
fn build(&self) -> WidgetNode {
let column = ColumnWidget::new(8.0)
.push(TextWidget::new("window A / dpr 1.00").with_size(16.0))
.push(TextWidget::new("window B / dpr 1.50").with_size(16.0))
.push(TextWidget::new("cross-screen move updates B only").with_size(13.0));
WidgetNode::new(ContainerWidget::new().child(column))
}
fn shared_state_summary(&self) -> Option<String> {
Some(format!(
"window_a_dpr={:.2} window_b_dpr={:.2} revision={}",
self.window_a.dpr(),
self.window_b.dpr(),
self.revision.get(),
))
}
fn text_runtime_summary(&self) -> Option<String> {
let revision = self.revision.get();
let a = Self::measure_key(&self.window_a, 800.0, revision);
let b = Self::measure_key(&self.window_b, 800.0, revision);
Some(format!("window_a_key={a:?} window_b_key={b:?}"))
}
fn on_scale_factor_changed(&self, dpr: f32) {
if (self.window_b.dpr() - dpr).abs() > f32::EPSILON {
self.window_b.set_dpr(dpr);
self.revision.set(self.revision.get() + 1);
}
}
}
pub fn builtin_scenes() -> SceneRegistry {
let mut registry = SceneRegistry::new();
registry.register(Box::new(EmptyScene));
registry.register(Box::new(ButtonScene));
registry.register(Box::new(FlagshipScene));
registry.register(Box::new(TextEditingScene));
registry.register(Box::new(CommandRouteScene::default()));
registry.register(Box::new(A11yJourneyScene::default()));
registry.register(Box::new(TextRuntimeIsolationScene::default()));
registry.register(Box::new(QueryCacheScene::default()));
registry.register(Box::new(AppServicesJourneyScene::default()));
registry.register(Box::new(MultiDprWindowsScene::default()));
registry
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_scenes_are_stably_named_and_buildable() {
let registry = builtin_scenes();
assert_eq!(
registry.names(),
vec![
"empty",
"button",
"flagship",
"text_editing",
"command_route",
"a11y_journey",
"text_runtime_isolation",
"query_cache_invalidation",
"app_services_journey",
"multi_dpr_windows",
]
);
for name in registry.names() {
let _ = registry.build(name).unwrap_or_else(|e| panic!("scene {name}: {e}"));
}
assert!(registry.build("missing").is_err());
}
}