Host MaterialCraft's egui UI on craft-libs next's runtime

The runtime is installed in the desktop and web shells and fed each frame;
the unsaved-work question decides in the framework's close path. Panels dock
in next's DockArea beside the saved workspace (file format unchanged), with
the graph as the canvas group. The update dialogs run on a DialogHost. Where
the app draws the window frame, the menu bar sits in the framework's title
bar. Escape no app widget takes arrives as the window's cancel and still runs
the Escape shortcuts. Shortcuts match through craft_keymap::Matcher with the
old dispatcher's contract. Removed framework helpers (widget palette, icon
button painter, interface direction) are app-local or come from craft-i18n.
Test harnesses that draw the app install the runtime.
This commit is contained in:
aiongg committed 2026-11-24 01:18:57 +00:00
1 parent 9583d9238a
commit 2afa397987
51 files changed
+2106 -479

No files matched your search

Generated
+1263 -93
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -96,6 +96,9 @@ craft-materialx = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c9
craft-mcmat = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc" }
craft-ui = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc" }
craft-behavior = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc" }
craft-host = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc" }
craft-theme = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc" }
craft-i18n = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc" }
# Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0
craft-keymap = { git = "https://github.com/aiongg/craft-libs", rev = "22e82c930ec7062fba45757a8cac8ba5e3cb94bc", features = ["egui"] }
# Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0
+1
View File
@@ -60,6 +60,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
canvas,
options,
Box::new(|cc| {
materialcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let mut app = MaterialCraftApp::new(cc, session);
// One thread cooks in the browser, so keep previews small
+4 -4
View File
@@ -102,10 +102,10 @@ fn main() {
prev(info);
}));
let session = initial_session(&args);
let window_frame = craft_window::Choice::probe(craft_window::Prefix::new("MATERIALCRAFT")).into_frame();
let mut viewport = craft_window::decorate(
let window_frame = materialcraft_ui_egui::framework::decide_frame();
let mut viewport = craft_window::policy::apply(
egui::ViewportBuilder::default().with_title("MaterialCraft").with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE),
&window_frame,
&window_frame.frame,
);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
@@ -120,8 +120,8 @@ fn main() {
"MaterialCraft",
options,
Box::new(move |cc| {
materialcraft_ui_egui::framework::install(&cc.egui_ctx, window_frame)?;
let mut app = MaterialCraftApp::new(cc, session);
app.window_layout = window_frame.layout().cloned();
// Called from the creator: winit installs its default menu before this runs. On error winit's menu stays, whose Quit does not ask
#[cfg(target_os = "macos")]
if let Err(error) = craft_menu::mac::install_app_menu(&cc.egui_ctx, "MaterialCraft") {
+4 -4
View File
@@ -15,6 +15,10 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"]
egui = { workspace = true }
craft-ui = { workspace = true }
craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-theme = { workspace = true }
craft-i18n = { workspace = true }
craft-window = { workspace = true, features = ["ui"] }
craft-keymap = { workspace = true, features = ["egui"] }
egui-phosphor = { version = "0.14", features = ["regular"] }
serde = { workspace = true }
@@ -30,10 +34,6 @@ sha2 = { workspace = true }
sys-locale = "0.3"
craft-update = { workspace = true }
craft-dialogs = { workspace = true }
craft-quit = { workspace = true, features = ["ui"] }
craft-window = { workspace = true, features = ["ui"] }
# Floating panels open as OS windows.
craft-ui = { workspace = true }
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
[target.'cfg(target_arch = "wasm32")'.dependencies]
+140 -139
View File
@@ -1,24 +1,26 @@
//! The dock host: every panel (explorer, library, graph, 3D view, 2D view, properties, console,
//! history) is a tab that can be docked, tabbed, resized, floated and closed. craft-ui's shared
//! docking (`craft_ui::docking`) draws the frames, tab strips, floating windows and drop previews
//! and owns the gestures; this module names the panels, builds the default arrangement, applies
//! the dock's changes and hosts the panel bodies.
//! history) is a tab that can be docked, tabbed, resized, floated and closed. craft-ui's
//! `DockArea` draws the frames, tab strips, floating windows and drop previews and owns the
//! gestures; this module names the panels, builds the default arrangement, applies the dock's
//! changes and hosts the panel bodies.
//!
//! The graph is the central canvas: it stays docked, never takes tabs and is the only panel that
//! cannot close or float. The layout persists with `UiState` as a craft-ui `Workspace`; a layout
//! that does not load or validate becomes the default.
//! cannot close or float. The layout persists with `UiState` as a craft-behavior `Workspace`; a
//! layout that does not load or validate becomes the default.
use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions};
use craft_ui::docking::{DockArea, DockContent, DockStyle, PanelLimits};
use std::sync::Arc;
use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions, SplitSize};
use craft_behavior::flow::Axis;
use craft_behavior::dock::SplitSize;
use egui::{Id, Margin, RichText, Ui, vec2};
use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use egui::{Margin, Rect, Ui, vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Panel {
@@ -65,31 +67,31 @@ impl Panel {
}
}
/// Where the panel floats when it has never been laid out: `[x, y, width, height]`, cascaded.
fn float_rect(self) -> Option<[f32; 4]> {
/// Where the panel floats when it has never been laid out, cascaded.
fn float_rect(self) -> Option<Rect> {
let slot = match self {
Panel::Console => 0.0,
Panel::History => 1.0,
_ => return None,
};
Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0])
Some(Rect::from_min_size(egui::pos2(900.0, 120.0 + 50.0 * slot), vec2(420.0, 320.0)))
}
}
/// The saved panel arrangement: craft-ui's workspace over MaterialCraft's panels.
/// The saved panel arrangement: craft-behavior's workspace over MaterialCraft's panels.
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
/// The graph never moves, floats, closes or takes tabs; panels dock beside it.
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
if *panel == Panel::Graph { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
}
fn tabs(panels: &[Panel]) -> Node<Panel> {
Node::Tabs { panels: panels.to_vec(), active: 0 }
Node::tabs(panels.to_vec(), 0)
}
fn split(axis: Axis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) }
Node::split(axis, SplitSize::Ratio(ratio), first, second)
}
/// The default: explorer over library on the left; the graph over the 3D and 2D views in the
@@ -100,33 +102,27 @@ pub fn default_workspace() -> Workspace {
let views = split(Axis::X, 0.5, tabs(&[View3d]), tabs(&[View2d]));
let center = split(Axis::Y, 0.52, tabs(&[Graph]), views);
let root = split(Axis::X, 0.15, left, split(Axis::X, 0.8, center, tabs(&[Properties])));
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
if let Some(rect) = panel.float_rect() {
let location = Location {
floating: Some(rect),
anchor: None,
placement: DockPlacement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
};
workspace.hidden.push((panel, location));
}
}
workspace
let hidden = Panel::ALL
.into_iter()
.filter_map(|panel| {
let rect = panel.float_rect()?;
let mut location = Location::new(None, DockPlacement::tab(None));
location.floating = Some(rect);
Some((panel, location))
})
.collect();
Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, Vec::new())
}
/// craft-ui's checks plus the graph's: a saved or hand-edited file cannot hide, float, group
/// or collapse it.
/// craft-behavior's checks plus the graph's: a saved or hand-edited file cannot hide, float,
/// group or collapse it.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = &workspace.layout;
let layout = workspace.layout();
if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) {
return Err("The graph cannot float".into());
}
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) {
if workspace.hidden().iter().any(|(panel, _)| *panel == Panel::Graph) {
return Err("The graph cannot be hidden".into());
}
let mut found = false;
@@ -143,7 +139,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
}
found = true;
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => {
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Graph) => {
return Err("The graph cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => {
@@ -158,17 +154,15 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
// ---------------------------------------------------------------------------------------------
// The live dock
/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`).
/// The dock layout (part of `UiState`; serialized as a craft-behavior `Workspace`).
#[derive(Clone, Debug)]
pub struct Dock {
workspace: Workspace,
/// A panel to bring in front of the other floating windows on the next frame.
raise: Option<Panel>,
}
impl Default for Dock {
fn default() -> Self {
Dock { workspace: default_workspace(), raise: None }
Dock { workspace: default_workspace() }
}
}
@@ -201,7 +195,7 @@ impl Dock {
if validate(&workspace).is_err() {
return Dock::default();
}
Dock { workspace, raise: None }
Dock { workspace }
}
pub fn workspace(&self) -> &Workspace {
@@ -209,12 +203,12 @@ impl Dock {
}
pub fn is_open(&self, p: Panel) -> bool {
self.workspace.layout.contains(&p)
self.workspace.layout().contains(&p)
}
/// Open and the front tab of its group.
pub fn is_visible(&self, p: Panel) -> bool {
self.workspace.layout.panel_state(&p) == PanelState::Front
self.workspace.layout().panel_state(&p) == PanelState::Front
}
/// Hide a visible panel, otherwise bring it up.
@@ -223,7 +217,7 @@ impl Dock {
}
pub fn close(&mut self, p: Panel) {
if let Err(error) = self.workspace.set_visible(p, false, None, permissions) {
if let Err(error) = self.workspace.set_visible(p, false, None, false, permissions) {
log::warn!("panel {p:?} was not closed: {error}");
}
}
@@ -232,11 +226,8 @@ impl Dock {
/// front.
pub fn focus(&mut self, p: Panel) {
let mut next = self.workspace.clone();
match next.set_visible(p, true, None, permissions) {
Ok(()) if validate(&next).is_ok() => {
self.workspace = next;
self.raise = Some(p);
}
match next.set_visible(p, true, None, false, permissions) {
Ok(()) if validate(&next).is_ok() => self.workspace = next,
Ok(()) => log::warn!("panel {p:?} was not opened: it would break the graph's rules"),
Err(error) => log::warn!("panel {p:?} was not opened: {error}"),
}
@@ -246,7 +237,7 @@ impl Dock {
/// it was.
fn apply(&mut self, action: Action<Panel>) {
let mut next = self.workspace.clone();
match next.apply(action, permissions) {
match next.apply(action, false, permissions) {
Ok(_) if validate(&next).is_ok() => self.workspace = next,
Ok(_) => log::warn!("a panel move would break the graph's rules"),
Err(error) => log::warn!("a panel move was not applied: {error}"),
@@ -254,73 +245,117 @@ impl Dock {
}
}
/// What the dock area keeps between passes: the workspace it shows and the panels' specs.
#[derive(Default)]
pub(crate) struct LiveDock {
shown: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
}
impl LiveDock {
/// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same,
/// so an idle pass keeps the workspace's revision and the dock reads no spec.
fn shown(&mut self, workspace: &Workspace) -> Arc<Workspace> {
if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
self.shown = Some(Arc::clone(&shown));
shown
}
}
/// What the dock reads of the panels: their tab names, in [`Panel::ALL`] order.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
struct DockSpecs {
labels: Vec<String>,
}
impl PanelSpecs<Panel> for DockSpecs {
fn spec(&self, panel: &Panel) -> PanelSpec {
let label = Panel::ALL.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
// Every panel body is MaterialCraft's own egui code: the dock runs it with the window's style.
let spec = PanelSpec::new(label).limits(limits(panel)).float_size(vec2(420.0, 320.0)).host_body();
if *panel == Panel::Graph { spec.canvas() } else { spec }
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// Smallest body sizes a divider drag leaves.
fn limits(panel: &Panel) -> SizeLimits {
SizeLimits::at_least(if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) })
}
/// The tab name of `panel`: what it shows (the selection, the scene, the image) in the interface
/// language.
fn label(app: &MaterialCraftApp, panel: Panel) -> String {
match panel {
Panel::Properties => crate::properties::title(app),
Panel::Graph => app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()),
Panel::View3d => format!("{} - {}", crate::view3d::scene_label(app), tr("3D View")),
Panel::View2d => crate::view2d::title(app),
p => tr(p.name()).to_string(),
}
}
/// Reads the tab names, moving the specs' revision only when one changed.
fn refresh_specs(app: &mut MaterialCraftApp) {
let labels: Vec<String> = Panel::ALL.iter().map(|panel| label(app, *panel)).collect();
if app.docks.specs.labels != labels {
app.docks.specs.labels = labels;
}
}
// ---------------------------------------------------------------------------------------------
// Drawing
fn area_id() -> Id {
Id::unique("materialcraft-docking")
}
/// The dock look: every panel group is a card on the window's frame colour, its tab strip
/// without hard lines, the shown tab a pill, uppercase captions.
fn style(ui: &Ui, t: &Tokens) -> DockStyle {
let mut s = DockStyle::from_ui(ui);
s.gap = 6.0;
// Smallest panel extent a divider drag leaves.
s.min_pane = 60.0;
s.background = t.panel;
s.tab_background = t.panel;
s.active_background = t.button;
s.text = t.text_strong;
s.inactive_text = t.text_dim;
s.border = egui::Stroke::NONE;
s.accent = t.accent;
s.floating_background = t.panel;
s.floating_stroke = egui::Stroke::new(1.0, t.button_border);
s.font = egui::FontId::proportional(10.5);
s.min_tab_width = 54.0;
s.tab_height = 30.0;
// Panels arrange in a split tree around the graph; floating title bars only move windows.
s.new_dock_zones = false;
s.title_bar_docks = false;
s
/// The graph editor's id as the window's document canvas.
fn graph_canvas_id() -> egui::Id {
egui::Id::unique("materialcraft-graph-canvas")
}
/// Draw the dock (graph and panels) into `ui`.
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let tk = Tokens::get(&ctx);
let style = style(ui, &tk);
let layout = app.ui.dock.workspace.layout.clone();
let mut area = DockArea::new(area_id()).input_blocked(crate::shell::modality::Modality::capture(app, &ctx).is_blocked());
if let Some(panel) = app.ui.dock.raise.take() {
area = area.raise_panel(panel);
}
let output = area.show_content(ui, &layout, &style, &mut Panels { app });
refresh_specs(app);
let shown = app.docks.shown(&app.ui.dock.workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.docks.specs);
// Panels arrange in a split tree around the graph; floating title bars only move windows.
let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false);
let output = {
let mut panels = Panels { app: &mut *app };
DockArea::new("Panels", Bind::given(Arc::clone(&shown)), &specs, &mut panels, config).show(ui)
};
app.docks.specs = specs;
if let Some(error) = &output.error {
log::warn!("docking: {error}");
log::warn!("docking: {:?}", error.error);
}
// A body that changed the layout (a panel opened from its own menu) wins over this frame's
// gestures, which were made against the old one.
if app.ui.dock.workspace.layout != layout {
craft_ui::docking::cancel_drag::<Panel>(&ctx, area_id());
if app.ui.dock.workspace != *shown {
craft_ui::runtime::drag::cancel(&ctx, craft_behavior::CancelReason::HostChanged);
return;
}
for action in output.actions {
for action in output.actions.into_iter().chain(output.requested) {
app.ui.dock.apply(action);
}
}
/// The panels' contents, names and limits for the dock area.
/// The panels' contents for the dock area.
struct Panels<'a> {
app: &'a mut MaterialCraftApp,
}
impl DockContent<Panel> for Panels<'_> {
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
impl DockPanels<Panel> for Panels<'_> {
fn body(&mut self, panel: &Panel, ui: &mut Ui, _: &mut BodyCx<'_>) {
let app = &mut *self.app;
match panel {
Panel::Graph => crate::graph::show(app, ui),
// The graph is its group's `group_view`.
Panel::Graph => {}
Panel::View3d => crate::view3d::show(app, ui),
Panel::View2d => crate::view2d::show(app, ui),
_ => {
@@ -336,31 +371,15 @@ impl DockContent<Panel> for Panels<'_> {
}
}
fn logical_label(&self, panel: &Panel) -> String {
match panel {
Panel::Properties => crate::properties::title(self.app),
Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()),
Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")),
Panel::View2d => crate::view2d::title(self.app),
p => tr(p.name()).to_string(),
/// The graph editor, edge to edge in its group, as the window's document canvas.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Graph) {
return None;
}
}
fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into()
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) };
PanelLimits { min, ..PanelLimits::default() }
}
fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> {
Some(vec2(420.0, 320.0))
crate::framework::host_canvas(ui.ctx(), graph_canvas_id());
crate::graph::show(self.app, ui);
Some(rect.height())
}
}
@@ -373,28 +392,10 @@ mod tests {
let w = default_workspace();
assert!(validate(&w).is_ok());
for panel in Panel::ALL {
assert!(w.layout.contains(&panel) || w.hidden.iter().any(|(p, _)| *p == panel), "{panel:?} is neither shown nor hidden");
assert!(w.layout().contains(&panel) || w.hidden().iter().any(|(p, _)| *p == panel), "{panel:?} is neither shown nor hidden");
}
}
#[test]
fn floating_panels_stop_while_a_dialog_is_open() {
let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
let ctx = egui::Context::default();
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 800.0)));
let frame = |app: &mut crate::MaterialCraftApp| {
ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| show(app, ui)).textures_delta.clear();
ctx.data(|data| data.get_temp::<bool>(area_id().with("input-blocked")))
};
assert_eq!(frame(&mut app), Some(false));
app.ui.windows.unsaved = Some(crate::unsaved::Guarded::Quit);
assert_eq!(frame(&mut app), Some(true), "the panels stop on the frame the prompt opens");
app.ui.windows.unsaved = None;
app.ui.windows.shortcuts = true;
assert_eq!(frame(&mut app), Some(false), "the Shortcuts list does not block");
}
#[test]
fn default_dock_round_trips() {
let dock = Dock::default();
+1 -1
View File
@@ -167,7 +167,7 @@ pub(super) fn rename_dialog(app: &mut MaterialCraftApp, ctx: &egui::Context) {
cancel |= ui.button(tr("Cancel")).clicked();
});
});
cancel |= ctx.input(|input| input.key_pressed(egui::Key::Escape));
cancel |= crate::framework::escape_pressed(ctx);
app.ui.explorer.rename = if open && !cancel { Some((target.clone(), name.clone())) } else { None };
if accept && activate(app, target.document()) {
let mut parameters = target.parameters();
+1 -1
View File
@@ -58,7 +58,7 @@ impl UiFonts {
defs.font_data.insert(name.clone(), data);
defs.families.entry(FontFamily::Proportional).or_default().push(name.clone());
defs.families.entry(FontFamily::Monospace).or_default().push(name);
ctx.set_fonts(defs);
crate::theme::load_fonts(ctx, defs);
self.installed = true;
}
+144
View File
@@ -0,0 +1,144 @@
//! The craft-ui runtime, hosted from MaterialCraft's own eframe `App` (craft-libs docs/craft-framework.md, section
//! 2.2). The desktop app calls [`install`] once, [`MaterialCraftApp::before_input`] in `raw_input_hook`,
//! [`MaterialCraftApp::close_path`] last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests
//! install with [`install_headless`]. The framework dialogs run on [`MaterialCraftApp::framework_dialogs`] after
//! MaterialCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of MaterialCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with
//! [`take_window_cancel`]; the graph editor is declared to the runtime with [`host_canvas`], which keeps Tab, the edit
//! chords and the clipboard events in egui's input for MaterialCraft's shortcuts.
use std::sync::Arc;
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::policy::Decision;
use craft_window::system::WindowSystem;
use crate::MaterialCraftApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The id every OS window of the app carries, as the desktop entry and the update app name it.
const APP_ID: &str = "ai.storyteller.materialcraft";
/// The environment-variable prefix of the frame override: `MATERIALCRAFT_TITLEBAR`.
#[cfg(not(target_arch = "wasm32"))]
const FRAME_PREFIX: craft_window::Prefix = craft_window::Prefix::new("MATERIALCRAFT");
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. MaterialCraft's own definitions
/// ([`crate::theme::install`]) replace it before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>, frame: Option<Decision>) -> Result<(), String> {
let mut spec = craft_ui::InstallSpec::new(shell, windows).app_id(APP_ID);
if let Some(frame) = frame {
spec = spec.frame(frame);
}
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Who draws the main window's frame. The app's bar is the title bar only where the desktop leaves the frame to the
/// app (GNOME on Wayland) or `MATERIALCRAFT_TITLEBAR=app` asks for it; everywhere else the system draws it. Call it
/// once, before the window exists: the desktop app builds its window with [`craft_window::policy::apply`] and hands
/// the decision to [`install`].
#[cfg(not(target_arch = "wasm32"))]
pub fn decide_frame() -> Decision {
use craft_window::policy::{TitleBarPref, decide_for};
let pref = if craft_window::Choice::probe(FRAME_PREFIX).frame().decorations() { TitleBarPref::System } else { TitleBarPref::Integrated };
decide_for(FRAME_PREFIX, craft_host::target::Backend::from_env(), pref)
}
/// Installs the runtime on the desktop window's context, once, before the first pass, with the window's `frame`.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, frame: Decision) -> Result<(), String> {
let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env());
install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows), None) {
log::warn!("{error}");
}
}
/// Who MaterialCraft is to the framework's dialogs (the update dialogs show its name).
pub(crate) fn host() -> Arc<Host> {
Arc::new(Host::builder(AppInfo { id: "materialcraft", name: "MaterialCraft", version: materialcraft_engine::VERSION }).build())
}
impl MaterialCraftApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale and
/// direction).
pub fn before_input(&mut self, ctx: &egui::Context) {
// MaterialCraft applies the interface scale itself (`step`), so the runtime keeps the zoom it applied last.
let scale = ctx.zoom_factor();
embed::before_input(ctx, |output| self.frame_input(output, scale));
}
/// The root values of this frame. MaterialCraft registers no commands with the runtime and lets it toggle no
/// chrome, so the output carries nothing it acts on.
fn frame_input(&mut self, _output: FrameOutput, scale: f32) -> FrameInput {
use crate::theme::Brightness;
let mode = match self.ui.prefs.brightness {
Brightness::Light | Brightness::MediumLight => craft_theme::Mode::Light,
Brightness::Dark | Brightness::MediumDark => craft_theme::Mode::Dark,
};
let direction = if crate::i18n::is_rtl() { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr };
let root = RootEnv::new().mode(mode).scale(Scale::new(scale)).direction(direction);
FrameInput::new(root).host(Arc::clone(&self.framework_host))
}
/// The framework's part of `App::logic`, after MaterialCraft's own: the root window's close path. Unsaved work
/// holds the window open while Save / Discard / Cancel asks ([`crate::unsaved::close_requested`]); a confirmed
/// quit closes it.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || if crate::unsaved::close_requested(self) { CloseDecision::Hold } else { CloseDecision::Close });
}
}
/// Declares the graph editor `id`, drawn in this pass, as the window's document canvas. With nothing focused it is the
/// window's key target: Tab (node search), the edit chords and the clipboard events stay in egui's input for
/// MaterialCraft's shortcuts.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) {
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL);
craft_ui::runtime::focus::host_canvas(ctx, id, KEYS);
}
/// Whether Escape was pressed in this pass: from egui while one of MaterialCraft's own widgets or popups has the
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel(ctx, false)
}
/// Takes the window's cancel (an Escape while nothing has framework focus) when it is there: no later reader sees it.
pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool {
window_cancel(ctx, true)
}
/// Whether the window's cancel is there and untaken; `take` takes it.
fn window_cancel(ctx: &egui::Context, take: bool) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = if take { intents.take(Intent::Cancel) } else { intents.untaken(&Intent::Cancel) };
take && pending
});
pending
}
+3 -2
View File
@@ -115,10 +115,11 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui:
}
});
let list = candidates(app, editor, &search.text);
let (up, down, enter, escape) = ui.input(|input| {
let (up, down, enter) = ui.input(|input| {
let pressed = |key| !blocked && input.key_pressed(key);
(pressed(egui::Key::ArrowUp), pressed(egui::Key::ArrowDown), pressed(egui::Key::Enter), pressed(egui::Key::Escape))
(pressed(egui::Key::ArrowUp), pressed(egui::Key::ArrowDown), pressed(egui::Key::Enter))
});
let escape = !blocked && crate::framework::escape_pressed(ui.ctx());
if down {
search.selected_index = (search.selected_index + 1).min(list.len().saturating_sub(1));
}
+1
View File
@@ -97,6 +97,7 @@ fn clicked_wires_swap_with_x_and_delete_together() {
app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| {
events.insert(0, egui::Event::ModifiersChanged(modifiers));
let input = egui::RawInput { events, ..Default::default() };
+3 -2
View File
@@ -13,8 +13,9 @@ pub(super) struct Frames {
impl Frames {
/// `session` after a few frames, so the canvas is laid out
pub(super) fn new(session: materialcraft_engine::Session) -> Frames {
let mut f =
Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0, canvas_text: Vec::new() };
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut f = Frames { ctx, app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0, canvas_text: Vec::new() };
for _ in 0..3 {
f.run(Vec::new(), egui::Modifiers::NONE);
}
+1 -1
View File
@@ -9,5 +9,5 @@ pub(crate) fn finished(ui: &Ui, owner: PointerButton) -> bool {
}
pub(crate) fn cancelled(ui: &Ui) -> bool {
ui.input(|input| !input.focused || input.key_pressed(egui::Key::Escape))
!ui.input(|input| input.focused) || crate::framework::escape_pressed(ui.ctx())
}
+3 -2
View File
@@ -71,10 +71,11 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) {
if s.connect_to.is_some() {
list.retain(|definition| !definition.outputs.is_empty());
}
let (up, down, enter, esc) = ui.input(|i| {
let (up, down, enter) = ui.input(|i| {
let pressed = |key| !blocked && i.key_pressed(key);
(pressed(egui::Key::ArrowUp), pressed(egui::Key::ArrowDown), pressed(egui::Key::Enter), pressed(egui::Key::Escape))
(pressed(egui::Key::ArrowUp), pressed(egui::Key::ArrowDown), pressed(egui::Key::Enter))
});
let esc = !blocked && crate::framework::escape_pressed(ui.ctx());
if down {
s.sel = (s.sel + 1).min(list.len().saturating_sub(1));
}
+1 -1
View File
@@ -41,7 +41,7 @@ pub fn current() -> &'static Language {
/// Returns true if `code` is a right-to-left language (e.g. Arabic `"ar"`).
pub fn is_rtl_code(code: &str) -> bool {
craft_ui::direction::resolve(code, craft_ui::direction::Setting::Language) == craft_ui::direction::Direction::Rtl
craft_i18n::direction(code) == craft_i18n::Direction::Rtl
}
/// Returns true if the current UI language is right-to-left.
+2
View File
@@ -8,6 +8,7 @@ pub mod docking;
pub mod explorer;
pub mod export;
pub mod fonts;
pub mod framework;
pub mod function;
pub mod graph;
mod graph_drag_payload;
@@ -26,6 +27,7 @@ mod preview_resolution;
#[path = "property/mod.rs"]
pub mod properties;
mod shell;
mod shortcut_dispatch;
pub mod state;
pub mod theme;
pub mod thumbs;
+19 -22
View File
@@ -58,12 +58,15 @@ pub struct MaterialCraftApp {
pub(crate) material_export_job: Option<std::sync::mpsc::Receiver<Result<Value, String>>>,
/// The held action waiting for the Save dialog the unsaved-changes prompt opened
pub(crate) awaiting_save: Option<crate::unsaved::Guarded>,
/// The window buttons to draw when the app draws the window frame; `None` while the desktop draws it (desktop only)
#[cfg(not(target_arch = "wasm32"))]
pub window_layout: Option<craft_window::Layout>,
/// Keyboard shortcuts and their dispatch
pub(crate) keymap: craft_keymap::Keymap,
pub(crate) dispatcher: craft_keymap::egui::Dispatcher,
pub(crate) dispatcher: crate::shortcut_dispatch::Dispatcher,
/// The dock area's workspace and panel specs between passes
pub(crate) docks: docking::LiveDock,
/// The framework dialogs (the update dialogs), run once per pass after MaterialCraft's own UI
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who MaterialCraft is to the framework's dialogs
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
/// What Copy or Cut put on the clipboard this frame, for the system clipboard
pub(crate) system_clipboard: Option<String>,
/// Fallback fonts for Arabic
@@ -135,12 +138,11 @@ impl MaterialCraftApp {
#[cfg(not(target_arch = "wasm32"))]
material_export_job: None,
awaiting_save: None,
#[cfg(not(target_arch = "wasm32"))]
window_layout: None,
keymap: menus::keymap(craft_keymap::Platform::current()),
// Accept clipboard events without duplicating web key commands
dispatcher: craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(true),
dispatcher: crate::shortcut_dispatch::Dispatcher::default(),
docks: docking::LiveDock::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: crate::framework::host(),
system_clipboard: None,
fonts: fonts::UiFonts::default(),
fonts_ready: false,
@@ -450,18 +452,19 @@ impl eframe::App for MaterialCraftApp {
}
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
control::feed_input(self, raw);
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(not(target_arch = "wasm32"))]
self.step_then(ctx, craft_quit::on_close_request);
#[cfg(target_arch = "wasm32")]
self.step(ctx);
self.close_path(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
#[cfg(not(target_arch = "wasm32"))]
crate::framework::before_ui(ui.ctx(), &*frame);
self.draw(ui);
#[cfg(not(target_arch = "wasm32"))]
self.dialogs.show_pending(Some(&*frame));
@@ -471,13 +474,6 @@ impl eframe::App for MaterialCraftApp {
}
impl MaterialCraftApp {
/// [`Self::step`], then the platform's close handling, which sees a close `step` canceled
#[cfg(not(target_arch = "wasm32"))]
fn step_then(&mut self, ctx: &egui::Context, close: impl FnOnce(&egui::Context) -> bool) {
self.step(ctx);
close(ctx);
}
/// Per-frame logic before drawing: styles, the control channel, cooking, shortcuts
pub fn step(&mut self, ctx: &egui::Context) {
if !self.fonts_ready {
@@ -509,7 +505,7 @@ impl MaterialCraftApp {
self.session.finish_edit();
}
crate::unsaved::handle_close(self, ctx);
crate::unsaved::finish_quit(self, ctx);
control::poll(self, ctx);
web_files::poll(self);
#[cfg(not(target_arch = "wasm32"))]
@@ -565,8 +561,9 @@ impl MaterialCraftApp {
self.ui.explorer.hovered = false;
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui));
windows::show(self, &ctx);
self.framework_dialogs.run(ui);
#[cfg(not(target_arch = "wasm32"))]
if self.window_layout.is_some() {
if crate::window_controls::app_draws_frame(&ctx) {
crate::window_controls::resize_zones(ui);
}
@@ -57,6 +57,7 @@ mod lib_tests {
app.ui.explorer.hovered = true;
app.ui.dock.close(crate::docking::Panel::Explorer);
let context = egui::Context::default();
crate::framework::install_headless(&context);
context.run_ui(egui::RawInput::default(), |ui| app.draw(ui)).textures_delta.clear();
@@ -79,14 +80,14 @@ mod close_order_tests {
fn close_frame(app: &mut MaterialCraftApp) -> bool {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut input = egui::RawInput::default();
input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
let mut canceled = false;
ctx.run_ui(input, |ui| {
app.step_then(ui.ctx(), |ctx| {
canceled = ctx.viewport(|viewport| viewport.commands.contains(&egui::ViewportCommand::CancelClose));
false
});
app.step(ui.ctx());
app.close_path(ui.ctx());
canceled = ui.ctx().viewport(|viewport| viewport.commands.contains(&egui::ViewportCommand::CancelClose));
})
.textures_delta
.clear();
+66 -58
View File
@@ -1,6 +1,6 @@
//! Menu actions and shortcuts share stable command ids
use craft_keymap::{Active, Binding, Chord, CommandDef, Keymap, Platform, Scope, Scopes};
use craft_keymap::{Binding, Chord, CommandDef, Keymap, Platform, Scope, Scopes};
use egui::class::HasClasses as _;
use serde_json::Value;
@@ -328,61 +328,61 @@ pub fn shortcut_of(id: &str) -> Option<&'static str> {
CATALOG.iter().find(|i| i.id == id).and_then(|i| i.shortcut).or_else(|| materialcraft_engine::find(id).and_then(|c| c.shortcut))
}
/// Draw menu bars with aligned labels and a separate gutter for checkmarks.
/// Draw menu bars with aligned labels and a separate gutter for checkmarks. Where the app draws the window's frame, the
/// menu bar is the window's title bar: the framework's title bar holds it, with the move area and the caption buttons
/// of the desktop's layout.
pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) {
let tokens = Tokens::get(ui.ctx());
egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tokens.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| {
#[cfg(not(target_arch = "wasm32"))]
let window_layout = app.window_layout.clone();
#[cfg(not(target_arch = "wasm32"))]
if window_layout.is_some() {
craft_window::title_bar::empty_area(ui, ui.max_rect());
}
egui::MenuBar::new().ui(ui, |ui| {
let context = ui.ctx().clone();
#[cfg(not(target_arch = "wasm32"))]
if let Some(layout) = &window_layout {
crate::window_controls::buttons(ui, &context, &layout.left);
}
for top in TOP {
ui.menu_button(tr(top), |ui| {
ui.set_min_width(220.0);
let mut current_submenu: Option<&str> = None;
let items: Vec<MenuItem> = CATALOG.iter().filter(|item| item.menu == top).copied().collect();
for item in &items {
if let Some(submenu) = item.sub {
if current_submenu == Some(submenu) {
continue;
}
current_submenu = Some(submenu);
ui.menu_button(menu_label(tr(submenu)), |ui| {
for entry in items.iter().filter(|entry| entry.sub == Some(submenu)) {
menu_item(app, &context, ui, entry);
}
});
continue;
}
if item.label == "-" {
ui.separator();
continue;
}
menu_item(app, &context, ui, item);
}
});
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(layout) = window_layout.as_ref().filter(|layout| !layout.right.is_empty()) {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut right = layout.right.clone();
right.reverse();
crate::window_controls::buttons(ui, &context, &right);
});
#[cfg(not(target_arch = "wasm32"))]
if crate::window_controls::app_bar_is_title_bar(ui.ctx()) {
use craft_ui::contract::ShowContainer as _;
egui::Panel::top("menu_bar").frame(egui::Frame::NONE.fill(tokens.chrome)).show(ui, |ui| {
let bar = craft_ui::shell::TitleBar::new().show(ui, |ui, _| menus(app, ui)).output;
if bar.close_requested {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
});
return;
}
egui::Panel::top("menu_bar")
.exact_size(24.0)
.frame(egui::Frame::NONE.fill(tokens.chrome).inner_margin(egui::Margin::symmetric(6, 0)))
.show(ui, |ui| menus(app, ui));
}
/// The top-level menus, in a menu bar
fn menus(app: &mut MaterialCraftApp, ui: &mut egui::Ui) {
egui::MenuBar::new().ui(ui, |ui| {
let context = ui.ctx().clone();
for top in TOP {
ui.menu_button(tr(top), |ui| {
ui.set_min_width(220.0);
let mut current_submenu: Option<&str> = None;
let items: Vec<MenuItem> = CATALOG.iter().filter(|item| item.menu == top).copied().collect();
for item in &items {
if let Some(submenu) = item.sub {
if current_submenu == Some(submenu) {
continue;
}
current_submenu = Some(submenu);
ui.menu_button(menu_label(tr(submenu)), |ui| {
for entry in items.iter().filter(|entry| entry.sub == Some(submenu)) {
menu_item(app, &context, ui, entry);
}
});
continue;
}
if item.label == "-" {
ui.separator();
continue;
}
menu_item(app, &context, ui, item);
}
});
}
});
}
@@ -460,6 +460,14 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
return;
}
// A plain Escape no widget of MaterialCraft's took is the window's cancel: it runs the Escape shortcuts
if crate::framework::take_window_cancel(ctx) {
ctx.input_mut(|i| {
let modifiers = i.modifiers;
i.events.insert(0, egui::Event::Key { key: egui::Key::Escape, physical_key: Some(egui::Key::Escape), pressed: true, repeat: false, modifiers });
});
}
// The desktop sends Copy, Cut and Paste events in place of their key presses
if !ctx
.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. } | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_))))
@@ -491,7 +499,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let gesture_in_progress = ctx.input(|i| i.pointer.any_down());
let node_search_open = app.graph.search_is_open() || app.function_editor.as_ref().is_some_and(|editor| editor.search.is_some());
let hits = ctx.input_mut(|i| {
app.dispatcher.dispatch_filtered(i, &app.keymap, &Active::NONE, |hit| {
app.dispatcher.dispatch_filtered(i, &app.keymap, |hit| {
let id = hit.command.id.as_str();
let keeps_escape = id == "ui.cook.cancel" && (!app.cooker.busy() || gesture_in_progress || node_search_open || label_selected);
modality.allows(id) && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) && !unavailable_clipboard_commands.contains(&id) && !keeps_escape
@@ -551,7 +559,7 @@ mod tests {
owners.entry(chord.to_string()).or_insert((id, chord));
}
for (id, chord) in owners.into_values() {
assert_eq!(map.lookup(&chord, false, &Active::NONE), craft_keymap::Lookup::Run(id.into()), "{chord}");
assert_eq!(map.lookup(&chord, false, &craft_keymap::Active::NONE), craft_keymap::Lookup::Run(id.into()), "{chord}");
}
}
}
@@ -782,7 +790,7 @@ mod tests {
let mut app = app();
app.ui.recent.push("recent.sbs".into());
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut MaterialCraftApp| menu_bar(app, ui), app);
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_ui_state(|ui, app: &mut MaterialCraftApp| menu_bar(app, ui), app);
harness.run_steps(2);
harness.get_by_label("File").click();
harness.run_steps(3);
@@ -802,7 +810,7 @@ mod tests {
let mut app = app();
app.dialogs.ask(craft_dialogs::FileDialog::open(), crate::native_dialogs::Then::OpenPackage);
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut MaterialCraftApp| menu_bar(app, ui), app);
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_ui_state(|ui, app: &mut MaterialCraftApp| menu_bar(app, ui), app);
harness.run_steps(2);
harness.get_by_label("File").click();
harness.run_steps(3);
@@ -898,7 +906,7 @@ mod tests {
#[test]
fn a_web_copy_press_runs_edit_copy() {
let mut app = app();
app.dispatcher = craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(true);
app.dispatcher = crate::shortcut_dispatch::Dispatcher::default();
app.run("edit.selectAll", serde_json::json!({}));
let ctx = egui::Context::default();
copy_event_kept(&mut app, &ctx, press_c(vec![egui::Event::Copy]));
@@ -908,7 +916,7 @@ mod tests {
#[test]
fn selected_label_text_keeps_its_copy_on_the_web() {
let mut app = app();
app.dispatcher = craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(true);
app.dispatcher = crate::shortcut_dispatch::Dispatcher::default();
app.run("edit.selectAll", serde_json::json!({}));
let ctx = egui::Context::default();
select_label_text(&ctx);
+2 -2
View File
@@ -63,13 +63,13 @@ impl GraphRef {
/// A queue for an app that has no window to wake yet (offscreen snapshots and tests)
pub(crate) fn unattached() -> Dialogs {
craft_dialogs::Dialogs::new(std::sync::Arc::new(|| {}))
craft_dialogs::Dialogs::new(craft_dialogs::Wake::none())
}
/// A queue whose answers wake the window
pub(crate) fn attached(ctx: &egui::Context) -> Dialogs {
let ctx = ctx.clone();
craft_dialogs::Dialogs::new(std::sync::Arc::new(move || ctx.request_repaint()))
craft_dialogs::Dialogs::new(craft_dialogs::Wake::new(move || ctx.request_repaint()))
}
/// Queue a dialog unless one is already open or waiting, in which case the open one comes forward
+17 -15
View File
@@ -248,7 +248,7 @@ fn the_prompts_save_with_a_path_saves_and_runs_the_action_at_once() {
#[test]
fn the_app_shows_a_requested_dialog_and_applies_its_answer() {
let mut harness = egui_kittest::Harness::builder().build_eframe(|_| app());
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|_| app());
harness.step();
harness.step();
let path = temp("frames.sbs");
@@ -452,29 +452,31 @@ fn a_held_close_waits_for_the_save_dialog() {
answer_prompt_with_save(&mut app);
app.session.modified = false;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut input = egui::RawInput::default();
input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
let mut output = ctx.run_ui(input, |ui| crate::unsaved::handle_close(&mut app, ui.ctx()));
let mut output = ctx.run_ui(input, |ui| app.close_path(ui.ctx()));
output.textures_delta.clear();
let commands = output.viewport_output.remove(&egui::ViewportId::ROOT).map(|root| root.commands).unwrap_or_default();
assert!(commands.contains(&egui::ViewportCommand::CancelClose));
}
/// The runtime brings a held window forward, a minimized one included, so the prompt can show.
#[test]
fn a_held_close_restores_a_minimized_window() {
for (minimized, restored) in [(Some(true), true), (Some(false), false), (None, false)] {
let mut app = modified_app_asking_to_quit();
app.ui.windows.unsaved = None;
let ctx = egui::Context::default();
let mut input = egui::RawInput::default();
let root = input.viewports.entry(egui::ViewportId::ROOT).or_default();
root.minimized = minimized;
root.events.push(egui::ViewportEvent::Close);
let mut output = ctx.run_ui(input, |ui| crate::unsaved::handle_close(&mut app, ui.ctx()));
output.textures_delta.clear();
let commands = output.viewport_output.remove(&egui::ViewportId::ROOT).map(|root| root.commands).unwrap_or_default();
assert_eq!(commands.contains(&egui::ViewportCommand::Minimized(false)), restored, "{minimized:?}");
}
let mut app = modified_app_asking_to_quit();
app.ui.windows.unsaved = None;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut input = egui::RawInput::default();
let root = input.viewports.entry(egui::ViewportId::ROOT).or_default();
root.minimized = Some(true);
root.events.push(egui::ViewportEvent::Close);
let mut output = ctx.run_ui(input, |ui| app.close_path(ui.ctx()));
output.textures_delta.clear();
let commands = output.viewport_output.remove(&egui::ViewportId::ROOT).map(|root| root.commands).unwrap_or_default();
assert!(commands.contains(&egui::ViewportCommand::Minimized(false)), "{commands:?}");
assert!(app.ui.windows.unsaved.is_some(), "the prompt asks");
}
#[test]
@@ -108,6 +108,11 @@ fn field(app: &mut MaterialCraftApp, ui: &mut Ui, entry: &str, label: &str) {
fn capture(app: &mut MaterialCraftApp, ui: &mut Ui) {
let Some(entry) = app.ui.preferences.capturing.clone() else { return };
// A plain Escape cancels the wait; with no field of MaterialCraft's focused it is the window's cancel
if crate::framework::take_window_cancel(ui.ctx()) {
app.ui.preferences.capturing = None;
return;
}
let platform = craft_keymap::egui::platform(ui.ctx());
let chord = ui.input(|input| input.events.iter().find_map(|event| crate::node_shortcuts::event_chord(event, platform)));
let Some(chord) = chord else { return };
@@ -145,6 +145,7 @@ fn a_file_dropped_behind_a_prompt_does_not_reach_the_package() {
let mut app = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut app, &ctx, Vec::new());
frame(&mut app, &ctx, Vec::new());
let png = encode(&Image::filled(2, 2, Kind::Gray, [0.5; 4]), "png", Depth::U8, false).unwrap();
+249
View File
@@ -0,0 +1,249 @@
//! The frame's key presses and clipboard events as the shortcuts they run: egui's events fed to
//! `craft_keymap::Matcher`, one press at a time in press order.
//!
//! - A press that runs a command is removed from egui's input, with the text it typed; one that
//! runs nothing, or whose hit the caller declines, stays.
//! - Held keys run their command again on each repeat (a held arrow nudges); repeats never count
//! toward a double press.
//! - egui's Copy, Cut and Paste events count as their plain chords (Cmd+C, Cmd+X, Cmd+V;
//! Shift+Delete and Shift+Insert), so the desktop's clipboard events run the edit commands. The
//! web build sends a clipboard press and the clipboard event it causes: the press decides, and
//! its event goes with it when it runs a command and stays otherwise.
//! - The keyboard layout is learned from what plain presses type, and taken from egui when the
//! integration reports whether it is Latin.
use craft_keymap::{Active, Hit, Key, KeyInput, Keymap, Layout, Matcher, Mods, Platform, Press};
use egui::{Event, InputState, Key as EguiKey};
/// eframe's web build sends a press's Text event first when no text field has focus.
const TEXT_FIRST: bool = cfg!(target_arch = "wasm32");
/// What matching carries between frames: the previous press (double presses) and the layout.
#[derive(Default)]
pub(crate) struct Dispatcher {
matcher: Matcher,
layout: Layout,
/// Whether right Alt is held. egui-winit reports AltGr with neither Ctrl nor Alt, so its
/// presses would otherwise teach the layout as plain ones.
right_alt: bool,
}
impl Dispatcher {
/// The commands this frame's key presses and clipboard events run, in press order, with
/// `accept` deciding each hit before its event is removed. A declined hit is left out and its
/// event, with any text it typed, stays in egui's input in its place.
pub(crate) fn dispatch_filtered(&mut self, input: &mut InputState, keymap: &Keymap, mut accept: impl FnMut(&Hit) -> bool) -> Vec<Hit> {
let platform = keymap.platform();
let now = input.time;
let frame_mods = Mods::from_egui(&input.modifiers, platform);
let events = std::mem::take(&mut input.events);
let text_of = text_of_press(&events, TEXT_FIRST);
if let Some(latin) = input.keyboard_layout_is_latin() {
self.layout.set_latin(Some(latin));
}
self.learn(&events, &text_of, platform);
let causes = clipboard_event_follows(&events, &self.layout, platform, input);
let mut caused_taken: Vec<Option<bool>> = vec![None; events.len()];
let mut drop = vec![false; events.len()];
let mut hits = Vec::new();
let mut kept = Vec::with_capacity(events.len());
for (i, event) in events.into_iter().enumerate() {
match &event {
Event::Key { pressed: true, repeat, .. } => {
let key = key_input(&event, platform, input);
if self.layout.resolve(&key).is_some() {
let press = Press { input: &key, repeat: *repeat, now, active: &Active::NONE, outer: &[] };
let hit = self.matcher.press(&self.layout, keymap, &press).filter(&mut accept);
if let Some((j, _)) = causes[i] {
caused_taken[j] = Some(hit.is_some());
}
if let Some(hit) = hit {
hits.push(hit);
if let Some(j) = text_of[i].filter(|_| !(key.mods.cmd || key.mods.ctrl)) {
drop[j] = true;
}
continue;
}
}
}
// Desktop clipboard events, and web ones whose press ran nothing.
Event::Copy | Event::Cut | Event::Paste(_) => match caused_taken[i] {
Some(true) => continue,
Some(false) => {}
None => {
let (key, held) = clipboard_chord(&event, frame_mods);
let press = Press { input: &KeyInput::new(held).with_typed(key), repeat: false, now, active: &Active::NONE, outer: &[] };
if let Some(hit) = self.matcher.press(&self.layout, keymap, &press).filter(&mut accept) {
hits.push(hit);
continue;
}
}
},
_ => {}
}
kept.push((i, event));
}
input.events = kept.into_iter().filter(|(i, _)| !drop[*i]).map(|(_, e)| e).collect();
hits
}
/// Teaches the layout what this frame's presses typed.
fn learn(&mut self, events: &[Event], text_of: &[Option<usize>], platform: Platform) {
for (event, text) in events.iter().zip(text_of) {
match event {
Event::Key { physical_key: Some(EguiKey::AltRight), pressed, .. } => self.right_alt = *pressed,
Event::WindowFocused(false) => self.right_alt = false,
_ => {}
}
if self.right_alt {
continue;
}
let Some(Event::Text(text)) = text.and_then(|j| events.get(j)) else { continue };
if let Some(KeyInput { mods, physical: Some(physical), .. }) = KeyInput::from_egui(event, platform) {
self.layout.observe(physical, mods, text);
}
}
}
}
/// A press as [`KeyInput::from_egui`] reads it, with the Latin layout's character `input` reports
/// for its key.
fn key_input(event: &Event, platform: Platform, input: &InputState) -> KeyInput {
let mut key = KeyInput::from_egui(event, platform).unwrap_or(KeyInput::new(Mods::NONE));
if let Event::Key { physical_key: Some(physical), .. } = event {
key.latin = input.latin_layout_char(*physical);
}
key
}
/// A clipboard event's kind.
#[derive(Clone, Copy)]
enum Clip {
Copy,
Cut,
Paste,
}
fn event_clip(event: &Event) -> Option<Clip> {
match event {
Event::Copy => Some(Clip::Copy),
Event::Cut => Some(Clip::Cut),
Event::Paste(_) => Some(Clip::Paste),
_ => None,
}
}
/// The clipboard event a backend sends for a press, if any.
fn clipboard_kind(key: Key, held: Mods) -> Option<Clip> {
match key {
Key::C if held.cmd => Some(Clip::Copy),
Key::X if held.cmd => Some(Clip::Cut),
Key::V if held.cmd => Some(Clip::Paste),
Key::Delete if held.shift => Some(Clip::Cut),
Key::Insert if held.shift => Some(Clip::Paste),
Key::Insert if held.cmd || held.ctrl => Some(Clip::Copy),
_ => None,
}
}
/// For each clipboard key press whose clipboard event comes later in the frame, as the web build
/// sends them: the index of that event, and the text of a Paste event.
fn clipboard_event_follows(events: &[Event], layout: &Layout, platform: Platform, input: &InputState) -> Vec<Option<(usize, Option<String>)>> {
let mut out = vec![None; events.len()];
let mut ahead: [Option<usize>; 3] = [None; 3];
for (i, event) in events.iter().enumerate().rev() {
if let Some(seen) = event_clip(event).and_then(|c| ahead.get_mut(c as usize)) {
*seen = Some(i);
} else if let Event::Key { pressed: true, .. } = event {
let chord = layout.resolve(&key_input(event, platform, input));
let clip = chord.and_then(|c| clipboard_kind(c.key, c.mods));
if let Some(j) = clip.and_then(|c| ahead.get_mut(c as usize)).and_then(Option::take) {
let text = if let Some(Event::Paste(text)) = events.get(j) { Some(text.clone()) } else { None };
out[i] = Some((j, text));
}
}
}
out
}
/// For each key press, the index of the Text event it typed. egui-winit, and eframe's web text
/// agent while a text field has focus, send the Text after the press, before the next one.
/// With `text_first`, eframe's web build with no text field focused, the Text comes right before
/// its press, and only for a press without Ctrl or Cmd.
fn text_of_press(events: &[Event], text_first: bool) -> Vec<Option<usize>> {
let is_text = |e: Option<&Event>| matches!(e, Some(Event::Text(t)) if !t.is_empty());
let mut out = vec![None; events.len()];
if text_first {
for (i, event) in events.iter().enumerate().skip(1) {
if let Event::Key { pressed: true, modifiers, .. } = event
&& !(modifiers.ctrl || modifiers.command || modifiers.mac_cmd)
&& is_text(events.get(i - 1))
{
out[i] = Some(i - 1);
}
}
return out;
}
let mut text_ahead = None;
for (i, event) in events.iter().enumerate().rev() {
match event {
Event::Key { pressed: true, .. } => out[i] = text_ahead.take(),
_ if is_text(Some(event)) => text_ahead = Some(i),
_ => {}
}
}
out
}
/// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also
/// sends Cut for Shift+Delete and Paste for Shift+Insert.
fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) {
let with_cmd = Mods { cmd: true, ..held };
let shift_only = held.shift && !held.cmd;
match event {
Event::Cut if shift_only => (Key::Delete, held),
Event::Cut => (Key::X, with_cmd),
Event::Paste(_) if shift_only => (Key::Insert, held),
Event::Paste(_) => (Key::V, with_cmd),
_ => (Key::C, with_cmd),
}
}
#[cfg(test)]
mod tests {
use super::*;
use craft_keymap::{Binding, CommandDef, Scope, Scopes};
fn keymap() -> Keymap {
let def = |id: &'static str, binding: &str| CommandDef::new(id, id, Scope::app()).with_default(Binding::parse(binding).unwrap());
Keymap::new(vec![def("tool.marquee", "M"), def("edit.copy", "Ctrl+C")], Scopes::new(), Platform::Windows)
}
fn press(key: EguiKey, modifiers: egui::Modifiers) -> Event {
Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }
}
/// A press that runs a command leaves egui's input with the text it typed; the others stay, in order.
#[test]
fn a_bound_press_and_its_text_leave_the_input() {
let mut input = InputState::default();
input.events = vec![press(EguiKey::M, egui::Modifiers::NONE), Event::Text("m".into()), press(EguiKey::Q, egui::Modifiers::NONE), Event::Text("q".into())];
let hits = Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| true);
assert_eq!(hits.iter().map(|hit| hit.command.id.as_str()).collect::<Vec<_>>(), ["tool.marquee"]);
assert_eq!(input.events, [press(EguiKey::Q, egui::Modifiers::NONE), Event::Text("q".into())]);
}
/// The desktop's Copy event runs the copy command; declined, it stays for egui.
#[test]
fn a_clipboard_event_runs_its_chord_unless_declined() {
let mut input = InputState::default();
input.events = vec![Event::Copy];
let hits = Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| true);
assert_eq!(hits.iter().map(|hit| hit.command.id.as_str()).collect::<Vec<_>>(), ["edit.copy"]);
assert!(input.events.is_empty());
input.events = vec![Event::Copy];
assert!(Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| false).is_empty());
assert_eq!(input.events, [Event::Copy]);
}
}
+19 -3
View File
@@ -292,9 +292,19 @@ pub fn font_definitions() -> egui::FontDefinitions {
fonts
}
/// Gives the context `fonts` through the framework runtime, which keeps its layout memory in step with them. The
/// framework's chrome (the dock, the update dialogs) also draws in the signature and semibold families; both take the
/// proportional faces, as MaterialCraft has no bold face. A family left out draws missing-glyph boxes.
pub fn load_fonts(ctx: &egui::Context, mut fonts: egui::FontDefinitions) {
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional.clone());
fonts.families.insert(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()), proportional);
craft_ui::fonts::load(ctx, fonts);
}
/// Install the fonts (once, at startup; the app applies the style from its settings).
pub fn install(ctx: &egui::Context) {
ctx.set_fonts(font_definitions());
load_fonts(ctx, font_definitions());
}
/// Apply brightness `b` and `accent`: store the tokens for [`Tokens::get`] and style egui with
@@ -334,8 +344,14 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) {
v.selection.stroke = Stroke::new(1.0, t.accent);
v.hyperlink_color = t.accent;
let w = &mut v.widgets;
craft_ui::theme::WidgetPalette { noninteractive: t.panel, inactive: t.button, hovered: t.row_hover, active: t.tool_active, open: t.row_hover }
.apply_to(w, t.cr(), Stroke::new(1.0, t.text));
for (widget, fill) in
[(&mut w.noninteractive, t.panel), (&mut w.inactive, t.button), (&mut w.hovered, t.row_hover), (&mut w.active, t.tool_active), (&mut w.open, t.row_hover)]
{
widget.bg_fill = fill;
widget.weak_bg_fill = fill;
widget.corner_radius = t.cr();
widget.fg_stroke = Stroke::new(1.0, t.text);
}
// Hovered and pressed lettering, and `RichText::strong` (captions), in the strong colour.
w.hovered.fg_stroke.color = t.text_strong;
w.active.fg_stroke.color = t.text_strong;
+19 -16
View File
@@ -118,22 +118,25 @@ fn perform(app: &mut MaterialCraftApp, action: Guarded) {
}
}
/// Per frame: hold back a window close while there is unsaved work, and finish a confirmed quit
pub fn handle_close(app: &mut MaterialCraftApp, ctx: &Context) {
if ctx.input(|i| i.viewport().close_requested()) && !app.quit_confirmed {
// Focused text is still a draft when the OS asks to close the window
crate::properties::GraphPropertyDraft::commit(app);
// While the Save dialog of a held action is open, the close waits for its answer
if app.awaiting_save.is_some() || holds_close(needs_confirmation(&app.session), app.quit_confirmed) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
// The prompt is drawn only while the window is visible
if ctx.input(|i| i.viewport().minimized) == Some(true) {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
guard(app, Guarded::Quit);
}
/// The root window was asked to close: whether unsaved work holds it open. Holding asks Save / Discard / Cancel for
/// the modified packages, and the runtime keeps the window open and brings it forward while the question is up.
/// Runs in the framework's close path ([`MaterialCraftApp::close_path`]).
pub fn close_requested(app: &mut MaterialCraftApp) -> bool {
if app.quit_confirmed {
return false;
}
// Focused text is still a draft when the OS asks to close the window
crate::properties::GraphPropertyDraft::commit(app);
// While the Save dialog of a held action is open, the close waits for its answer
let holds = app.awaiting_save.is_some() || holds_close(needs_confirmation(&app.session), app.quit_confirmed);
if holds {
guard(app, Guarded::Quit);
}
holds
}
/// Per frame: close the window once a quit is confirmed
pub fn finish_quit(app: &MaterialCraftApp, ctx: &Context) {
if app.quit_confirmed {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
@@ -174,7 +177,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &Context) {
}
});
});
if choice.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if choice.is_none() && crate::framework::escape_pressed(ctx) {
choice = Some(Choice::Cancel);
}
let Some(choice) = choice else { return };
+37 -16
View File
@@ -1,8 +1,10 @@
//! Software updates on the desktop: the background check at startup, Help > Check for updates and
//! the prompts that report them
//! the prompts that report them, as craft-update's dialogs on the app's
//! [`DialogHost`](craft_ui::dialog::DialogHost)
use craft_ui::dialog::DialogResult;
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
use craft_update::updater::{Action, Status, Updater};
use craft_update::{CheckResultDialog, CheckResultResponse};
use crate::MaterialCraftApp;
@@ -58,9 +60,9 @@ pub(crate) fn tick(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let rt = &mut app.updates_rt;
rt.repaint = Some(ctx.clone());
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
rt.updater.check_now();
} else if rt.startup_check {
rt.updater.check_at_start(ctx);
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
}
@@ -72,25 +74,44 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool {
!prompt_open && !matches!(status, Status::Idle)
}
/// One pass of the update flow, before the dialog host runs: answers the result dialog closed in
/// the last pass, drives the startup prompt, and keeps the result dialog open and current while the
/// updater has something to report
pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
// An installation, and the close for a ready update, wait until nothing is unsaved
let clean = !crate::unsaved::needs_confirmation(&app.session);
match app.updates_rt.updater.show_if(ctx, clean) {
// Answered before the dialog is kept open below, so a dismissed outcome does not open again at once
match app.framework_dialogs.take::<UpdateCheckDialog>() {
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.check_requested = true,
// The next `run` asks the window to close once nothing is unsaved
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
Some(DialogResult::Ok(CheckChoice::Update)) => {
app.updates_rt.updater.request_install(clean);
}
Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
// Closing the dialog dismisses the outcome it showed
Some(_) => app.updates_rt.updater.dismiss_status(),
None => {}
}
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Action::None => {}
_ => {}
}
// A found update opens the startup prompt and leaves the status idle, which ends the result dialog
let rt = &mut app.updates_rt;
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, materialcraft_engine::VERSION).with_translator(translate).show(ctx, rt.updater.status()) {
CheckResultResponse::None => {}
// Closing the dialog dismisses the outcome it showed
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => rt.check_requested = true,
// The next `show_if` asks the window to close once nothing is unsaved
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
}
let updater = &app.updates_rt.updater;
let shows = result_window_shows(updater.status(), updater.prompt_open());
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
let dialogs = &mut app.framework_dialogs;
if shows && !dialogs.is_open::<UpdateCheckDialog>() {
dialogs.open(UpdateCheckDialog::new(materialcraft_engine::VERSION));
} else if !shows && dialogs.is_open::<UpdateCheckDialog>() {
dialogs.cancel::<UpdateCheckDialog>(ctx);
}
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
}
+15 -2
View File
@@ -111,6 +111,7 @@ fn frame(app: &mut MaterialCraftApp, ctx: &egui::Context) {
fn the_menu_command_starts_a_check_on_the_next_frame() {
let (mut app, checks, _) = app_with_source();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut app, &ctx);
menus::invoke(&mut app, &ctx, COMMAND);
assert!(app.updates_rt.check_requested);
@@ -167,7 +168,13 @@ fn an_offered_release_opens_the_prompt_over_the_window() {
assert!(blocks_input(&app));
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut MaterialCraftApp| crate::windows::show(app, ui.ctx()), app);
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
crate::windows::show(app, ui.ctx());
app.framework_dialogs.run(ui);
},
app,
);
harness.run_steps(3);
@@ -191,7 +198,13 @@ fn a_requested_check_shows_its_progress() {
check(&mut app);
tick(&mut app, &egui::Context::default());
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut MaterialCraftApp| crate::windows::show(app, ui.ctx()), app);
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
crate::windows::show(app, ui.ctx());
app.framework_dialogs.run(ui);
},
app,
);
harness.run_steps(3);
let _ = harness.get_by_label("Checking for updates…");
drop(release);
+1 -1
View File
@@ -156,7 +156,7 @@ fn keys(app: &mut MaterialCraftApp, ui: &Ui, response: &Response) {
if pressed(Modifiers::NONE, Key::L) {
app.view3d.tool = Tool::Light;
}
if pressed(Modifiers::NONE, Key::Escape) {
if ui.input(|input| input.modifiers.is_none()) && crate::framework::escape_pressed(ui.ctx()) {
app.view3d.selected = false;
}
}
+1 -1
View File
@@ -65,7 +65,7 @@ impl PackageSave {
});
});
app.ui.windows.package_save = Some(request);
let dismissed = !open || cancel || ctx.input(|input| input.key_pressed(egui::Key::Escape));
let dismissed = !open || cancel || crate::framework::escape_pressed(ctx);
if accept || dismissed {
Self::finish(app, accept && !dismissed, download);
}
+24 -16
View File
@@ -1,7 +1,6 @@
//! Compact widgets matching the app's look: labelled slim sliders, icon buttons, section
//! headers, channel toggle chips and color swatches.
use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle};
use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2};
use crate::theme::Tokens;
@@ -179,24 +178,33 @@ pub fn elided(painter: &egui::Painter, text: impl Into<String>, size: f32, color
}
/// A square icon button (Phosphor glyph) in a rounded tool well: `selected` sits in the accent
/// tinted well (the shared Craft icon button, `craft_ui::buttons`).
/// tinted well, a hovered one in the row-hover well and a pressed one in the tool well; keyboard
/// focus draws an inset accent outline. `tooltip` is its accessible name and tooltip. A
/// non-finite, non-positive or oversized (over 4096 points) size gives an inert zero-size response.
pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: f32) -> Response {
let tk = Tokens::get(ui.ctx());
let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon };
let style = IconButtonStyle {
normal: well(Color32::TRANSPARENT, tk.text),
hovered: well(tk.row_hover, tk.text_strong),
pressed: Some(well(tk.tool_active, tk.text_strong)),
selected: well(tk.tool_active, tk.text_strong),
corner_radius: CornerRadius::same(6),
focus_stroke: Stroke::new(1.0, tk.accent),
let valid = size.is_finite() && size > 0.0 && size <= 4096.0;
let (rect, response) = ui.allocate_exact_size(if valid { vec2(size, size) } else { egui::Vec2::ZERO }, if valid { Sense::click() } else { Sense::hover() });
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, valid && ui.is_enabled(), selected, tooltip));
if !valid {
return response;
}
let (fill, color) = if selected || response.is_pointer_button_down_on() {
(tk.tool_active, tk.text_strong)
} else if response.hovered() {
(tk.row_hover, tk.text_strong)
} else {
(Color32::TRANSPARENT, tk.text)
};
IconButton::new(tooltip, vec2(size, size), &style)
.selected(selected)
.show(ui, |ui, rect, color| {
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color);
})
.on_hover_text(tooltip)
let radius = CornerRadius::same(6);
if fill != Color32::TRANSPARENT {
ui.painter().rect_filled(rect, radius, fill);
}
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color);
if response.has_focus() && rect.width() > 4.0 && rect.height() > 4.0 {
ui.painter().rect_stroke(rect.shrink(2.0), radius, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
response.on_hover_text(tooltip)
}
/// A flat button filled with the accent, white lettering (a dialog's main action).
+12 -38
View File
@@ -1,34 +1,20 @@
//! The menu bar as the title bar, where the desktop leaves the window frame to the app (GNOME on Wayland)
//! The window's own frame where the desktop leaves it to the app (GNOME on Wayland): which frame the runtime has, and
//! the resize zones along the window's edges. The menu bar is the title bar there (`menus::menu_bar`).
use craft_window::Button;
use craft_ui::runtime::windows::WindowHost;
use craft_window::policy::Frame;
use egui::viewport::ResizeDirection;
use egui::{Context, CursorIcon, Id, LayerId, Order, PointerButton, Rect, Sense, Ui, ViewportCommand, pos2, vec2};
use egui_phosphor::regular as icon;
use egui::{CursorIcon, Id, LayerId, Order, PointerButton, Rect, Sense, Ui, ViewportCommand, pos2, vec2};
use crate::i18n::tr;
fn label(button: Button) -> &'static str {
match button {
Button::Minimize => "Minimize",
Button::Maximize => "Maximize",
Button::Close => "Close",
}
/// Whether the app's menu bar is the window's title bar: the frame the runtime has for the window is the app's.
pub(crate) fn app_bar_is_title_bar(ctx: &egui::Context) -> bool {
!matches!(WindowHost::of(ctx).frame(), Frame::Native)
}
fn glyph(button: Button) -> &'static str {
match button {
Button::Minimize => icon::MINUS,
Button::Maximize => icon::SQUARE,
Button::Close => icon::X,
}
}
fn command(button: Button, maximized: bool) -> ViewportCommand {
match button {
Button::Minimize => ViewportCommand::Minimized(true),
Button::Maximize => ViewportCommand::Maximized(!maximized),
Button::Close => ViewportCommand::Close,
}
/// Whether the window has no frame of the system's, so the app gives it its resize edges (macOS keeps its own edges
/// under an inset title bar).
pub(crate) fn app_draws_frame(ctx: &egui::Context) -> bool {
matches!(WindowHost::of(ctx).frame(), Frame::Integrated(_))
}
const EDGE: f32 = 5.0;
@@ -70,18 +56,6 @@ pub(crate) fn resize_zones(ui: &mut Ui) {
}
}
/// Draw `buttons` in the given left-to-right order
pub(crate) fn buttons(ui: &mut Ui, ctx: &Context, buttons: &[Button]) {
for &button in buttons {
let response = crate::widgets::icon_button(ui, glyph(button), tr(label(button)), false, 18.0);
crate::widgets::name(&response, egui::Role::Button, label(button));
if response.clicked() {
let maximized = ctx.input(|input| input.viewport().maximized).unwrap_or(false);
ctx.send_viewport_cmd(command(button, maximized));
}
}
}
#[cfg(test)]
#[path = "window_controls.test.rs"]
mod tests;
+14 -12
View File
@@ -1,13 +1,5 @@
use super::*;
#[test]
fn each_button_sends_its_viewport_command() {
assert_eq!(command(Button::Minimize, false), ViewportCommand::Minimized(true));
assert_eq!(command(Button::Maximize, false), ViewportCommand::Maximized(true));
assert_eq!(command(Button::Maximize, true), ViewportCommand::Maximized(false));
assert_eq!(command(Button::Close, false), ViewportCommand::Close);
}
fn commands_after_press_at(pos: egui::Pos2) -> Vec<ViewportCommand> {
let ctx = egui::Context::default();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
@@ -43,12 +35,22 @@ fn a_press_inside_the_window_does_not_resize() {
assert!(!commands.iter().any(|command| matches!(command, ViewportCommand::BeginResize(_))), "{commands:?}");
}
/// The frame decision of a window whose bar the app draws, with the caption buttons of `layout`.
fn app_frame(layout: craft_window::Layout) -> craft_window::policy::Decision {
use craft_window::policy::{CaptionFamily, Captions, Decision};
let desktop = craft_window::desktop::Desktop { kind: craft_window::desktop::DesktopKind::Other, ssd: Some(false), gtk_theme: None, icon_theme: None };
Decision { frame: Frame::Integrated(Captions { family: CaptionFamily::Generic, layout }), overridden: Some(true), desktop }
}
#[test]
fn the_menu_bar_shows_window_buttons_only_when_the_app_draws_the_frame() {
let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
let mut labels_drawn = |layout: Option<craft_window::Layout>| {
app.window_layout = layout;
let mut labels_drawn = |frame: Option<craft_window::policy::Decision>| {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
if let Some(frame) = frame {
WindowHost::of(&ctx).set_root_frame(frame);
}
ctx.enable_accesskit();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| crate::menus::menu_bar(&mut app, ui));
output.textures_delta.clear();
@@ -59,12 +61,12 @@ fn the_menu_bar_shows_window_buttons_only_when_the_app_draws_the_frame() {
let desktop = labels_drawn(None);
assert!(!desktop.iter().any(|label| label == "Close"), "{desktop:?}");
let drawn = labels_drawn(Some(craft_window::Layout::default()));
let drawn = labels_drawn(Some(app_frame(craft_window::Layout::default())));
for button in ["Minimize", "Maximize", "Close"] {
assert!(drawn.iter().any(|label| label == button), "{button} in {drawn:?}");
}
let left = labels_drawn(Some(craft_window::Layout { left: vec![Button::Close], right: Vec::new() }));
let left = labels_drawn(Some(app_frame(craft_window::Layout { left: vec![craft_window::Button::Close], right: Vec::new() })));
assert!(left.iter().any(|label| label == "Close"), "{left:?}");
assert!(!left.iter().any(|label| label == "Minimize"), "{left:?}");
}
+1 -1
View File
@@ -8,7 +8,7 @@ mod home_modality_tests {
let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
// The icon font has to be in place for the frame that first draws Home
let mut fonts_installed = false;
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
move |ui, app: &mut MaterialCraftApp| {
if std::mem::replace(&mut fonts_installed, true) {
crate::windows::show(app, ui.ctx());
@@ -13,7 +13,7 @@ fn harness(render: bool) -> Harness<'static, MaterialCraftApp> {
let levels = app.run("graph.node.add", json!({"def": "levels", "connectFrom": {"node": source}})).unwrap()["id"].as_u64().unwrap();
app.run("graph.select", json!({"ids": [source, levels]})).unwrap();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0));
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0));
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
+1 -1
View File
@@ -10,7 +10,7 @@ fn harness(id: &'static str, render: bool) -> Harness<'static, State> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = id == "home";
app.ui.windows.export = id == "export";
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
move |ui, (app, rect): &mut State| {
+1 -1
View File
@@ -10,7 +10,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.dock.close(materialcraft_ui_egui::docking::Panel::Library);
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
let mut harness = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+4 -2
View File
@@ -25,7 +25,7 @@ fn harness(render: bool) -> Harness<'static, MaterialCraftApp> {
}
fn app_harness(app: MaterialCraftApp, render: bool) -> Harness<'static, MaterialCraftApp> {
let builder = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
@@ -153,7 +153,9 @@ fn close_with_focused_graph_text(native_close: bool) {
if native_close {
let mut input = egui::RawInput::default();
input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().events.push(egui::ViewportEvent::Close);
let mut output = egui::Context::default().run_ui(input, |ui| materialcraft_ui_egui::unsaved::handle_close(harness.state_mut(), ui.ctx()));
let ctx = egui::Context::default();
materialcraft_ui_egui::framework::install_headless(&ctx);
let mut output = ctx.run_ui(input, |ui| harness.state_mut().close_path(ui.ctx()));
// This close-event frame has no renderer to consume texture updates
output.textures_delta.clear();
+1 -1
View File
@@ -10,7 +10,7 @@ fn harness(scale: f32, render: bool) -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
app.ui.windows.preferences = true;
app.ui.prefs.ui_scale = scale;
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
+1 -1
View File
@@ -9,7 +9,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = false;
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
let mut harness = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+1 -1
View File
@@ -9,7 +9,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = false;
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
let mut harness = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+1 -1
View File
@@ -9,7 +9,7 @@ use serde_json::json;
fn harness(app: MaterialCraftApp) -> Harness<'static, MaterialCraftApp> {
// Short steps keep two clicks within the double-click delay
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(0.05).build_ui_state(
let mut harness = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(0.05).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+2 -2
View File
@@ -51,7 +51,7 @@ fn toggle(h: &mut Harness<'static, MaterialCraftApp>) {
#[test]
fn display_toggle_updates_the_session_and_rerenders_the_normal_map() {
let mut h = Harness::builder().with_size(vec2(1400.0, 860.0)).build_ui_state(
let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1400.0, 860.0)).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
@@ -78,7 +78,7 @@ fn display_toggle_updates_the_session_and_rerenders_the_normal_map() {
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn normal_convention_snapshot() {
let mut harness = Harness::builder().with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state(
let mut harness = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+2 -2
View File
@@ -13,7 +13,7 @@ fn harness(render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) {
app.run("file.new", json!({"template":"empty"})).unwrap();
let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap());
app.session.reset_history();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
@@ -51,7 +51,7 @@ fn graph_name_typed_across_frames_commits_on_focus_loss() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.run("file.new", json!({"template":"empty"})).unwrap();
app.session.reset_history();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
@@ -10,7 +10,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = false;
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
let mut harness = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
@@ -12,7 +12,7 @@ fn harness(preview: u32, render: bool) -> (Harness<'static, MaterialCraftApp>, N
let id = NodeId(app.run("graph.node.add", json!({"def":"uniform"})).unwrap()["id"].as_u64().unwrap());
app.apply_prefs();
app.session.cook();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
+1 -1
View File
@@ -6,7 +6,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState};
fn harness() -> Harness<'static, MaterialCraftApp> {
let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if std::env::var_os("MC_SNAPSHOT_DIR").is_some() { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
@@ -18,7 +18,7 @@ fn harness(ppp: f32, render: bool, definition: &str) -> (Harness<'static, Materi
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let id = NodeId(app.run("graph.node.add", json!({"def":definition})).unwrap()["id"].as_u64().unwrap());
app.session.reset_history();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
@@ -85,7 +85,7 @@ fn fractional_parameter_values_remain_reachable() {
#[test]
fn bar_slider_drag_reaches_exact_round_values() {
let mut h = Harness::builder().with_size(vec2(800.0, 400.0)).with_pixels_per_point(1.0).build_ui_state(
let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(800.0, 400.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, value: &mut f32| {
widgets::bar_slider(ui, "Brightness", value, 0.0..=1.0, 128.0);
},
@@ -112,7 +112,7 @@ fn bar_slider_drag_reaches_exact_round_values() {
#[test]
fn bar_slider_drag_preserves_fractional_values() {
let mut h = Harness::builder().with_size(vec2(800.0, 400.0)).with_pixels_per_point(1.0).build_ui_state(
let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(800.0, 400.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, value: &mut f32| {
widgets::bar_slider(ui, "Brightness", value, 0.0..=1.0, 128.0);
},
+1 -1
View File
@@ -11,7 +11,7 @@ fn unsaved_dialog_snapshot_and_cancel() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.session.modified = true;
unsaved::guard(&mut app, Guarded::Menu { id: "ui.closeAll".into() });
let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_ui_state(
let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 960.0)).wgpu().build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+1 -1
View File
@@ -14,7 +14,7 @@ fn harness(w: f32, h: f32) -> Harness<'static, MaterialCraftApp> {
app.session.view3d.override_resolution = true;
app.session.view3d.viewport_resolution = true;
app.session.view3d.render_scale = 25;
Harness::builder().with_size(vec2(w, h)).with_pixels_per_point(1.0).build_ui_state(
Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(w, h)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
+1 -1
View File
@@ -54,7 +54,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(app: MaterialCraftApp, w: f32, h: f32) -> Harness<'static, MaterialCraftApp> {
Harness::builder().with_size(vec2(w, h)).with_pixels_per_point(1.0).wgpu().build_ui_state(
Harness::builder().with_context_setup(materialcraft_ui_egui::framework::install_headless).with_size(vec2(w, h)).with_pixels_per_point(1.0).wgpu().build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);