Merge pull request #318 from aiongg/minimal-port-next

MaterialCraft: move to craft-libs next (minimal port)
This commit is contained in:
aiongg authored and GitHub committed 2026-11-25 23:09:00 -05:00
commit 665e5fa286
69 files changed
+2757 -601

No files matched your search

Generated
+1286 -104
View File
File diff suppressed because it is too large. Load diff
+35 -31
View File
@@ -39,19 +39,19 @@ license = "MIT OR Apache-2.0"
[workspace.dependencies]
# Standard Base64 output; strict SBS decoding remains app-local
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", version = "0.1.0" }
# Read 3D meshes through craft-mesh; keep mesh processing app-local
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false, features = ["obj", "gltf"] }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", default-features = false, features = ["obj", "gltf"] }
# Shared XML escaping and bounded XML parsing; SBS model and serialization policy stay app-local
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Shared SBS package/schema parsing, sniffing, embedded codec, and envelope writing (storytold/craft-libs#2496)
craft-sbs = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "380a2f79f6a195c090a5372e819cbcda2b703c09" }
craft-sbs = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Shared bounded ZIP archive reader and deterministic writer (storytold/craft-libs#2411)
craft-zip = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "512a1b8e8b59a7b325e7f69f6131aa8628470288" }
craft-zip = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Bound SVG parsing and drawing through craft-svg
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["tree-render"] }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["tree-render"] }
# Shared raster image codecs
craft-image-codecs = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# internal
materialcraft-core = { path = "crates/core" }
materialcraft-geom = { path = "crates/geom" }
@@ -91,43 +91,47 @@ getrandom = "0.3"
# Shared Craft egui components from storytold/craft-libs
# MIT OR Apache-2.0
egui_kittest = "0.37"
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# MCMAT v3 uses its merged archive revision and the matching ZIP crate
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["egui"] }
# Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-platform = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-platform = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["ui"] }
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Who draws the window frame, and an app-drawn strip as the title bar: storytold/craft-libs, MIT OR Apache-2.0
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["ui"] }
# Release checks and self-updates for the desktop app: storytold/craft-libs, MIT OR Apache-2.0
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["ui"] }
# Atomic persistence, at the suite's current revision
craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-png = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c42c34bfa127b095fb0a8d5ccaba0c168c254062" }
craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-png = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Parse the optional shared font catalog at build time; the font repository is not a dependency
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
# Float image planes and texture sampling for node cooking: storytold/craft-libs, MIT OR Apache-2.0
craft-texture = { git = "https://github.com/storytold/craft-libs", rev = "5a913a42abc9fed0cfc588114788e400229f5108", features = ["parallel"] }
craft-texture = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["parallel"] }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
# egui-phosphor has no release for egui 0.37 (vendor/egui-phosphor/VENDORED.md).
egui-phosphor = { path = "vendor/egui-phosphor" }
+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
+1 -1
View File
@@ -26,7 +26,7 @@ rfd = { workspace = true }
craft-atomic = { workspace = true }
# The window frame's choice applies before the window exists.
craft-window = { workspace = true, features = ["egui"] }
craft-window = { workspace = true, features = ["ui"] }
# The Windows update helper is a copy of this program started with `--finish-update`.
[target.'cfg(windows)'.dependencies]
+4 -4
View File
@@ -239,10 +239,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(os_window::name_for(os_window::identity())).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE),
&window_frame,
&window_frame.frame,
);
// Stable keeps eframe's implicit app id, so its saved layout stays where it is; a Nightly
// carries its own id so docks, compositor rules and the taskbar list it separately.
@@ -282,6 +282,7 @@ fn main() {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
materialcraft_ui_egui::framework::install(&cc.egui_ctx, window_frame)?;
let mut app = MaterialCraftApp::new(cc, session);
app.build_version = BUILT_VERSION.to_owned();
app.build_commit = BUILD_SHA.to_owned();
@@ -291,7 +292,6 @@ fn main() {
app.at_exit = Some(Box::new(move || {
nightly_session::finish_once(&hook_session, hook_notice.load(std::sync::atomic::Ordering::Relaxed));
}));
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, os_window::name_for(os_window::identity())) {
+5 -4
View File
@@ -14,6 +14,11 @@ materialcraft-render = { workspace = true }
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 +35,6 @@ sha2 = { workspace = true }
sys-locale = "0.3"
craft-update = { workspace = true }
craft-dialogs = { workspace = true }
craft-quit = { workspace = true, features = ["egui"] }
craft-window = { workspace = true, features = ["egui"] }
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
[target.'cfg(target_arch = "wasm32")'.dependencies]
+183 -128
View File
@@ -1,22 +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_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement};
use craft_ui::layout::{SplitAxis, SplitSize};
use egui::{Id, Margin, RichText, Ui, vec2};
use std::sync::Arc;
use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions, SplitSize};
use craft_behavior::flow::Axis;
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 {
@@ -63,68 +67,62 @@ 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.
pub type Workspace = craft_ui::docking::Workspace<Panel>;
/// 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: SplitAxis, 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) }
fn split(axis: Axis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
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
/// middle; properties on the right. Console and history are closed and open floating.
pub fn default_workspace() -> Workspace {
use Panel::*;
let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library]));
let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d]));
let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views);
let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 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: Placement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
};
workspace.hidden.push((panel, location));
}
}
workspace
let left = split(Axis::Y, 0.36, tabs(&[Explorer]), tabs(&[Library]));
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 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;
@@ -141,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)) => {
@@ -156,7 +154,7 @@ 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,
@@ -207,12 +205,18 @@ 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
}
/// Puts the default layout back. It replaces the workspace instead of editing it, which ends a drag in progress.
pub fn reset(&mut self) {
self.workspace.replace(default_workspace());
self.raise = None;
}
/// Hide a visible panel, otherwise bring it up.
@@ -221,7 +225,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}");
}
}
@@ -230,7 +234,7 @@ impl Dock {
/// front.
pub fn focus(&mut self, p: Panel) {
let mut next = self.workspace.clone();
match next.set_visible(p, true, None, permissions) {
match next.set_visible(p, true, None, false, permissions) {
Ok(()) if validate(&next).is_ok() => {
self.workspace = next;
self.raise = Some(p);
@@ -244,7 +248,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}"),
@@ -252,73 +256,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
}
/// 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);
let raise = app.ui.dock.raise.take();
// 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 };
let mut area = DockArea::new("Panels", Bind::given(Arc::clone(&shown)), &specs, &mut panels, config);
if let Some(panel) = raise {
area = area.raise(panel);
}
area.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),
_ => {
@@ -334,31 +382,14 @@ 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.
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::graph::show(self.app, ui);
Some(rect.height())
}
}
@@ -371,7 +402,7 @@ 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");
}
}
@@ -379,18 +410,30 @@ mod tests {
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")))
};
let modal = |app: &mut crate::MaterialCraftApp| app.frame_input(&ctx, Default::default(), 1.0).app_modal;
assert_eq!(frame(&mut app), Some(false));
assert_eq!(modal(&mut app), None);
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");
assert_eq!(modal(&mut app), Some(egui::ViewportId::ROOT), "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");
assert_eq!(modal(&mut app), None, "the Shortcuts list does not block");
}
#[test]
fn a_focused_panel_is_raised_for_one_frame() {
let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.ui.dock.focus(Panel::Properties);
assert_eq!(app.ui.dock.raise, Some(Panel::Properties));
// The first frame only installs the fonts
for _ in 0..2 {
ctx.run_ui(egui::RawInput::default(), |ui| app.draw(ui)).textures_delta.clear();
}
assert_eq!(app.ui.dock.raise, None);
}
#[test]
@@ -401,6 +444,18 @@ mod tests {
assert_eq!(back, dock);
}
#[test]
fn only_a_reset_replaces_the_workspace() {
let mut dock = Dock::default();
let start = dock.workspace().generation();
dock.focus(Panel::Console);
dock.close(Panel::Library);
assert_eq!(dock.workspace().generation(), start);
dock.reset();
assert_ne!(dock.workspace().generation(), start);
assert_eq!(dock, Dock::default());
}
#[test]
fn the_graph_stays_put_and_panels_come_back() {
let mut dock = Dock::default();
+2 -2
View File
@@ -158,7 +158,7 @@ pub(super) fn rename_dialog(app: &mut MaterialCraftApp, ctx: &egui::Context) {
.show(ctx, |ui| {
let response = ui.text_edit_singleline(&mut name);
crate::widgets::name(&response, egui::Role::TextInput, "Name");
if !ctx.memory(|memory| memory.has_focus(response.id)) && !ctx.egui_wants_keyboard_input() {
if !ctx.memory(|memory| memory.has_focus(response.id)) && !crate::framework::widget_has_keyboard(ctx) {
response.request_focus();
}
accept |= response.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter));
@@ -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;
}
+213
View File
@@ -0,0 +1,213 @@
//! 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's canvas is declared to the runtime with [`host_canvas`], which keeps the edit
//! chords and the clipboard events in egui's input for MaterialCraft's shortcuts, and Tab while it opens the node search.
//! The focused canvas leaves the keyboard to the shortcuts ([`widget_has_keyboard`]).
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::{Chord, Key, Overrides};
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, NavCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{self, EditSet, FocusTarget, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::runtime::overlay::{self, OpenFilter};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::policy::Decision;
use craft_window::system::WindowSystem;
use crate::MaterialCraftApp;
use crate::shell::modality::Modality;
use egui::ViewportId;
/// 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 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(crate::os_window::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 and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "materialcraft", name: "MaterialCraft", version: materialcraft_engine::VERSION })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.materialcraft.png"))
.build(),
)
}
/// Preferences > Shortcuts assigns any chord to a node, so the runtime's F6 and Shift+F6 pane moves are unbound.
/// Overrides are keyed by command id, which the command set gives.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
for id in [NavCommand::NextPane.id(), NavCommand::PreviousPane.id()] {
overrides.insert(id, Vec::new());
}
Arc::new(overrides)
})
.clone()
}
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(ctx, output, scale));
}
/// The root values of this frame. MaterialCraft registers no commands with the runtime (it unbinds the framework's
/// pane moves, [`command_overrides`]) and lets it toggle no chrome, so the output carries nothing it acts on. While one of MaterialCraft's own egui modals shows in the
/// root window, the runtime blocks the panels floated into windows of their own.
pub(crate) fn frame_input(&mut self, ctx: &egui::Context, _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);
let app_modal = Modality::capture(self, ctx).is_blocked().then_some(ViewportId::ROOT);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)).app_modal(app_modal)
}
/// 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 });
}
}
/// The graph editor's canvas widget, the window's document canvas. The material, function and FX-Map editors share it,
/// so it keeps the focus when one replaces another.
pub fn canvas_id() -> egui::Id {
egui::Id::unique("materialcraft-graph-canvas")
}
/// Declares the graph editor's canvas, drawn in this pass, as the window's document canvas. With nothing or the canvas
/// focused, the edit chords and the clipboard events stay in egui's input for MaterialCraft's shortcuts. With
/// `opens_search` the focused canvas claims a bare Tab, which opens its node search; Shift+Tab always moves on from
/// it, and Tab does otherwise.
pub(crate) fn host_canvas(ctx: &egui::Context, opens_search: bool) {
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL);
const TAB: [Chord; 1] = [Chord::plain(Key::Tab)];
const SEARCH_KEYS: KeyUse = KEYS.with_claims(&TAB);
// The claim would hold with nothing focused too, where a bare Tab moves the focus into the window
let claims_tab = opens_search && ctx.memory(|memory| memory.has_focus(canvas_id()));
focus::host_canvas(ctx, canvas_id(), if claims_tab { SEARCH_KEYS } else { KEYS });
}
/// Gives the canvas the keyboard focus, with the arrows and Escape its own.
pub(crate) fn focus_canvas(ctx: &egui::Context) {
focus::request(ctx, FocusTarget::Id(canvas_id()));
}
/// The widget that has the keyboard, the canvas left out: the focused canvas leaves the keyboard to MaterialCraft's
/// shortcuts, as with nothing focused.
pub(crate) fn focused_widget(ctx: &egui::Context) -> Option<egui::Id> {
ctx.memory(|memory| memory.focused()).filter(|focused| *focused != canvas_id())
}
/// Whether a widget other than the canvas has the keyboard.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
focused_widget(ctx).is_some()
}
/// Whether a dialog, MaterialCraft's, egui's or the framework's, the home screen, or an egui menu or popup is up.
pub(crate) fn overlay_open(app: &MaterialCraftApp, ctx: &egui::Context) -> bool {
app.ui.windows.home || Modality::capture(app, ctx).is_blocked() || egui::Popup::is_any_open(ctx) || overlay::any_open(ctx, OpenFilter::Modal)
}
/// 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)
}
/// Releases the keyboard from a framework widget (a dock tab row, a panel's drag band) when nothing took the Escape
/// pressed on it, as egui does for MaterialCraft's own widgets. Called last in the UI: what is drawn before it takes its
/// Escape first. A framework modal keeps the focus in it, and a text field its own.
pub(crate) fn release_keyboard(ctx: &egui::Context) {
if let Some(focused) = focused_widget(ctx)
&& !ctx.text_edit_focused()
&& !overlay::any_open(ctx, OpenFilter::Modal)
&& take_window_cancel(ctx)
{
ctx.memory_mut(|memory| memory.surrender_focus(focused));
}
}
/// 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
}
+2
View File
@@ -39,6 +39,8 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui
super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry, on_annotation);
let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom };
super::search::show(app, editor, ui, &camera);
let over_canvas = crate::graph::canvas_focus::under_pointer(ui, &frame.response, frame.response.hovered(), super::search::area());
crate::graph::canvas_focus::settle(app, ui, over_canvas && editor.search.is_none());
frame.geometry.publish(&mut app.graph, frame.response.rect);
if editor.drag.is_none() {
let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom };
+4 -3
View File
@@ -137,7 +137,8 @@ pub(super) fn handle(
}
}
if response.clicked() && !on_wire && !ui.input(|input| input.modifiers.alt) {
// A click of the pointer: Enter and Space on the focused canvas make it `clicked` too
if response.clicked_by(egui::PointerButton::Primary) && !on_wire && !ui.input(|input| input.modifiers.alt) {
crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers));
crate::graph::node_selection::select(&mut editor.selected_wires, None, ui.input(|input| input.modifiers));
}
@@ -189,7 +190,7 @@ pub(super) fn handle(
// Space or Tab over the canvas, or a double-click on empty canvas, searches for a node to add
// Tab moves focus between widgets, so it waits only for text fields and focus held before this frame
let space = !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space));
let space = !crate::framework::widget_has_keyboard(ui.ctx()) && ui.input(|input| input.key_pressed(egui::Key::Space));
let tab = app.ui.prefs.tab_opens_node_search
&& !app.graph.keyboard_was_focused
&& !ui.ctx().text_edit_focused()
@@ -205,7 +206,7 @@ pub(super) fn handle(
editor.menu_at = camera.to_graph(pointer_position);
editor.search = Some(FunctionSearch::at(editor.menu_at, None));
}
response.context_menu(|ui| {
crate::graph::canvas_focus::context_menu(response, |ui| {
super::context_menu::show(app, editor, ui, None);
});
}
+2 -1
View File
@@ -7,7 +7,8 @@ use egui::{Align2, Color32, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2};
use std::collections::{BTreeMap, BTreeSet};
pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option<FunctionCanvas> {
let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag());
let size = ui.available_size().max(vec2(200.0, 200.0));
let (canvas_bounds, response) = crate::graph::canvas_focus::allocate(app, ui, size);
app.graph.view = canvas_bounds;
let graph = editor.current(app)?;
let snap = app.ui.prefs.snap_to_grid;
+13 -4
View File
@@ -85,12 +85,17 @@ pub(crate) fn pick(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, sear
editor.inspected_node = Some(id);
}
/// The search popup's area
pub(super) fn area() -> egui::Id {
egui::Id::unique("function-node-search")
}
pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui, camera: &GraphCamera) {
let blocked = crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked();
let Some(mut search) = editor.search.take() else { return };
let tokens = Tokens::get(ui.ctx());
let area = egui::Id::unique("function-node-search");
let area = area();
let mut close = false;
let mut chosen = None;
egui::Area::new(area).fixed_pos(camera.to_screen(search.at)).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
@@ -115,10 +120,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));
}
@@ -154,7 +160,10 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui:
&& ui.ctx().pointer_interact_pos().is_some_and(|pointer| !ui.ctx().layer_id_at(pointer).is_some_and(|layer| layer.id == area));
if let Some(candidate) = chosen.filter(|_| !blocked) {
pick(app, editor, &search, &candidate);
} else if !close && !clicked_outside {
crate::framework::focus_canvas(ui.ctx());
} else if close {
crate::framework::focus_canvas(ui.ctx());
} else if !clicked_outside {
editor.search = Some(search);
}
}
+4 -1
View File
@@ -51,7 +51,8 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let theme = Tokens::get(ui.ctx());
let context = ui.ctx().clone();
let (rect, response) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag());
let size = ui.available_size();
let (rect, response) = super::canvas_focus::allocate(app, ui, size);
crate::widgets::name(&response, egui::Role::Canvas, "Node graph");
app.graph.view = rect;
if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) {
@@ -350,6 +351,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
super::search::show(app, ui, &camera);
let over_canvas = super::canvas_focus::under_pointer(ui, &response, ui.rect_contains_pointer(rect), super::search::area());
super::canvas_focus::settle(app, ui, over_canvas && app.graph.search.is_none());
let (failed, placeholders) = app.session.cook_failures();
let mut at = rect.right_bottom() - vec2(8.0, 8.0);
if !failed.is_empty() {
+86
View File
@@ -0,0 +1,86 @@
//! The graph editor's canvas widget and its keyboard focus
use crate::MaterialCraftApp;
use crate::framework::{canvas_id, focus_canvas, focused_widget, host_canvas, overlay_open};
use crate::shell::modality::Modality;
use egui::{Id, PointerButton, Popup, Rect, Response, Sense, SetOpenCommand, Ui, Vec2};
/// The passes a graph that opens asks for the focus in: the widget that opened it keeps egui's focus for up to two
/// passes, the one it was last drawn in and the one after it went away.
const FOCUS_PASSES: u8 = 3;
/// Allocate and draw the canvas widget: every editor (material, function, FX-Map) draws the one that has the focus
pub(crate) fn allocate(app: &MaterialCraftApp, ui: &mut Ui, size: Vec2) -> (Rect, Response) {
let (_, rect) = ui.allocate_space(size);
let response = ui.interact(rect, canvas_id(), Sense::click_and_drag());
// Declared before the widgets on the canvas, for its place in Tab order
host_canvas(ui.ctx(), false);
focus_on_press(app, ui, &response);
(rect, response)
}
/// A press anywhere on the canvas gives it the keyboard focus. Real presses only: with the canvas focused, egui makes
/// Enter and Space clicks of it.
fn focus_on_press(app: &MaterialCraftApp, ui: &Ui, canvas: &Response) {
let ctx = ui.ctx();
if !ui.input(|input| input.pointer.any_pressed()) || !ui.rect_contains_pointer(canvas.rect) || Modality::capture(app, ctx).is_blocked() {
return;
}
// A press in the value being edited on a node stays there
let in_editor = ctx.text_edit_focused() && focused_widget(ctx).and_then(|id| ctx.read_response(id)).is_some_and(|field| field.is_pointer_button_down_on());
if !in_editor {
focus_canvas(ctx);
}
}
/// The canvas's context menu. Real clicks only, as for [`focus_on_press`]: Enter picks in the Add node menu and must not
/// close it.
pub(crate) fn context_menu(canvas: &Response, contents: impl FnOnce(&mut Ui)) {
let open = if canvas.secondary_clicked() {
Some(SetOpenCommand::Bool(true))
} else if canvas.clicked_by(PointerButton::Primary) {
Some(SetOpenCommand::Bool(false))
} else {
None
};
Popup::context_menu(canvas).open_memory(open).show(contents);
}
/// Whether the pointer is over the canvas: `hovered`, or over the node search `search`, which still covers the canvas in
/// the passes after it closes
pub(crate) fn under_pointer(ui: &Ui, canvas: &Response, hovered: bool, search: Id) -> bool {
let ctx = ui.ctx();
hovered
|| ctx.pointer_interact_pos().is_some_and(|pointer| canvas.rect.contains(pointer) && ctx.layer_id_at(pointer).is_some_and(|layer| layer.id == search))
}
/// Settle the focus and Tab once the canvas has handled its input. A graph that opens or becomes active asks for the
/// focus, and so does the canvas while nothing is focused and Tab opens its node search (`opens_search`). It waits for a
/// dialog, menu or popup to close, and leaves the focus with a text field and, after [`FOCUS_PASSES`], with a widget
/// of another window.
pub(crate) fn settle(app: &mut MaterialCraftApp, ui: &Ui, opens_search: bool) {
let ctx = ui.ctx();
let opens_search = opens_search && app.ui.prefs.tab_opens_node_search && !Modality::capture(app, ctx).is_blocked();
let shown = Some((app.session.document_id, app.session.graph, app.graph.annotation_target.clone()));
if app.graph.shown != shown {
app.graph.shown = shown;
app.graph.focus_passes = FOCUS_PASSES;
}
let focused = ctx.memory(|memory| memory.focused());
let unfocused = opens_search && focused.is_none() && !ui.input(|input| input.pointer.any_down());
if (app.graph.focus_passes > 0 || unfocused) && !overlay_open(app, ctx) {
let same_window = focused.is_none_or(|id| ctx.read_response(id).is_some_and(|widget| widget.layer_id == ui.layer_id()));
if ctx.text_edit_focused() {
app.graph.focus_passes = 0;
} else if same_window {
app.graph.focus_passes = 0;
focus_canvas(ctx);
} else {
app.graph.focus_passes = app.graph.focus_passes.saturating_sub(1);
ctx.request_repaint();
}
}
host_canvas(ctx, opens_search);
}
+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);
}
@@ -103,6 +103,21 @@ fn space_tab_and_double_click_open_the_search_and_enter_adds() {
assert!(nodes.iter().any(|(_, op, _)| op == "add"));
}
#[test]
fn space_on_the_focused_canvas_keeps_the_selection() {
let (mut frames, constant) = function_canvas();
let at = empty(&frames);
frames.click(at, Modifiers::NONE);
let selection = vec![materialcraft_engine::core::NodeId(u64::from(constant))];
frames.app.session.selection = selection.clone();
frames.run(Vec::new(), Modifiers::NONE);
assert_eq!(frames.ctx.memory(|memory| memory.focused()), Some(crate::framework::canvas_id()));
frames.run(vec![press(Key::Space)], Modifiers::NONE);
assert!(search(&frames).is_some());
assert_eq!(frames.app.session.selection, selection, "egui's click for Space selects nothing");
}
#[test]
fn wires_dropped_on_empty_canvas_search_and_connect_the_new_node() {
let (mut frames, constant) = function_canvas();
+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())
}
+1 -1
View File
@@ -58,7 +58,7 @@ impl GraphCamera {
pub(crate) fn frame_key(ui: &Ui, view: Rect) -> bool {
ui.rect_contains_pointer(view)
&& !ui.ctx().egui_wants_keyboard_input()
&& !crate::framework::widget_has_keyboard(ui.ctx())
&& ui.input(|input| input.key_pressed(egui::Key::F) && input.modifiers.is_none())
}
}
+6
View File
@@ -5,6 +5,10 @@ use materialcraft_engine::core::NodeId;
pub struct GraphView {
pub(crate) inspected_node: Option<NodeId>,
pub(crate) keyboard_was_focused: bool,
/// The document, graph and nested editor shown last frame
pub(super) shown: Option<(u64, usize, materialcraft_engine::AnnotationTarget)>,
/// The passes left in which the canvas asks for the keyboard focus, after what is shown changed
pub(super) focus_passes: u8,
pub(super) thumbnails_cleared: bool,
pub(super) drag: Option<GraphDrag>,
pub(super) search: Option<NodeSearch>,
@@ -56,6 +60,8 @@ impl Default for GraphView {
GraphView {
inspected_node: None,
keyboard_was_focused: false,
shown: None,
focus_passes: 0,
thumbnails_cleared: false,
drag: None,
search: None,
+2 -2
View File
@@ -239,7 +239,7 @@ pub(super) fn handle(
}
let at = app.graph.menu_at;
canvas.context_menu(|ui| match app.graph.menu_wire.clone() {
super::canvas_focus::context_menu(canvas, |ui| match app.graph.menu_wire.clone() {
Some(wire) => wire_menu(app, ui, wire, at),
None => super::context_menu::show(app, ui, at, None),
});
@@ -277,7 +277,7 @@ pub(super) fn handle(
&& app.graph.search.is_none()
&& !crate::shell::modality::Modality::capture(app, &context).is_blocked()
{
let typing = context.egui_wants_keyboard_input();
let typing = crate::framework::widget_has_keyboard(&context);
let platform = craft_keymap::egui::platform(&context);
if !typing && let Some(entry) = context.input(|input| crate::node_shortcuts::pressed(&app.ui.prefs.node_shortcuts, input, platform)) {
let under_pointer = camera.to_graph(position);
+1
View File
@@ -3,6 +3,7 @@ pub(crate) mod add_node_menu;
pub(crate) mod annotation_canvas;
pub(crate) mod annotation_input;
pub(crate) mod canvas;
pub(crate) mod canvas_focus;
mod context_menu;
pub(crate) mod frame_hit;
#[cfg(test)]
+14 -4
View File
@@ -5,6 +5,11 @@ use egui_phosphor::regular as icon;
use materialcraft_engine::core::NodeId;
use serde_json::json;
/// The search popup's area
pub(super) fn area() -> egui::Id {
egui::Id::unique("node-search")
}
pub(super) fn open_search(app: &mut MaterialCraftApp, ctx: &egui::Context, at: Pos2, connect: Option<(NodeId, String)>) {
if crate::shell::modality::Modality::capture(app, ctx).is_blocked() {
return;
@@ -45,7 +50,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) {
let screen = cam.to_screen(s.at);
let mut close = false;
let mut pick: Option<&'static str> = None;
egui::Area::new(egui::Id::unique("node-search")).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
egui::Area::new(area()).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_width(260.0);
if blocked {
@@ -71,10 +76,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));
}
@@ -109,7 +115,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) {
});
let clicked_out = !blocked
&& ui.input(|i| i.pointer.any_pressed())
&& ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == egui::Id::unique("node-search")));
&& ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == area()));
if let Some(def) = pick.filter(|_| !crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked()) {
let s = app.graph.search.take();
if let Some(s) = s {
@@ -124,7 +130,11 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) {
app.run("graph.connect", json!({"from": id.0, "fromPort": output, "to": to.0, "toPort": port}));
}
}
crate::framework::focus_canvas(ui.ctx());
} else if close || clicked_out {
app.graph.search = None;
if close {
crate::framework::focus_canvas(ui.ctx());
}
}
}
+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
@@ -9,6 +9,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;
@@ -28,6 +29,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;
+40 -25
View File
@@ -58,18 +58,23 @@ 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
pub fonts: fonts::UiFonts,
/// The icon font is installed (it takes effect on the frame after `set_fonts`)
fonts_ready: bool,
/// The frame that only installed the fonts: egui runs it again once they are loaded.
fonts_frame: Option<u64>,
ui_gesture_active: bool,
/// The version this build names itself with: the Launcher's feed identity for a Nightly.
pub build_version: String,
@@ -143,15 +148,15 @@ 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,
fonts_frame: None,
ui_gesture_active: false,
build_version: materialcraft_engine::VERSION.to_owned(),
build_commit: String::new(),
@@ -468,18 +473,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));
@@ -489,13 +495,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 {
@@ -503,6 +502,10 @@ impl MaterialCraftApp {
ctx.request_repaint();
return;
}
if self.reruns_fonts_frame(ctx) {
ctx.request_repaint();
return;
}
i18n::set_language(&self.ui.prefs.language);
self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences);
@@ -527,7 +530,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"))]
@@ -562,19 +565,29 @@ impl MaterialCraftApp {
}
}
/// Whether this pass is egui's rerun of the frame that only installed the fonts
fn reruns_fonts_frame(&mut self, ctx: &egui::Context) -> bool {
self.fonts_frame = self.fonts_frame.filter(|frame| *frame == ctx.cumulative_frame_nr());
self.fonts_frame.is_some()
}
/// Draw the whole window into `ui`
pub fn draw(&mut self, ui: &mut egui::Ui) {
crate::annotation::activate(self, crate::annotation::target(self));
let ctx = ui.ctx().clone();
if !self.fonts_ready {
self.fonts_ready = true;
self.fonts_frame = Some(ctx.cumulative_frame_nr());
return;
}
if self.reruns_fonts_frame(&ctx) {
return;
}
let ctx = ui.ctx().clone();
let t0 = now_ms();
// Tab can focus a menu or toolbar button while drawing; preserve keyboard ownership
self.graph.keyboard_was_focused = ctx.egui_wants_keyboard_input();
self.graph.keyboard_was_focused = crate::framework::widget_has_keyboard(&ctx);
menus::menu_bar(self, ui);
if self.ui.prefs.show_toolbar {
toolbar::main_toolbar(self, ui);
@@ -583,12 +596,14 @@ 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);
crate::framework::release_keyboard(&ctx);
#[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);
}
let gesture_active = ctx.input(|input| input.pointer.any_down()) || ctx.egui_wants_keyboard_input();
let gesture_active = ctx.input(|input| input.pointer.any_down()) || crate::framework::widget_has_keyboard(&ctx);
if !gesture_active && (self.ui_gesture_active || ctx.input(|input| input.pointer.any_released())) {
self.session.finish_edit();
}
@@ -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();
@@ -103,7 +104,8 @@ mod close_order_tests {
let mut clean = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
clean.fonts_ready = true;
clean.session.modified = false;
assert!(!close_frame(&mut clean), "nothing to hold: the hook sees a close to take over");
// Only the app's decision: a close that goes ahead ends in the platform's quit, which macOS answers by canceling it.
assert!(!crate::unsaved::close_requested(&mut clean), "nothing to hold: the hook sees a close to take over");
}
}
+82 -63
View File
@@ -1,6 +1,6 @@
//! Menu actions and shortcuts share stable command ids
use craft_keymap::{Active, Bindable, Binding, Chord, Keymap, Platform, Scope, Scopes};
use craft_keymap::{Binding, Chord, CommandDef, Keymap, Platform, Scope, Scopes};
use egui::class::HasClasses as _;
use serde_json::Value;
@@ -251,7 +251,7 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
"ui.preferences" => app.ui.windows.preferences = true,
"ui.view.graph" => {}
"ui.resetLayout" => app.ui.dock = crate::docking::Dock::default(),
"ui.resetLayout" => app.ui.dock.reset(),
"ui.closeAll" => crate::unsaved::guard(app, crate::unsaved::Guarded::Menu { id: id.to_string() }),
"file.newPackage" => {
app.run("file.newPackage", serde_json::json!({}));
@@ -318,7 +318,7 @@ pub(crate) fn shortcut_table() -> Vec<(&'static str, &'static str)> {
pub(crate) fn keymap(platform: Platform) -> Keymap {
let catalog = shortcut_table()
.into_iter()
.filter_map(|(id, text)| Some(Bindable::new(id, id, Scope::app()).with_default(Binding::new(parse_shortcut(text)?))))
.filter_map(|(id, text)| Some(CommandDef::new(id, id, Scope::app()).with_default(Binding::new(parse_shortcut(text)?))))
.collect();
Keymap::new(catalog, Scopes::new(), platform)
}
@@ -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);
}
});
}
});
}
@@ -454,12 +454,21 @@ fn menu_item(app: &mut MaterialCraftApp, context: &egui::Context, ui: &mut egui:
}
}
/// Dispatch shortcuts unless a widget, popup or dialog owns the keyboard
/// Dispatch shortcuts unless a widget other than the canvas, a popup or a dialog owns the keyboard
pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if ctx.egui_wants_keyboard_input() || egui::Popup::is_any_open(ctx) {
if crate::framework::widget_has_keyboard(ctx) || egui::Popup::is_any_open(ctx) {
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) {
let held = craft_ui::runtime::keys::escape_mods(ctx).unwrap_or_default();
let modifiers = egui::Modifiers { shift: held.shift, alt: held.alt, ..Default::default() };
ctx.input_mut(|i| {
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,10 +500,16 @@ 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
// The runtime's Quit runs Ctrl+Q, in the panels' own windows and from text fields too
let runtime_quits = id == "ui.quit";
modality.allows(id)
&& !runtime_quits
&& !(label_selected && matches!(id, "edit.copy" | "edit.cut"))
&& !unavailable_clipboard_commands.contains(&id)
&& !keeps_escape
})
});
for hit in hits {
@@ -551,7 +566,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 +797,9 @@ 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 +819,9 @@ 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 +917,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 +927,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);
+3 -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
@@ -141,6 +141,7 @@ pub(crate) fn poll(app: &mut MaterialCraftApp) {
Some(path) => chosen(app, then, &path),
None => cancelled(app, then),
},
Answer::Saved { path, .. } => chosen(app, then, &path),
Answer::Cancelled | Answer::Message(_) => cancelled(app, then),
Answer::Unavailable(why) => {
app.toast(format!("{}: {why}", tr("The file dialog could not be shown")), true);
+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]
+4 -2
View File
@@ -50,13 +50,15 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let points = if slot.is_some() { geometry::wire(source.pos, pointer) } else { geometry::wire(pointer, source.pos) };
ui.painter_at(response.rect).add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR)));
}
response.context_menu(|ui| super::context_menu::show(app, &mut editor, ui));
crate::graph::canvas_focus::context_menu(&response, |ui| super::context_menu::show(app, &mut editor, ui));
crate::graph::canvas_focus::settle(app, ui, false);
editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node);
app.pattern_editor = Some(editor);
}
fn paint(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Option<PatternCanvas> {
let (bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(100.0, 100.0)), Sense::click_and_drag());
let size = ui.available_size().max(vec2(100.0, 100.0));
let (bounds, response) = crate::graph::canvas_focus::allocate(app, ui, size);
app.graph.view = bounds;
let graph = editor.current(app)?;
let selected: std::collections::BTreeSet<_> = editor.selection.iter().copied().collect();
+1 -1
View File
@@ -118,7 +118,7 @@ pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui:
}
}
if response.hovered()
&& !ui.ctx().egui_wants_keyboard_input()
&& !crate::framework::widget_has_keyboard(ui.ctx())
&& ui.input(|input| input.key_pressed(egui::Key::Space))
&& !crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked()
{
@@ -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 };
+4 -1
View File
@@ -240,10 +240,13 @@ fn digest_name(stem: &str) -> bool {
stem.len() == 64 && stem.bytes().all(|byte| byte.is_ascii_hexdigit())
}
/// craft-atomic's staging file of a cache file: `.{file}.{pid}-{n}.craft_tmp`, where `file` is the cache file's name or
/// its first part (older craft-atomic cut it to 64 characters).
fn staging_name(name: &str) -> bool {
let Some((stem, suffix)) = name.strip_prefix('.').and_then(|name| name.strip_suffix(".craft_tmp")).and_then(|name| name.split_once('.')) else {
let Some((file, suffix)) = name.strip_prefix('.').and_then(|name| name.strip_suffix(".craft_tmp")).and_then(|name| name.rsplit_once('.')) else {
return false;
};
let stem = file.split_once('.').map_or(file, |(stem, _)| stem);
digest_name(stem) && suffix.split_once('-').is_some_and(|(pid, counter)| pid.parse::<u32>().is_ok_and(|pid| pid > 0) && counter.parse::<u64>().is_ok())
}
@@ -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();
+250
View File
@@ -0,0 +1,250 @@
//! 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]);
}
}
+23 -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,18 @@ 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 };
+38 -15
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. A Nightly has no updater: the Launcher installs it.
//! the prompts that report them, as craft-update's dialogs on the app's
//! [`DialogHost`](craft_ui::dialog::DialogHost). A Nightly has no updater: the Launcher installs it.
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;
@@ -70,9 +72,9 @@ pub(crate) fn tick(app: &mut MaterialCraftApp, ctx: &egui::Context) {
rt.repaint = Some(ctx.clone());
let Some(updater) = rt.updater.as_mut() else { return };
if std::mem::take(&mut rt.check_requested) {
updater.check_now(ctx);
updater.check_now();
} else if rt.startup_check {
updater.check_at_start(ctx);
updater.check_at_start();
}
updater.tick(ctx);
}
@@ -84,25 +86,46 @@ 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) {
let Some(updater) = app.updates_rt.updater.as_mut() else { return };
// An installation, and the close for a ready update, wait until nothing is unsaved
let clean = !crate::unsaved::needs_confirmation(&app.session);
match 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)) => updater.restart_to_update(),
Some(DialogResult::Ok(CheckChoice::Update)) => {
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(_) => updater.dismiss_status(),
None => {}
}
match 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
if result_window_shows(updater.status(), updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, materialcraft_engine::VERSION).with_translator(translate).show(ctx, updater.status()) {
CheckResultResponse::None => {}
// Closing the dialog dismisses the outcome it showed
CheckResultResponse::Close => updater.dismiss_status(),
CheckResultResponse::CheckAgain => app.updates_rt.check_requested = true,
// The next `show_if` asks the window to close once nothing is unsaved
CheckResultResponse::RestartToUpdate => updater.restart_to_update(),
}
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);
// Hidden for the prompt, not dismissed: the outcome shows again after it
let _ = dialogs.take::<UpdateCheckDialog>();
}
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
}
+16 -3
View File
@@ -112,6 +112,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);
@@ -168,11 +169,17 @@ 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);
let _ = harness.get_by_label("LATER");
let _ = harness.get_by_label("Later");
assert!(harness.state().updates_rt.updater.as_ref().unwrap().prompt_open());
}
@@ -192,7 +199,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
@@ -199,7 +199,7 @@ fn stretch_for(physical: [f32; 3], pixels: [u32; 2]) -> f32 {
/// Space toggles tiling, F fits the image and C, R, G, B and A pick the channels, while the pointer is over the image
fn keys(app: &mut MaterialCraftApp, ui: &Ui, response: &Response) {
if !response.hovered() || ui.ctx().egui_wants_keyboard_input() || crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked() {
if !response.hovered() || crate::framework::widget_has_keyboard(ui.ctx()) || crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked() {
return;
}
+2 -2
View File
@@ -130,7 +130,7 @@ pub(super) fn reset_selected(app: &mut MaterialCraftApp) {
/// The keys of the view, while the pointer is over it and nothing else has the keyboard
fn keys(app: &mut MaterialCraftApp, ui: &Ui, response: &Response) {
if !response.hovered() || ui.ctx().egui_wants_keyboard_input() || crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked() {
if !response.hovered() || crate::framework::widget_has_keyboard(ui.ctx()) || crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked() {
return;
}
@@ -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:?}");
}
+11 -10
View File
@@ -8,16 +8,17 @@ 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(
move |ui, app: &mut MaterialCraftApp| {
if std::mem::replace(&mut fonts_installed, true) {
crate::windows::show(app, ui.ctx());
} else {
crate::theme::install(ui.ctx());
}
},
app,
);
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());
} else {
crate::theme::install(ui.ctx());
}
},
app,
);
let app = harness.state_mut();
app.ui.windows.home = true;
app.ui.recent.push("recent.sbs".into());
+166
View File
@@ -0,0 +1,166 @@
//! The graph canvas as a Tab stop: it keeps the focus Tab gives it, a press and an opening graph give it the focus, Tab
//! over it opens the node search, and its keys work as with nothing focused
use egui::accesskit::Role;
use egui::{Event, Id, Key, Modifiers, PointerButton, vec2};
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_ui_egui::framework::{canvas_id, install_headless};
use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus};
type AppHarness = Harness<'static, MaterialCraftApp>;
fn harness(session: materialcraft_engine::Session) -> AppHarness {
let mut h = Harness::builder().with_context_setup(install_headless).with_size(vec2(1600.0, 960.0)).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
MaterialCraftApp::headless(session, UiState::default()),
);
h.run_steps(8);
h
}
fn focused(h: &AppHarness) -> Option<Id> {
h.ctx.memory(|memory| memory.focused())
}
fn press(h: &mut AppHarness, modifiers: Modifiers, key: Key) -> Option<Id> {
h.key_press_modifiers(modifiers, key);
h.run_steps(3);
focused(h)
}
fn search_open(h: &AppHarness) -> bool {
h.query_by_label("Search nodes").is_some()
}
fn hover_canvas(h: &mut AppHarness) {
h.hover_at(h.state().graph.view.center());
h.run_steps(2);
}
#[test]
fn tab_walks_over_the_canvas_to_the_stops_after_it_and_back() {
let mut h = harness(materialcraft_engine::new_session());
let canvas = Some(canvas_id());
assert_eq!(focused(&h), canvas, "an opened graph has the keyboard");
let after = press(&mut h, Modifiers::NONE, Key::Tab);
assert!(after.is_some() && after != canvas, "Tab moves on from the canvas");
assert_eq!(press(&mut h, Modifiers::SHIFT, Key::Tab), canvas);
let before = press(&mut h, Modifiers::SHIFT, Key::Tab);
assert!(before.is_some() && before != canvas && before != after, "Shift+Tab leaves it backward");
assert_eq!(press(&mut h, Modifiers::NONE, Key::Tab), canvas, "Tab from the stop before it stops at it");
assert_eq!(press(&mut h, Modifiers::NONE, Key::Tab), after, "and reaches the stop after it");
assert!(!search_open(&h));
}
#[test]
fn tab_with_the_pointer_over_the_canvas_opens_the_search_and_shift_tab_leaves_it() {
let mut h = harness(materialcraft_engine::new_session());
let canvas = Some(canvas_id());
hover_canvas(&mut h);
let left = press(&mut h, Modifiers::SHIFT, Key::Tab);
assert!(left.is_some() && left != canvas, "Shift+Tab leaves the canvas");
assert!(!search_open(&h));
h.ctx.memory_mut(|memory| memory.surrender_focus(left.unwrap()));
h.run_steps(2);
assert_eq!(focused(&h), canvas, "with nothing focused, the canvas under the pointer takes the keyboard");
press(&mut h, Modifiers::NONE, Key::Tab);
assert!(search_open(&h), "Tab opens the search");
assert_eq!(press(&mut h, Modifiers::NONE, Key::Escape), canvas, "closing it gives the keyboard back");
assert!(!search_open(&h));
}
#[test]
fn escape_releases_the_keyboard_from_the_dock_controls_after_the_canvas() {
let mut h = harness(materialcraft_engine::new_session());
// The 3D view's tab row and its drag band
for stop in 1..=2 {
h.ctx.memory_mut(|memory| memory.request_focus(canvas_id()));
h.run_steps(2);
for _ in 0..stop {
press(&mut h, Modifiers::NONE, Key::Tab);
}
assert!(focused(&h).is_some_and(|id| id != canvas_id()), "Tab reaches stop {stop} after the canvas");
assert_eq!(press(&mut h, Modifiers::NONE, Key::Escape), None, "Escape releases stop {stop}");
}
}
#[test]
fn a_press_in_the_canvas_takes_the_keyboard_from_a_toolbar_button() {
let mut h = harness(materialcraft_engine::new_session());
h.get_by_label("Open package... (Ctrl+O)").focus();
h.run_steps(2);
press(&mut h, Modifiers::SHIFT, Key::Tab);
assert!(h.get_by_label("New graph... (Ctrl+N)").is_focused());
hover_canvas(&mut h);
assert!(h.get_by_label("New graph... (Ctrl+N)").is_focused(), "the pointer alone takes no focus from a widget");
let pos = h.state().graph.view.center();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
assert_eq!(focused(&h), Some(canvas_id()));
}
press(&mut h, Modifiers::NONE, Key::Space);
assert!(search_open(&h), "Space goes to the canvas");
assert!(!h.state().ui.windows.new_graph, "and not to the button");
}
#[test]
fn enter_in_the_canvas_menu_adds_the_node_its_letter_filters() {
let mut h = harness(materialcraft_engine::new_session());
hover_canvas(&mut h);
let pos = h.state().graph.view.center();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE });
}
h.run_steps(3);
h.get_by_label("Add node").hover();
h.run_steps(3);
assert_eq!(focused(&h), Some(canvas_id()));
press(&mut h, Modifiers::NONE, Key::L);
press(&mut h, Modifiers::NONE, Key::Enter);
assert_eq!(h.state().session.graph().unwrap().nodes.len(), 1);
assert!(h.query_by_label("Add node").is_none(), "and the menu closes");
}
#[test]
fn a_graph_created_by_keyboard_in_a_dialog_gets_the_focus() {
let mut h = harness(materialcraft_engine::sample_session());
let ctx = h.ctx.clone();
menus::invoke(h.state_mut(), &ctx, "ui.newFunctionGraph");
h.run_steps(4);
h.state_mut().ui.new_graph_package = None;
h.get(By::new().role(Role::Button).label("Create")).focus();
h.run_steps(2);
assert!(h.get(By::new().role(Role::Button).label("Create")).is_focused());
press(&mut h, Modifiers::NONE, Key::Enter);
h.run_steps(4);
assert!(h.state().session.graph().unwrap().function.is_some());
assert_eq!(focused(&h), Some(canvas_id()));
}
#[test]
fn shortcuts_run_with_the_canvas_focused() {
let mut h = harness(materialcraft_engine::sample_session());
assert_eq!(focused(&h), Some(canvas_id()));
let nodes = |h: &AppHarness| h.state().session.graph().unwrap().nodes.len();
let before = nodes(&h);
press(&mut h, Modifiers::COMMAND, Key::A);
assert_eq!(h.state().session.selection.len(), before, "Ctrl+A selects every node");
press(&mut h, Modifiers::NONE, Key::Delete);
assert_eq!(nodes(&h), 0, "Delete deletes them");
press(&mut h, Modifiers::COMMAND, Key::Z);
assert_eq!(nodes(&h), before, "Ctrl+Z brings them back");
assert_eq!(focused(&h), Some(canvas_id()));
}
@@ -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| {
+2 -1
View File
@@ -10,7 +10,8 @@ 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| {
+11 -7
View File
@@ -10,13 +10,17 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
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);
},
app,
);
harness.run_steps(6);
harness
}
+5 -2
View File
@@ -25,7 +25,8 @@ 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 +154,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();
+5 -1
View File
@@ -10,7 +10,11 @@ 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
View File
@@ -2,6 +2,7 @@
//! Keep snapshot.rs standalone; language_switching.rs needs process isolation for global locale state.
//! resize.rs isolates its bounded render wait from unrelated tests sharing the global Rayon pool.
mod canvas_focus;
mod clipboard_shortcuts;
mod dialogs;
mod export_window;
+11 -7
View File
@@ -9,13 +9,17 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
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);
},
app,
);
harness.run_steps(6);
harness
}
+11 -7
View File
@@ -9,13 +9,17 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
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);
},
app,
);
harness.run_steps(6);
harness
}
+12 -7
View File
@@ -9,13 +9,18 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
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);
},
app,
);
harness.run_steps(6);
harness
}
+9 -8
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,13 +78,14 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app(),
);
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);
},
app(),
);
settle(&mut harness, 0);
let rendered = harness.state().view3d.renders;
open_material_properties(&mut harness);
+4 -2
View File
@@ -13,7 +13,8 @@ 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 +52,8 @@ 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());
+11 -7
View File
@@ -10,13 +10,17 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
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);
},
app,
);
harness.run_steps(6);
harness
}
@@ -12,7 +12,8 @@ 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| {
+2 -1
View File
@@ -6,7 +6,8 @@ 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| {
+25 -13
View File
@@ -18,7 +18,11 @@ 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,12 +89,16 @@ 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(
|ui, value: &mut f32| {
widgets::bar_slider(ui, "Brightness", value, 0.0..=1.0, 128.0);
},
0.0f32,
);
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);
},
0.0f32,
);
h.run_steps(3);
let rect = h.get(By::new().role(egui::accesskit::Role::Slider).label("Brightness")).rect();
let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y);
@@ -112,12 +120,16 @@ 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(
|ui, value: &mut f32| {
widgets::bar_slider(ui, "Brightness", value, 0.0..=1.0, 128.0);
},
0.0f32,
);
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);
},
0.0f32,
);
h.run_steps(3);
let rect = h.get(By::new().role(egui::accesskit::Role::Slider).label("Brightness")).rect();
let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y);
+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);
+12 -7
View File
@@ -54,13 +54,18 @@ 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(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
)
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);
},
app,
)
}
/// Run frames until background work (cooks, previews) settles
+1 -1
View File
@@ -39,7 +39,7 @@ fn navigation_pin_library_drop_and_properties_in_every_canvas() {
assert_eq!(target.items(&harness.state().session).unwrap().pins.len(), 1, "{kind}");
let input = By::new().role(Role::TextInput).label("Navigation Pin description");
assert!(harness.query(input.clone()).is_some(), "{kind}");
assert!(harness.ctx.egui_wants_keyboard_input(), "new pin description must receive focus: {kind}");
assert!(harness.ctx.text_edit_focused(), "new pin description must receive focus: {kind}");
harness.event(Event::ModifiersChanged(Modifiers::COMMAND));
harness.event(Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
harness.step();