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

The runtime is installed from TextureCraft's own eframe App (framework.rs): the close question
decides in the runtime's close path, the window's Escape runs TextureCraft's Escape handlers and
the shortcut recorder, the viewport is the window's document canvas (Tab stays Hide UI), and
Ctrl+Q and F6 stay TextureCraft's. The dock is next's DockArea over the saved workspace, with the
viewport as its canvas group; the update dialogs run on a DialogHost; the strip is next's
TitleBar where the app draws the frame. The removed helpers (icon-button painter, pane split,
widget palette, shortcut dispatcher) are app-local. Every app harness installs the runtime.
This commit is contained in:
aiongg committed 2026-11-24 15:32:09 +00:00
1 parent dc1e046faa
commit a13e9a74ee
143 files changed
+1408 -1077

No files matched your search

Generated
+2 -1
View File
@@ -6010,10 +6010,11 @@ dependencies = [
"chrono",
"craft-behavior",
"craft-dialogs",
"craft-host",
"craft-i18n",
"craft-image-codecs",
"craft-keymap",
"craft-quit",
"craft-theme",
"craft-ui",
"craft-update",
"craft-usd",
+4 -2
View File
@@ -80,10 +80,12 @@ craft-update = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f7
craft-dialogs = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs).
craft-keymap = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de", features = ["egui"] }
# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs).
craft-quit = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de", features = ["ui"] }
# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs).
craft-menu = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
# The UI runtime's host: who the app is to the framework's dialogs (crates/ui-egui/src/framework.rs).
craft-host = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
# The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs).
craft-theme = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
+1
View File
@@ -58,6 +58,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
canvas,
options,
Box::new(|cc| {
texturecraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let mut app = TextureCraftApp::new(cc, session);
if let Some(rs) = &cc.wgpu_render_state {
let backend = rs.adapter.get_info().backend;
+13 -22
View File
@@ -146,13 +146,11 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std:
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default()
}
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
/// on macOS the traffic lights and AppKit's `movable` flag.
/// The app with the window chrome that needs the native window: the Windows borderless guard, and the native window
/// the framework runtime answers the hit test of.
struct Shell {
app: TextureCraftApp,
window_frame: Option<window_frame::WindowFrameFn>,
#[cfg(target_os = "macos")]
movable: Option<bool>,
}
impl eframe::App for Shell {
@@ -179,9 +177,8 @@ impl eframe::App for Shell {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
texturecraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.app.ui(ui, frame);
#[cfg(target_os = "macos")]
texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable);
}
}
@@ -235,12 +232,13 @@ fn main() {
prefs.apply_work_threads();
prefs.apply_resource_limits();
let session = initial_session(&args);
let title_bar = TitleBar::decide(prefs.system_title_bar);
let frame_decision = TitleBar::decide(prefs.system_title_bar);
let title_bar = TitleBar::of(&frame_decision.frame);
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
let viewport = title_bar.viewport(viewport);
let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport);
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) {
fatal(&e.to_string(), true);
@@ -261,19 +259,15 @@ fn main() {
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
log::warn!("the app menu could not be installed: {e}");
}
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?;
let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
let mut app = TextureCraftApp::new(cc, session);
app.title_bar = title_bar;
app.set_startup_update_check(checks_for_updates_at_start(control));
if let Some(port) = control {
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
}
Ok(Box::new(Shell {
app,
window_frame,
#[cfg(target_os = "macos")]
movable: None,
}))
Ok(Box::new(Shell { app, window_frame: frame_guard }))
}),
);
if let Err(e) = result {
@@ -406,13 +400,10 @@ mod tests {
#[test]
fn the_window_holds_the_pointer_while_the_preview_square_is_held() {
let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]));
let mut harness = builder.build_eframe(|cc| Shell {
app: TextureCraftApp::new(cc, session),
window_frame: None,
#[cfg(target_os = "macos")]
movable: None,
});
let builder = egui_kittest::Harness::builder()
.with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]))
.with_context_setup(texturecraft_ui_egui::framework::install_headless);
let mut harness = builder.build_eframe(|cc| Shell { app: TextureCraftApp::new(cc, session), window_frame: None });
harness.run_steps(4);
let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone();
harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap();
+2 -3
View File
@@ -19,7 +19,8 @@ craft-behavior = { workspace = true }
craft-i18n = { workspace = true }
craft-window = { workspace = true }
craft-keymap = { workspace = true }
craft-quit = { workspace = true }
craft-host = { workspace = true }
craft-theme = { workspace = true }
egui-phosphor = { version = "0.14", features = ["regular", "fill"] }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -32,8 +33,6 @@ craft-image-codecs = { workspace = true }
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sys-locale = "0.3"
# Floating panels open as OS windows.
craft-ui = { workspace = true }
# Help > Check for Updates and the check at start (updates_ui.rs).
craft-update = { workspace = true }
# Native file dialogs (file_dialogs.rs); the browser build has none.
+1 -1
View File
@@ -287,7 +287,7 @@ mod tests {
fn display_harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(0.01).with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().ui.dock.focus(crate::docking::Panel::Display);
harness.run_steps(4);
+179 -242
View File
@@ -1,20 +1,22 @@
//! The dock host: every side panel (assets, texture set list, layers, texture set settings,
//! properties, display/shader settings, history, log) is a tab that can be docked, tabbed,
//! resized, floated and closed around the viewport. 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. The bodies live in `dock.rs`, `shelf.rs` and
//! `windows.rs`.
//! resized, floated and closed around the viewport. 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 bodies live in `dock.rs`, `shelf.rs` and `windows.rs`.
//!
//! The viewport 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.
//! that cannot close or float. The layout persists with `UiState` as a craft-behavior
//! `Workspace`; a layout that does not load or validate becomes the default.
use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions};
use craft_ui::docking::{DockArea, DockContent, DockStyle, PanelLimits};
use std::sync::Arc;
use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions, SplitSize};
use craft_behavior::flow::Axis;
use craft_behavior::dock::SplitSize;
use egui::{Id, Margin, RichText, Ui, Vec2, vec2};
use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use egui::{Margin, Rect, Ui, Vec2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -22,11 +24,6 @@ use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
mod header_band;
mod shown_group_tab;
pub(crate) use shown_group_tab::HEADER_TITLE_LEFT;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Panel {
Viewport,
@@ -132,8 +129,8 @@ 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::Display => 0.0,
Panel::Shader => 1.0,
@@ -144,24 +141,24 @@ impl Panel {
Panel::BakingLog => 6.0,
_ => return None,
};
Some([960.0, 90.0 + 50.0 * slot, 300.0, 380.0])
Some(Rect::from_min_size(egui::pos2(960.0, 90.0 + 50.0 * slot), vec2(300.0, 380.0)))
}
}
/// The saved panel arrangement: craft-ui's workspace over TextureCraft's panels.
/// The saved panel arrangement: craft-behavior's workspace over TextureCraft's panels.
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
/// The viewport never moves, floats, closes or takes tabs; panels dock beside it.
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Viewport { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
if *panel == Panel::Viewport { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
}
fn tabs(panels: &[Panel]) -> Node<Panel> {
Node::Tabs { panels: panels.to_vec(), active: 0 }
Node::tabs(panels.to_vec(), 0)
}
fn split(axis: Axis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
Node::split(axis, size, first, second)
}
/// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties
@@ -188,46 +185,30 @@ pub fn default_workspace() -> Workspace {
tabs(&[Assets]),
split(Axis::X, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
);
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
if let Some(rect) = panel.float_rect() {
workspace.hidden.push((panel, floating_location(rect)));
}
}
let mut hidden: Vec<(Panel, Location<Panel>)> = Panel::ALL.into_iter().filter_map(|panel| Some((panel, floating_location(panel.float_rect()?)))).collect();
for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] {
workspace.hidden.push((
panel,
Location {
floating: None,
anchor: Some(TextureSetList),
placement: DockPlacement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
},
));
hidden.push((panel, Location::new(Some(TextureSetList), DockPlacement::tab(None))));
}
workspace
Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, Vec::new())
}
/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`)
fn floating_location(rect: [f32; 4]) -> Location<Panel> {
Location { floating: Some(rect), anchor: None, placement: DockPlacement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None }
/// Where a closed panel reopens as its own floating window at `rect`
fn floating_location(rect: Rect) -> Location<Panel> {
let mut location = Location::new(None, DockPlacement::tab(None));
location.floating = Some(rect);
location
}
/// craft-ui's checks plus the viewport'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::Viewport)) {
return Err("The viewport cannot float".into());
}
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Viewport) {
if workspace.hidden().iter().any(|(panel, _)| *panel == Panel::Viewport) {
return Err("The viewport cannot be hidden".into());
}
let mut found = false;
@@ -244,7 +225,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
}
found = true;
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Viewport) => {
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Viewport) => {
return Err("The viewport cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Viewport)) => {
@@ -271,19 +252,17 @@ const BAKING_LOG_HEIGHT: f32 = 160.0;
/// Share of the first bake column the texture set list takes above the mesh map bakers
const TEXTURE_SET_LIST_SHARE: f32 = 0.4;
/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`).
/// The dock layout (part of `UiState`; serialized as a craft-behavior `Workspace`).
#[derive(Clone, Debug)]
pub struct Dock {
workspace: Workspace,
/// A panel to bring in front of the other floating windows on the next frame.
raise: Option<Panel>,
/// A saved layout could not be read, so this is the painting default in its place
replaced_unreadable: bool,
}
impl Default for Dock {
fn default() -> Self {
Dock { workspace: default_workspace(), raise: None, replaced_unreadable: false }
Dock { workspace: default_workspace(), replaced_unreadable: false }
}
}
@@ -319,7 +298,7 @@ impl Dock {
return unreadable;
}
Dock { workspace, raise: None, replaced_unreadable: false }
Dock { workspace, replaced_unreadable: false }
}
/// Whether a saved layout could not be read and this dock is the painting default instead
@@ -329,15 +308,16 @@ impl Dock {
/// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport
pub(crate) fn for_baking() -> Self {
let mut workspace = default_workspace();
let painting = default_workspace();
let mut hidden = painting.hidden().to_vec();
for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] {
if let Ok(location) = workspace.layout.location(&panel) {
workspace.hidden.push((panel, location));
if let Ok(location) = painting.layout().location(&panel) {
hidden.push((panel, location));
}
}
let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log];
workspace.hidden.retain(|(panel, _)| !bake_panels.contains(panel));
hidden.retain(|(panel, _)| !bake_panels.contains(panel));
let gutter_width = f32::from(crate::theme::GUTTER);
let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers]));
@@ -346,8 +326,8 @@ impl Dock {
let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log]));
let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH;
let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport]));
workspace.layout = Layout { root: Some(root), floating: Vec::new() };
Dock { workspace, raise: None, replaced_unreadable: false }
let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec());
Dock { workspace, replaced_unreadable: false }
}
pub fn workspace(&self) -> &Workspace {
@@ -355,12 +335,12 @@ impl Dock {
}
pub fn is_open(&self, p: Panel) -> bool {
self.workspace.layout.contains(&p)
self.workspace.layout().contains(&p)
}
/// Open and the front tab of its group.
pub fn is_visible(&self, p: Panel) -> bool {
self.workspace.layout.panel_state(&p) == PanelState::Front
self.workspace.layout().panel_state(&p) == PanelState::Front
}
/// Hide a visible panel, otherwise bring it up.
@@ -369,7 +349,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}");
}
}
@@ -378,20 +358,19 @@ impl Dock {
/// front.
pub fn focus(&mut self, p: Panel) {
let mut next = self.workspace.clone();
match next.set_visible(p, true, None, permissions) {
Ok(()) if validate(&next).is_ok() => {
self.workspace = next;
self.raise = Some(p);
}
match next.set_visible(p, true, None, false, permissions) {
Ok(()) if validate(&next).is_ok() => self.workspace = next,
Ok(()) => log::warn!("panel {p:?} was not opened: it would break the viewport's rules"),
Err(error) => log::warn!("panel {p:?} was not opened: {error}"),
}
}
/// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`)
pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) {
self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel);
self.workspace.hidden.push((panel, floating_location(rect)));
/// Open the closed `panel` as a floating window at `rect`
pub(crate) fn float_at(&mut self, panel: Panel, rect: Rect) {
let mut hidden = self.workspace.hidden().to_vec();
hidden.retain(|(hidden_panel, _)| *hidden_panel != panel);
hidden.push((panel, floating_location(rect)));
self.workspace = Workspace::from_parts(self.workspace.layout().clone(), hidden, self.workspace.floated().to_vec());
self.focus(panel);
}
@@ -399,7 +378,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 viewport's rules"),
Err(error) => log::warn!("a panel move was not applied: {error}"),
@@ -407,58 +386,80 @@ 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 TextureCraft's own egui code: the dock runs it with the window's style.
let spec = PanelSpec::new(label).limits(SizeLimits::at_least(min_size(*panel))).float_size(FLOATING_SIZE.max(min_size(*panel))).host_body();
if *panel == Panel::Viewport { spec.canvas() } else { spec }
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// The tab name of `panel` in the interface language.
fn label(app: &TextureCraftApp, panel: Panel) -> String {
match panel {
Panel::Properties => crate::dock::properties_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 TextureCraftApp) {
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("texturecraft-docking")
/// The viewport's id as the window's document canvas.
fn viewport_canvas_id() -> egui::Id {
egui::Id::unique("texturecraft-viewport-canvas")
}
/// Smallest panel extent a divider drag leaves, in points
const MIN_PANE_EXTENT: f32 = 60.0;
/// Border width of a floating panel, in points
const FLOATING_BORDER_WIDTH: f32 = 1.0;
/// Text size of the panel tabs, in points
const TAB_TEXT_SIZE: f32 = 12.5;
/// Narrowest panel tab, in points
const MIN_TAB_WIDTH: f32 = 54.0;
/// Mixing in title ink keeps the light dock's focus outline above 3:1 on both header surfaces
const LIGHT_DOCK_ACCENT_TEXT_MIX: f32 = 0.2;
/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
let mut dock_style = DockStyle::from_ui(ui);
dock_style.gap = f32::from(crate::theme::GUTTER);
dock_style.min_pane = MIN_PANE_EXTENT;
dock_style.background = tokens.panel;
dock_style.tab_background = tokens.chrome;
// The selected title is brighter while the strip keeps its colour
dock_style.active_background = tokens.chrome;
dock_style.text = tokens.text_strong;
dock_style.inactive_text = tokens.text_dim;
dock_style.border = egui::Stroke::NONE;
dock_style.accent = if tokens.dark { tokens.accent } else { tokens.accent.lerp_to_gamma(tokens.text_strong, LIGHT_DOCK_ACCENT_TEXT_MIX) };
dock_style.floating_background = tokens.panel;
dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border);
dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE);
dock_style.min_tab_width = MIN_TAB_WIDTH;
dock_style.tab_height = TAB_HEIGHT;
// Panels arrange in a split tree around the viewport; floating title bars only move windows
dock_style.new_dock_zones = false;
dock_style.title_bar_docks = false;
dock_style
/// Declares the viewport, drawn in this pass, as the window's document canvas (the dock's canvas
/// group, or the whole window with the UI hidden).
pub(crate) fn host_viewport_canvas(ctx: &egui::Context) {
crate::framework::host_canvas(ctx, viewport_canvas_id());
}
/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included,
/// do not take it.
/// From a panel's left edge to its contents' text (an empty panel's note)
pub(crate) const HEADER_TITLE_LEFT: f32 = 12.0;
/// Whether one of TextureCraft's own modal layers or the update dialogs hold the input, so the
/// panels floated into windows of their own do not take it (`FrameInput::app_modal`).
pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> bool {
let modal = context.memory(|memory| memory.top_modal_layer()).is_some();
#[cfg(not(target_arch = "wasm32"))]
@@ -480,57 +481,49 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
}
let context = ui.ctx().clone();
let tokens = Tokens::get(&context);
let style = style(ui, &tokens);
let layout = app.ui.dock.workspace.layout.clone();
let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context));
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, tokens, layout: &layout, style: &style });
crate::rail_popup::hand_drag_to_dock(&context, area_id());
refresh_specs(app);
let shown = app.docks.shown(&app.ui.dock.workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.docks.specs);
// Panels arrange in a split tree around the viewport; floating title bars only move windows.
let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false);
let output = {
let tokens = Tokens::get(&context);
let mut panels = Panels { app: &mut *app, tokens, layout: shown.layout().clone() };
DockArea::new("Panels", Bind::given(Arc::clone(&shown)), &specs, &mut panels, config).show(ui)
};
app.docks.specs = specs;
// The popup needs the viewport the dock recorded this frame
crate::rail_popup::show(app, &context);
// Keys pressed in a panel floated into a window of its own run the app's shortcuts there
#[cfg(not(target_arch = "wasm32"))]
crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default());
for (_, viewport) in &output.windows {
let (events, held) = context.input_for(*viewport, |input| (input.events.clone(), input.modifiers));
crate::menus::forwarded_shortcuts(app, &context, events, held);
}
if let Some(error) = &output.error {
log::warn!("docking: {error}");
log::warn!("docking: {:?}", error.error);
}
// A layout changed by a panel takes priority over gestures from the old layout
if app.ui.dock.workspace.layout != layout {
craft_ui::docking::cancel_drag::<Panel>(&context, area_id());
if app.ui.dock.workspace != *shown {
craft_ui::runtime::drag::cancel(&context, 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);
}
}
/// Size of the panel names on a header bar
const HEADER_TITLE_SIZE: f32 = 12.0;
/// Side of the close × at the right end of a header bar
const HEADER_CLOSE_SIZE: f32 = 22.0;
/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter)
const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0;
/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes)
fn header_closes(active: &Panel, floating: bool) -> bool {
!floating && permissions(active).closable
}
/// The panels' contents, names and limits for the dock area
/// The panels' contents for the dock area
struct Panels<'a> {
app: &'a mut TextureCraftApp,
tokens: Tokens,
layout: &'a Layout<Panel>,
style: &'a DockStyle,
/// The arrangement the dock shows in this pass
layout: Layout<Panel>,
}
/// Room between a panel's edges and its contents
@@ -596,100 +589,42 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
});
}
impl DockContent<Panel> for Panels<'_> {
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
if *panel == Panel::Viewport {
crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect());
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport);
crate::viewport::central(self.app, ui);
return;
}
// Before the rows, which draw over the foot of the shown tab's box
self.paint_shown_group_tab(ui, *panel);
panel_body(self.app, ui, *panel);
}
fn logical_label(&self, panel: &Panel) -> String {
match panel {
Panel::Properties => crate::dock::properties_title(self.app),
p => tr(p.name()).to_string(),
impl DockPanels<Panel> for Panels<'_> {
fn body(&mut self, panel: &Panel, ui: &mut Ui, _: &mut BodyCx<'_>) {
// The viewport is its group's `group_view`
if *panel != Panel::Viewport {
panel_body(self.app, ui, *panel);
}
}
fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
// Capitals on the bar only: menus and screen readers keep the logical name
let name = logical.to_uppercase();
let font = crate::theme::semibold(HEADER_TITLE_SIZE);
// Popup menu rows use their unpadded text metrics
if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) {
return RichText::new(name).font(font).color(color).into();
/// The viewport, edge to edge in its group, as the window's document canvas.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Viewport) {
return None;
}
header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into()
host_viewport_canvas(ui.ctx());
crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect());
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport);
crate::viewport::central(self.app, ui);
Some(rect.height())
}
fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 {
if header_closes(active, floating) {
HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN
} else if redocks(panels, active, floating) {
DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN
} else {
0.0
/// A rail panel floating on its own carries the Dock button that sends it back to the rail
fn group_header(&mut self, panels: &[Panel], active: usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
let Some(active) = panels.get(active).copied() else { return };
let floating = self.layout.floating.iter().any(|window| window.contains(&active));
if redocks(panels, &active, floating)
&& crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked()
{
self.app.ui.dock.close(active);
}
}
/// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail
fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) {
if redocks(panels, active, floating) {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() {
self.app.ui.dock.close(*active);
}
});
return;
}
if !header_closes(active, floating) {
return;
}
// Centre the close control on the header title line
let rect = ui.max_rect();
let button = egui::Rect::from_center_size(
egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)),
vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE),
);
let clicked = ui
.scope_builder(egui::UiBuilder::new().max_rect(button), |ui| {
crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked()
})
.inner;
if clicked {
self.app.ui.dock.close(*active);
}
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
PanelLimits { min: min_size(*panel), ..PanelLimits::default() }
}
fn floating_size(&self, panel: &Panel) -> Option<egui::Vec2> {
Some(FLOATING_SIZE.max(min_size(*panel)))
}
}
/// Size of the Dock button in a floating rail panel's tab strip
/// Size of the Dock button in a floating rail panel's header
const DOCK_BUTTON_SIZE: f32 = 22.0;
/// Room right of the Dock button, so it clears the strip's end
const DOCK_BUTTON_MARGIN: f32 = 6.0;
/// Whether a floating window holds one rail panel alone: its Dock button closes it back onto the rail
fn redocks(panels: &[Panel], active: &Panel, floating: bool) -> bool {
floating && panels.len() == 1 && crate::rail_popup::is_rail_panel(*active)
@@ -700,7 +635,7 @@ mod tests {
use super::*;
fn panels_of(w: &Workspace) -> Vec<Panel> {
w.layout.panels().into_iter().copied().collect()
w.layout().panels().into_iter().copied().collect()
}
#[test]
@@ -710,7 +645,7 @@ mod tests {
assert!(validate(&workspace).is_ok());
for panel in Panel::ALL {
assert!(workspace.layout.contains(&panel) || workspace.hidden.iter().any(|(hidden, _)| *hidden == panel), "{panel:?} is neither shown nor hidden");
assert!(workspace.layout().contains(&panel) || workspace.hidden().iter().any(|(hidden, _)| *hidden == panel), "{panel:?} is neither shown nor hidden");
}
assert_eq!(panels_of(&workspace), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]);
@@ -718,12 +653,14 @@ mod tests {
#[test]
fn a_saved_split_keeps_its_own_share() {
let mut workspace = default_workspace();
let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") };
let default = default_workspace();
let mut layout = default.layout().clone();
let Some(Node::Split { second: right, .. }) = layout.root.as_mut() else { panic!("assets | rest") };
let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") };
let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") };
let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") };
*size = SplitSize::Ratio(0.57);
let workspace = Workspace::from_parts(layout, default.hidden().to_vec(), default.floated().to_vec());
let back = Dock::from_value(serde_json::to_value(&workspace).unwrap());
assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged");
@@ -772,7 +709,7 @@ mod tests {
let dock = Dock::from_value(saved);
assert!(!dock.replaced_unreadable(), "the saved layout is kept");
assert!(dock.workspace().hidden.iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed");
assert!(dock.workspace().hidden().iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed");
}
#[test]
@@ -781,8 +718,8 @@ mod tests {
dock.close(Panel::Viewport);
assert!(dock.is_open(Panel::Viewport));
let before = dock.clone();
dock.apply(Action::Float { panel: Panel::Viewport, rect: [0.0, 0.0, 300.0, 300.0] });
dock.apply(Action::Move { panel: Panel::Layers, anchor: Panel::Viewport, placement: DockPlacement::Tab { before: None } });
dock.apply(Action::float(Panel::Viewport, Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))));
dock.apply(Action::move_beside(Panel::Layers, Panel::Viewport, DockPlacement::tab(None)));
assert_eq!(dock, before);
}
@@ -806,8 +743,8 @@ mod tests {
let mut dock = Dock::default();
dock.focus(Panel::Display);
assert!(dock.is_visible(Panel::Display));
assert_eq!(dock.workspace().layout.floating.len(), 1);
assert!(dock.workspace().layout.floating[0].contains(&Panel::Display));
assert_eq!(dock.workspace().layout().floating.len(), 1);
assert!(dock.workspace().layout().floating[0].contains(&Panel::Display));
// Hiding and showing the views one by one.
dock.toggle(Panel::Display);
assert!(!dock.is_open(Panel::Display));
-54
View File
@@ -1,54 +0,0 @@
//! Positions dock tab titles within the tab strip and the gutter above it.
use craft_behavior::dock::{Layout, Node};
use craft_behavior::flow::Axis;
use egui::text::{LayoutJob, TextFormat};
use egui::{Align, Color32, FontId, Ui};
use super::Panel;
/// Gap left between a header band and the panel above it, in points.
const HEADER_SEPARATION: f32 = 2.0;
/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation
pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - HEADER_SEPARATION;
/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none
pub(super) fn under_a_panel(layout: &Layout<Panel>, panel: Panel) -> bool {
layout.root.as_ref().and_then(|node| group_is_below_panel(node, panel, false)).unwrap_or(false)
}
fn group_is_below_panel(node: &Node<Panel>, panel: Panel, below_panel: bool) -> Option<bool> {
match node {
Node::Split { axis, first, second, .. } => {
group_is_below_panel(second, panel, below_panel || *axis == Axis::Y).or_else(|| group_is_below_panel(first, panel, below_panel))
}
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(below_panel),
Node::Dock { columns, .. } => {
columns.iter().find_map(|column| column.groups.iter().position(|group| group.panels.contains(&panel))).map(|index| below_panel || index > 0)
}
_ => None,
}
}
/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders)
pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift_points: f32) -> LayoutJob {
let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() };
let mut job = LayoutJob::single_section(name.to_owned(), format);
let galley = ui.painter().layout_job(job.clone());
// Scripts without capitals use the whole galley as their ink bounds
let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph)));
let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0);
// Room below the name raises it when centred, room above lowers it
let shift = ink_middle - galley.size().y / 2.0 + lift_points;
if shift < 0.0
&& let Some(section) = job.sections.first_mut()
{
section.format.valign = Align::BOTTOM;
}
job.first_row_min_height = galley.size().y + 2.0 * shift.abs();
job
}
@@ -1,102 +0,0 @@
//! The active tab in a panel group, drawn as a raised box joined to the panel body
use craft_ui::docking::DockContent;
use craft_behavior::dock::Node;
use egui::text::TextWrapping;
use egui::{Rect, Stroke, StrokeKind, Ui, pos2};
use super::header_band::{HEADER_RISE, header_name, under_a_panel};
use super::{HEADER_TITLE_SIZE, Panel, Panels, area_id};
use crate::property_sheet::{full_height_tab_rect, shown_tab_box};
use crate::theme::semibold;
/// Horizontal padding of craft-ui's dock tab, in points
const DOCK_TAB_PADDING: f32 = 24.0;
/// From a panel's left edge to its header's name
pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0;
/// Gap between the active tab's box and its neighbours, in points
const TAB_BOX_INSET: f32 = 4.0;
/// Insets the focus outline inside the tab's actual hit rect
const TAB_FOCUS_INSET: f32 = 2.0;
/// Width of the focus outline in points
const TAB_FOCUS_STROKE_WIDTH: f32 = 1.0;
/// The tab group containing `panel`; a collapsed stack has no tabs
fn group_of(node: &Node<Panel>, panel: Panel) -> Option<&[Panel]> {
match node {
Node::Split { first, second, .. } => group_of(first, panel).or_else(|| group_of(second, panel)),
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(panels),
Node::Dock { columns, .. } => {
columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)).map(|group| group.panels.as_slice())
}
_ => None,
}
}
impl Panels<'_> {
/// How far a header band reaches above its tab strip
fn header_rise(&self, panel: Panel) -> f32 {
if under_a_panel(self.layout, panel) { HEADER_RISE } else { 0.0 }
}
/// How far a header name sits above the tab strip's centre
pub(super) fn header_lift(&self, panel: Panel) -> f32 {
self.header_rise(panel) / 2.0
}
/// Paints the active tab and its focus outline above the renderer's fallback paint
pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) {
let layout = self.layout;
let in_group = layout
.root
.iter()
.chain(layout.floating.iter().map(|window| &window.root))
.find_map(|root| group_of(root, panel))
.is_some_and(|group| group.len() > 1);
if !in_group {
return;
}
// The shared renderer submits the active tab before it calls the panel body
let tab_id = area_id().with(("tab", &panel));
let Some(tab) = ui.ctx().read_response(tab_id) else { return };
let body = ui.max_rect();
let tab_rect = tab.rect;
if tab.layer_id != ui.layer_id() || tab_rect.bottom() != body.top() || tab_rect.left() < body.left() || tab_rect.right() > body.right() {
return;
}
let band_top = tab_rect.top() - self.header_rise(panel);
let box_left = if tab_rect.left() > body.left() { tab_rect.left() + TAB_BOX_INSET } else { tab_rect.left() };
let box_right = tab_rect.right() - TAB_BOX_INSET;
if box_left >= box_right {
return;
}
// Extend the body's clip over the header without widening it
let clip = ui.clip_rect();
let mut painter = ui.painter().clone();
painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band_top..=clip.bottom()));
let band = Rect::from_x_y_ranges(body.x_range(), band_top..=tab_rect.bottom());
shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, box_right));
let name = self.logical_label(&panel).to_uppercase();
let font = semibold(HEADER_TITLE_SIZE);
let mut job = header_name(ui, &name, font, self.style.text, (tab_rect.top() - band_top) / 2.0);
job.wrap = TextWrapping::truncate_at_width((tab_rect.width() - DOCK_TAB_PADDING).max(0.0));
let galley = painter.layout_job(job);
let at = pos2(tab_rect.left() + HEADER_TITLE_LEFT, tab_rect.center().y - galley.size().y / 2.0);
painter.galley(at, galley, self.style.text);
// Preserve the shared dock's keyboard focus ring above the opaque selected tab
let pointer_focus = ui.data(|data| data.get_temp::<bool>(tab_id.with("pointer-focus"))).unwrap_or(false);
let focus_rect = tab_rect.shrink(TAB_FOCUS_INSET);
if tab.has_focus() && !pointer_focus && focus_rect.is_positive() {
painter.rect_stroke(focus_rect, 0.0, Stroke::new(TAB_FOCUS_STROKE_WIDTH, self.style.accent), StrokeKind::Inside);
}
}
}
+1 -2
View File
@@ -6,7 +6,6 @@
use std::panic::Location;
use std::path::PathBuf;
use std::sync::Arc;
pub use craft_dialogs::{Answer, FileDialog, Override, Request};
@@ -57,7 +56,7 @@ impl FileDialogs {
/// The dialogs of the app whose context is `ctx`: an answer wakes its event loop.
pub fn new(ctx: egui::Context) -> FileDialogs {
FileDialogs {
dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())),
dialogs: craft_dialogs::Dialogs::new(craft_dialogs::Wake::new(move || ctx.request_repaint())),
asked: Vec::new(),
headless: false,
shown_folders: Vec::new(),
+1 -1
View File
@@ -161,7 +161,7 @@ impl UiFonts {
defs.families.entry(family).or_default().push(name.clone());
}
}
ctx.set_fonts(defs);
crate::theme::load_fonts(ctx, defs);
self.installed = want;
}
+1 -1
View File
@@ -418,7 +418,7 @@ pub(crate) mod tests {
let session = Session::new_project("Gizmo", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
let builder = egui_kittest::Harness::builder().with_size(TEST_WINDOW);
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = builder.with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
harness
}
+154
View File
@@ -0,0 +1,154 @@
//! The craft-ui runtime, hosted from TextureCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`TextureCraftApp::before_input`] in `raw_input_hook`,
//! [`TextureCraftApp::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 [`TextureCraftApp::framework_dialogs`] after
//! TextureCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of TextureCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with
//! [`take_window_cancel`]; the 3D/2D viewport is declared to the runtime with [`host_canvas`], which keeps Tab (Hide
//! UI), the edit chords and the clipboard events in egui's input for TextureCraft's shortcuts.
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::Overrides;
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, NavCommand, QuitCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::policy::Decision;
use craft_window::system::WindowSystem;
use egui::ViewportId;
use crate::TextureCraftApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The id every OS window of the app carries, as the desktop entry and the update app name it.
const APP_ID: &str = "ai.storyteller.texturecraft";
/// 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. TextureCraft's own definitions
/// ([`crate::theme::install`]) replace it before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>, frame: Option<Decision>) -> Result<(), String> {
let mut spec = craft_ui::InstallSpec::new(shell, windows).app_id(APP_ID);
if let Some(frame) = frame {
spec = spec.frame(frame);
}
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass, with the window's `frame`
/// ([`crate::titlebar::TitleBar::decide`]).
#[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 TextureCraft 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: "texturecraft", name: "TextureCraft", version: texturecraft_engine::VERSION })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png"))
.build(),
)
}
/// TextureCraft's own shortcut table keeps the keys the framework binds by default: Ctrl+Q is `ui.quit`, F6 is
/// `camera.orthographic` (and Shift+F6 stays free for it), so the framework's quit and pane moves are unbound.
/// Overrides are keyed by command id, which the command sets give.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
for id in [QuitCommand::Quit.id(), NavCommand::NextPane.id(), NavCommand::PreviousPane.id()] {
overrides.insert(id, Vec::new());
}
Arc::new(overrides)
})
.clone()
}
impl TextureCraftApp {
/// 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 and interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
// TextureCraft applies the interface scale itself (`logic`), 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. TextureCraft registers no commands with the runtime (its own shortcut table
/// runs every key, [`command_overrides`]) and lets it toggle no chrome (Tab is Hide UI, kept in egui by the
/// viewport's [`host_canvas`]), so the output carries nothing it acts on. While one of TextureCraft'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 root = RootEnv::new().mode(mode).scale(Scale::new(scale));
let app_modal = crate::docking::input_blocked(self, ctx).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 TextureCraft's own: the root window's close path. Unsaved changes
/// hold the window open while the Unsaved Changes dialog asks ([`crate::windows::close_requested`]); otherwise
/// it closes.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || if crate::windows::close_requested(self) { CloseDecision::Hold } else { CloseDecision::Close });
}
}
/// Declares the viewport `id`, drawn in this pass, as the window's document canvas. With nothing focused it is the
/// window's key target: Tab (Hide UI), the edit chords and the clipboard events stay in egui's input for TextureCraft's
/// shortcuts.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) {
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL);
craft_ui::runtime::focus::host_canvas(ctx, id, KEYS);
}
/// Whether Escape was pressed in this pass: from egui while one of TextureCraft's own widgets or popups has the
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel(ctx, false)
}
/// Takes the window's cancel (an Escape while nothing has framework focus) when it is there: no later reader sees it.
pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool {
window_cancel(ctx, true)
}
/// Whether the window's cancel is there and untaken; `take` takes it.
fn window_cancel(ctx: &egui::Context, take: bool) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = if take { intents.take(Intent::Cancel) } else { intents.untaken(&Intent::Cancel) };
take && pending
});
pending
}
+14 -8
View File
@@ -4,7 +4,7 @@
use std::collections::BTreeMap;
use craft_keymap::egui::Dispatcher;
use crate::shortcut_dispatch::Dispatcher;
use craft_keymap::{Active, Chord, CommandDef, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes};
use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2};
use egui_phosphor::regular as ic;
@@ -229,7 +229,7 @@ impl Default for Bindings {
let stored = Keymap::new();
let map = resolved(&stored, Platform::current());
// Held keys repeat their command. Copy, Cut and Paste events count as Ctrl+C, X and V.
Bindings { stored, map, dispatcher: Dispatcher::new().with_repeat(true).with_clipboard_events(true) }
Bindings { stored, map, dispatcher: Dispatcher::default() }
}
}
@@ -245,7 +245,7 @@ impl Bindings {
/// The ids of the commands this frame's key presses run, in press order. The presses are
/// removed from the input.
pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec<String> {
self.dispatcher.dispatch(input, &self.map, &Active::NONE).into_iter().map(|hit| hit.command.id).collect()
self.dispatcher.dispatch_filtered(input, &self.map, |_| true).into_iter().map(|hit| hit.command.id).collect()
}
/// The id of the command a key press outside the main window runs. The press is matched as
@@ -391,7 +391,9 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
let tk = Tokens::get(&ctx);
let capture_id = Id::unique(SETTINGS_CAPTURE);
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
if let (Some(i), Some(sc)) = (capture, pressed(&ctx, recorder)) {
if let Some(i) = capture
&& let Some(sc) = pressed(&ctx, recorder)
{
if let Some(b) = bindings().get(i) {
if sc.logical_key == Key::Delete && sc.modifiers.is_none() {
rebind(keymap, b, "");
@@ -487,15 +489,17 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
});
}
/// The first key press this frame as a shortcut.
/// The first key press this frame as a shortcut. A plain Escape while none of TextureCraft's widgets has the keyboard
/// is the window's cancel, which the recorder takes as the Escape that cancels it.
fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option<KeyboardShortcut> {
let platform = craft_keymap::egui::platform(ctx);
ctx.input(|i| {
let press = ctx.input(|i| {
i.events.iter().find_map(|e| match e {
Event::Key { key, pressed: true, modifiers, .. } => Some(bindings.recorded(e, *key, *modifiers, platform)),
_ => None,
})
})
});
press.or_else(|| crate::framework::take_window_cancel(ctx).then(|| KeyboardShortcut::new(Modifiers::NONE, Key::Escape)))
}
/// The shortcut editor window.
@@ -509,7 +513,9 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
let capture_id = Id::unique(CAPTURE);
let filter_id = Id::unique("keymap_filter");
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
if let (Some(i), Some(sc)) = (capture, pressed(ctx, &app.bindings)) {
if let Some(i) = capture
&& let Some(sc) = pressed(ctx, &app.bindings)
{
if (sc.logical_key != Key::Escape || !sc.modifiers.is_none())
&& let Some(b) = bindings().get(i)
{
+23 -2
View File
@@ -43,6 +43,7 @@ mod filter_slot;
mod filter_transform_rows;
mod folder_properties;
pub mod fonts;
pub mod framework;
mod frame_gizmo;
mod generator_panel;
pub mod gpu;
@@ -89,6 +90,7 @@ mod orb_environment;
mod orb_material;
pub mod orb_previews;
mod orb_shape;
mod pane_split;
pub mod parity;
mod past_end;
mod path_hit;
@@ -135,6 +137,7 @@ mod session_log_file;
pub mod settings_window;
pub mod shader_settings;
pub mod shelf;
mod shortcut_dispatch;
mod shelf_entry;
mod shelf_folders;
pub mod shelf_panes;
@@ -309,6 +312,12 @@ pub struct TextureCraftApp {
pub banner: Option<&'static str>,
/// Who draws the window's title bar (decided at startup, before the window opens).
pub title_bar: titlebar::TitleBar,
/// 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 TextureCraft's own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who TextureCraft is to the framework's dialogs.
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
last_time: f64,
/// When the next autosave is due (seconds of app time; desktop only).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
@@ -434,6 +443,9 @@ impl TextureCraftApp {
fonts: fonts::UiFonts::default(),
banner: None,
title_bar: titlebar::TitleBar::default(),
docks: docking::LiveDock::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: framework::host(),
last_time: 0.0,
next_autosave,
styled: None,
@@ -1052,6 +1064,7 @@ impl TextureCraftApp {
impl eframe::App for TextureCraftApp {
/// A drag that holds the pointer reads the pointer's moves as moves of a pointer no screen edge stops
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
self.before_input(ctx);
pointer_lock::rewrite(ctx, raw_input);
}
@@ -1158,7 +1171,7 @@ impl eframe::App for TextureCraftApp {
self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32;
// Last, so it sees every close request this frame's work made
windows::close_request(self, ctx);
self.close_path(ctx);
}
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
@@ -1187,7 +1200,14 @@ impl eframe::App for TextureCraftApp {
// The dock keeps the cards' gutter from the bars and rails around it
let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) };
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) });
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| {
if hide_ui {
docking::host_viewport_canvas(ui.ctx());
viewport::central(self, ui);
} else {
docking::show(self, ui);
}
});
windows::show(self, &ctx);
// Finish after the dock and windows have requested their thumbnails
@@ -1195,6 +1215,7 @@ impl eframe::App for TextureCraftApp {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
self.framework_dialogs.run(ui);
toasts(self, &ctx);
#[cfg(not(target_arch = "wasm32"))]
self.file_dialogs.show_pending(frame);
+8
View File
@@ -458,6 +458,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
return;
}
// A plain Escape no widget of TextureCraft's took is the window's cancel: it runs the Escape handlers and shortcuts below
if crate::framework::take_window_cancel(ctx) {
ctx.input_mut(|i| {
let modifiers = i.modifiers;
i.events.insert(0, egui::Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: true, repeat: false, modifiers });
});
}
// The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V
// Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V
ctx.input_mut(|input| {
+261
View File
@@ -0,0 +1,261 @@
//! Two panes split by a focusable divider: the geometry of one split and its resize handle (pointer drag, arrow keys
//! and accessibility). The shelf's saved searches and path filter (`shelf_panes.rs`) use it.
use std::ops::RangeInclusive;
use craft_behavior::dock::SplitSize;
use craft_behavior::flow::Axis;
use egui::{Color32, EventFilter, Id, Key, Modifiers, Rect, Response, Sense, Ui, Vec2, accesskit};
/// Contained, non-overlapping rectangles of a single split, including its divider.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct SplitLayout {
pub(crate) first: Rect,
pub(crate) divider: Rect,
pub(crate) second: Rect,
first_size: f32,
available: f32,
}
impl SplitLayout {
/// The first pane's size along the split axis, in points.
pub(crate) fn first_size(self) -> f32 {
self.first_size
}
/// Space for both panes, excluding the divider, in points.
pub(crate) fn available(self) -> f32 {
self.available
}
/// The size after moving the divider by `delta` points, in the same sizing mode. When both minima cannot fit,
/// each pane gets half the available space. Invalid inputs and zero available space give `None`, so the caller
/// keeps its saved value.
pub(crate) fn resized(self, size: SplitSize, delta: f32, minimum: f32) -> Option<SplitSize> {
if !value(size).is_finite() || !delta.is_finite() || !valid_nonnegative(minimum) || self.available <= 0.0 {
return None;
}
let available = f64::from(self.available);
let first = clamp_first(f64::from(self.first_size) + f64::from(delta), available, minimum);
Some(match size {
SplitSize::FixedFirst(_) => SplitSize::FixedFirst(first as f32),
SplitSize::FixedSecond(_) => SplitSize::FixedSecond((available - first) as f32),
_ => SplitSize::Ratio((first / available) as f32),
})
}
}
fn value(size: SplitSize) -> f32 {
match size {
SplitSize::Ratio(v) | SplitSize::FixedFirst(v) | SplitSize::FixedSecond(v) => v,
#[allow(unreachable_patterns)]
_ => f32::NAN,
}
}
/// Divides `rect` into two panes and a divider `gap` points thick. Equal pane minima relax to half the remaining
/// span in tiny areas; finite sizes outside the available range are clamped. Inverted or non-finite rectangles, a
/// negative or non-finite gap or minimum and a non-finite size give `None`.
pub(crate) fn split_rect(rect: Rect, axis: Axis, size: SplitSize, gap: f32, minimum: f32) -> Option<SplitLayout> {
if !valid_rect(rect) || !valid_nonnegative(gap) || !valid_nonnegative(minimum) || !value(size).is_finite() {
return None;
}
let total = if axis == Axis::X { rect.width() } else { rect.height() };
let gap = gap.min(total);
let available = total - gap;
let space = f64::from(available);
// f64: two finite f32 inputs can overflow when multiplied.
let wanted = match size {
SplitSize::FixedFirst(points) => f64::from(points),
SplitSize::FixedSecond(points) => space - f64::from(points),
other => space * f64::from(value(other)),
};
let first_size = clamp_first(wanted, space, minimum) as f32;
let (mut first, mut divider, mut second) = (rect, rect, rect);
if axis == Axis::X {
first.max.x = (rect.min.x + first_size).min(rect.max.x);
divider.min.x = first.max.x;
divider.max.x = (divider.min.x + gap).min(rect.max.x);
second.min.x = divider.max.x;
} else {
first.max.y = (rect.min.y + first_size).min(rect.max.y);
divider.min.y = first.max.y;
divider.max.y = (divider.min.y + gap).min(rect.max.y);
second.min.y = divider.max.y;
}
Some(SplitLayout { first, divider, second, first_size, available })
}
fn valid_rect(rect: Rect) -> bool {
rect.min.is_finite() && rect.max.is_finite() && rect.width().is_finite() && rect.height().is_finite() && rect.min.x <= rect.max.x && rect.min.y <= rect.max.y
}
fn valid_nonnegative(value: f32) -> bool {
value.is_finite() && value >= 0.0
}
fn clamp_first(wanted: f64, available: f64, minimum: f32) -> f64 {
let low = f64::from(minimum).min(available * 0.5);
wanted.clamp(low, available - low)
}
/// Colours of a resize handle. The handle at rest paints no fill.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ResizeHandleStyle {
pub(crate) hovered: Color32,
pub(crate) dragged: Color32,
pub(crate) focused: Color32,
}
/// A focusable divider moved by a pointer drag, the arrows along its axis while it has focus, and accessibility's
/// Increment, Decrement and SetValue. It never stores a size: [`show`](ResizeHandle::show) returns the move along the
/// axis for the caller to apply.
pub(crate) struct ResizeHandle<'a> {
id: Id,
axis: Axis,
rect: Rect,
label: &'a str,
style: ResizeHandleStyle,
hit_margin: f32,
value: Option<(f32, RangeInclusive<f32>)>,
}
/// Keyboard and accessibility step, in points.
const STEP: f32 = 8.0;
impl<'a> ResizeHandle<'a> {
pub(crate) fn new(id: Id, axis: Axis, rect: Rect, label: &'a str, style: ResizeHandleStyle) -> Self {
Self { id, axis, rect, label, style, hit_margin: 3.0, value: None }
}
/// Widens the hit rectangle along the movement axis, in points. Default: 3.
pub(crate) fn hit_margin(mut self, margin: f32) -> Self {
self.hit_margin = margin;
self
}
/// The current size and its bounds, for accessibility and its SetValue action.
pub(crate) fn value(mut self, value: f32, range: RangeInclusive<f32>) -> Self {
self.value = Some((value, range));
self
}
/// Shows the handle and returns the requested move along the axis this pass, in points (0 for none).
pub(crate) fn show(self, ui: &mut Ui) -> f32 {
let horizontal = self.axis == Axis::X;
let hit = self.rect.expand2(if horizontal { Vec2::new(self.hit_margin, 0.0) } else { Vec2::new(0.0, self.hit_margin) });
let valid = valid_rect(self.rect)
&& self.rect.width() > 0.0
&& self.rect.height() > 0.0
&& valid_rect(hit)
&& (0.0..=4096.0).contains(&self.hit_margin)
&& self.value.as_ref().is_none_or(|(value, range)| value.is_finite() && range.start().is_finite() && range.end().is_finite() && range.start() <= range.end());
let inert = Rect::from_min_size(ui.min_rect().min, Vec2::ZERO);
let mut response = ui.interact(if valid { hit } else { inert }, self.id, if valid { Sense::drag() } else { Sense::hover() });
let enabled = valid && response.enabled();
let mut delta = 0.0;
if enabled {
drag_focus(ui, &response);
if response.dragged() {
let drag = response.drag_delta();
delta = if horizontal { drag.x } else { drag.y };
}
if response.has_focus() {
let filter = EventFilter { horizontal_arrows: horizontal, vertical_arrows: !horizontal, ..Default::default() };
ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, filter));
let (back, forward) = if horizontal { (Key::ArrowLeft, Key::ArrowRight) } else { (Key::ArrowUp, Key::ArrowDown) };
ui.input_mut(|input| {
if input.consume_key(Modifiers::NONE, back) {
delta -= STEP;
}
if input.consume_key(Modifiers::NONE, forward) {
delta += STEP;
}
});
}
let mut change = 0.0;
ui.input_mut(|input| {
input.consume_accesskit_action_requests(response.id, |request| match request.action {
accesskit::Action::Increment => {
change += STEP;
true
}
accesskit::Action::Decrement => {
change -= STEP;
true
}
accesskit::Action::SetValue => {
if let (Some((value, range)), Some(accesskit::ActionData::NumericValue(new_value))) = (&self.value, &request.data)
&& new_value.is_finite()
{
change = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32;
delta = 0.0;
}
true
}
_ => false,
});
});
delta += change;
}
if !delta.is_finite() {
delta = 0.0;
}
if delta != 0.0 {
response.mark_changed();
}
response.widget_info(|| match &self.value {
Some((value, _)) if valid => egui::WidgetInfo::slider(enabled, f64::from(*value), self.label),
_ => egui::WidgetInfo::labeled(egui::Role::Unknown, enabled, self.label),
});
ui.ctx().accesskit_node_builder(response.id, |node| {
node.set_role(accesskit::Role::Splitter);
// Orientation describes the divider itself, across its movement axis.
node.set_orientation(if horizontal { accesskit::Orientation::Vertical } else { accesskit::Orientation::Horizontal });
if enabled {
node.add_action(accesskit::Action::Increment);
node.add_action(accesskit::Action::Decrement);
if let Some((value, range)) = &self.value {
node.set_numeric_value(f64::from(*value));
node.set_min_numeric_value(f64::from(*range.start()));
node.set_max_numeric_value(f64::from(*range.end()));
node.set_numeric_value_step(f64::from(STEP));
node.add_action(accesskit::Action::SetValue);
}
}
});
if enabled {
let fill = if response.dragged() {
Some(self.style.dragged)
} else if response.has_focus() {
Some(self.style.focused)
} else if response.hovered() {
Some(self.style.hovered)
} else {
None
};
if let Some(fill) = fill {
ui.painter().rect_filled(self.rect, 0.0, fill);
}
if response.hovered() || response.dragged() {
ui.ctx().set_cursor_icon(if horizontal { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
}
}
delta
}
}
/// A pointer drag focuses its handle for the gesture only and gives the focus up on release, so the app's shortcuts
/// and its canvas arrow keys work again. A handle focused from the keyboard before the drag keeps its focus.
fn drag_focus(ui: &Ui, response: &Response) {
let key = response.id.with("pointer-focus");
if response.drag_started() {
if !response.has_focus() {
ui.ctx().data_mut(|d| d.insert_temp(key, ()));
}
response.request_focus();
}
if response.drag_stopped() && ui.ctx().data_mut(|d| d.remove_temp::<()>(key)).is_some() {
response.surrender_focus();
}
}
@@ -285,7 +285,7 @@ impl PropertySheet<'_> {
});
// Escape ends hex editing first even when egui has already dropped the field's focus
let escape = ctx.input(|input| input.key_pressed(egui::Key::Escape))
let escape = crate::framework::escape_pressed(&ctx)
&& ctx.memory(|memory| memory.focused().is_none_or(|focused| focused == bar.id))
&& !hex_took_escape(&ctx);
if closed || (!list_open && !waiting && (pressed_outside || escape)) {
+1 -1
View File
@@ -63,7 +63,7 @@ pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection};
pub(crate) use row_lead::RowLead;
pub(crate) use section_tabs::{
SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections,
full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box,
in_scope, room_past_end, section_tabs,
};
pub(crate) use sheet::PropertySheet;
pub(crate) use slot_response::SlotResponse;
@@ -109,13 +109,8 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect {
Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(right, strip.bottom() + TAB_BELOW))
}
/// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab
pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect {
Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW))
}
/// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip
pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) {
fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) {
painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel);
}
+3 -19
View File
@@ -56,11 +56,6 @@ fn icons_id() -> Id {
Id::unique("rail_popup_icons")
}
/// The panel whose popup title a drag left, and the title's rect, until the dock takes the drag over
fn pending_drag_id() -> Id {
Id::unique("rail_popup_pending_drag")
}
/// Where the dock drew the viewport on this frame
fn viewport_id() -> Id {
Id::unique("rail_popup_viewport")
@@ -114,16 +109,6 @@ pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) {
}
}
/// Hand a drag that left the popup's title to the dock, once the dock has drawn the panel it floated
pub(crate) fn hand_drag_to_dock(ctx: &egui::Context, dock_area: Id) {
let Some((panel, title)) = ctx.data(|data| data.get_temp::<(Panel, Rect)>(pending_drag_id())) else { return };
ctx.data_mut(|data| data.remove::<(Panel, Rect)>(pending_drag_id()));
if ctx.input(|input| input.pointer.primary_down()) {
craft_ui::docking::begin_drag(ctx, dock_area, panel, title);
}
}
/// A rail popup and its dismissing press cannot start a paint stroke or move a decal
pub(crate) fn blocks_paint_input(app: &TextureCraftApp, ctx: &egui::Context) -> bool {
let closing_id = area_id().with("closing");
@@ -196,13 +181,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
// The floating window opens where the popup was, at its size
app.ui.rail_panel = None;
if let Some(rect) = shown {
app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]);
app.ui.dock.float_at(panel, rect);
}
} else if let Some(title) = dragged_from {
// The floating window opens where the popup was
app.ui.rail_panel = None;
let rect = shown.unwrap_or(title);
app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]);
ctx.data_mut(|data| data.insert_temp(pending_drag_id(), (panel, title)));
app.ui.dock.float_at(panel, shown.unwrap_or(title));
}
}
+3 -3
View File
@@ -39,7 +39,7 @@ fn environment_cache_retains_source_identity_until_replaced() {
// The harness draws once; parallel translation tests must not change its language mid-frame
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state();
let mut app = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state();
app.session.doc.project.display.environment = "resource:environment".into();
let source = Arc::new(ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0]; 2], false));
let original_source = Arc::downgrade(&source);
@@ -71,7 +71,7 @@ fn environment_cache_retains_source_identity_until_replaced() {
#[test]
fn a_new_display_background_restarts_the_render() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state();
let mut app = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state();
let before = super::key(&app, "scene", (64, 64));
assert_eq!(super::key(&app, "scene", (64, 64)), before);
@@ -109,7 +109,7 @@ fn gpu_app() -> Option<crate::TextureCraftApp> {
let mut app = egui_kittest::Harness::builder()
.with_size(egui::vec2(800.0, 600.0))
.renderer(WgpuTestRenderer::from_render_state(render_state))
.build_eframe(|context| crate::TextureCraftApp::new(context, session()))
.with_context_setup(crate::framework::install_headless).build_eframe(|context| crate::TextureCraftApp::new(context, session()))
.into_state();
app.session.update();
for cache in &mut app.session.caches {
+2 -2
View File
@@ -44,8 +44,8 @@ fn pick_with(ui: &mut Ui, id: Id, linear: &mut [f32; 3], button: impl FnOnce(&mu
pick.target = if picking { None } else { Some(id) };
} else if picking {
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
let (clicked, escaped, pointer) =
ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos()));
let (clicked, pointer) = ui.input(|input| (input.pointer.primary_clicked(), input.pointer.interact_pos()));
let escaped = crate::framework::escape_pressed(ui.ctx());
if escaped {
pick.target = None;
} else if clicked && let Some(point) = pointer {
+4 -4
View File
@@ -1,6 +1,5 @@
//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree
use craft_ui::layout::{ResizeHandle, ResizeHandleStyle, SplitLayout, split_rect};
use craft_behavior::flow::Axis;
use craft_behavior::dock::SplitSize;
use egui::{Rect, RichText, Ui, UiBuilder};
@@ -8,6 +7,7 @@ use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use crate::TextureCraftApp;
use crate::pane_split::{ResizeHandle, ResizeHandleStyle, SplitLayout, split_rect};
use crate::i18n::{n_, tr};
use crate::saved_search::SavedSearch;
use crate::shelf::TABS;
@@ -105,12 +105,12 @@ fn splitter(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) -> Option<SplitL
if available_points > 2.0 * minimum_points {
let colors =
ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill };
let resize = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors)
let delta = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors)
.hit_margin(0.0)
.value(layout.first_size(), minimum_points..=available_points - minimum_points)
.show(ui);
if resize.delta != 0.0
&& let Some(SplitSize::Ratio(share)) = layout.resized(size, resize.delta, minimum_points)
if delta != 0.0
&& let Some(SplitSize::Ratio(share)) = layout.resized(size, delta, minimum_points)
{
app.ui.shelf_panes_split = share;
layout = split_rect(rect, axis, SplitSize::Ratio(share), SPLITTER_HEIGHT_POINTS, minimum_points)?;
+255
View File
@@ -0,0 +1,255 @@
//! 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 keyboard layout learned so far: what a press stands for as a chord.
pub(crate) fn layout(&self) -> &Layout {
&self.layout
}
/// 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]);
}
}
+25 -3
View File
@@ -324,9 +324,21 @@ 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: signature
/// takes the proportional faces and semibold TextureCraft's own semibold list. 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();
let semibold = fonts.families.get(&FontFamily::Name(SEMIBOLD.into())).cloned().unwrap_or_else(|| proportional.clone());
fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional);
fonts.families.insert(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()), semibold);
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
@@ -371,8 +383,18 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) {
v.selection.stroke = Stroke::new(1.0, t.text_strong);
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;
+63 -156
View File
@@ -1,8 +1,9 @@
//! The strip at the top of the window: the app icon at the very left, the menus and the mode label,
//! and the window's title bar unless the system draws one. As the title bar its empty space moves
//! the window and follows the system's double-click setting (craft-window's `title_bar`), and on a
//! window without an OS frame it also has the minimize, maximize/restore and close buttons and
//! invisible resize zones along the window's edges.
//! and the window's title bar unless the system draws one. As the title bar it is craft-ui's
//! `shell::TitleBar`: its free area moves the window and follows the system's double-click
//! setting, and on a window without an OS frame it has the caption buttons of the desktop's
//! layout; the window keeps invisible resize zones along its edges where the runtime does not
//! answer the window's hit test itself (everywhere but Windows).
//!
//! Who draws the frame is decided once at startup ([`TitleBar::decide`]): Windows draws no OS
//! frame, macOS keeps its traffic lights over the strip (a full-size content view with a hidden
@@ -11,12 +12,14 @@
//! overrides that, and Settings › Interface › System title bar brings the OS frame back on the
//! next start. The web build has no window frame: the strip is the menu bar.
use craft_window::{Button, Frame, Layout};
use craft_ui::contract::ShowContainer as _;
use craft_ui::runtime::windows::WindowHost;
use craft_window::policy::{Decision, TitleBarPref};
use craft_window::{Frame, Layout};
use egui::emath::GuiRounding as _;
use egui::{Align, Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2};
use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Ui, ViewportCommand, pos2, vec2};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
/// Who draws the window's title bar.
@@ -31,13 +34,9 @@ pub enum TitleBar {
App(Layout),
}
/// One caption button: as wide as Windows' own.
pub const BUTTON_WIDTH: f32 = 46.0;
/// The room at the strip's left for the macOS traffic lights (their width and the gaps around them).
const TRAFFIC_LIGHTS: f32 = 78.0;
/// The app icon's side, in points.
const ICON: f32 = 16.0;
/// The space between the strip's edges (or its caption buttons) and its content.
/// The space between the icon and the menus.
const PAD: f32 = 8.0;
/// Resize zone thickness along an edge, and the side of a corner zone.
const EDGE: f32 = 5.0;
@@ -53,12 +52,28 @@ const ICONS: [(f32, &[u8]); 5] = [
(64.0, include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png")),
];
/// The override variable's prefix: `TEXTURECRAFT_TITLEBAR`.
const PREFIX: craft_window::Prefix = craft_window::Prefix::new("TEXTURECRAFT");
impl TitleBar {
/// Decide who draws the title bar; call once at startup, before the window is created.
/// Decide who draws the title bar; call once at startup, before the window is created, and
/// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`).
/// `system` is Settings › Interface › System title bar.
pub fn decide(system: bool) -> TitleBar {
let choice = craft_window::Choice::probe(craft_window::Prefix::new("TEXTURECRAFT"));
Self::from_choice(choice.frame(), choice.overridden(), system)
pub fn decide(system: bool) -> Decision {
let choice = craft_window::Choice::probe(PREFIX);
let wanted = Self::from_choice(choice.frame(), choice.overridden(), system);
let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated };
craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref)
}
/// The bar a decided `frame` gives.
pub fn of(frame: &craft_window::policy::Frame) -> TitleBar {
use craft_window::policy::Frame as Decided;
match frame {
Decided::Native => TitleBar::System,
Decided::Inset(_) => TitleBar::Integrated,
Decided::Integrated(captions) => TitleBar::App(captions.layout.clone()),
}
}
/// `TEXTURECRAFT_TITLEBAR` (`overridden`) wins, then the System title bar setting. Otherwise
@@ -77,17 +92,6 @@ impl TitleBar {
}
}
/// `builder` with this frame: decorations off for the app's own, and on macOS the content
/// under a transparent title bar without its title.
pub fn viewport(&self, builder: egui::ViewportBuilder) -> egui::ViewportBuilder {
let frame = match self {
TitleBar::App(layout) => Frame::App(layout.clone()),
_ => Frame::Desktop,
};
let builder = craft_window::decorate(builder, &frame);
if *self == TitleBar::Integrated { builder.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false) } else { builder }
}
/// The name `ui.inspect` reports: `app`, `integrated` or `system`.
pub fn name(&self) -> &'static str {
match self {
@@ -98,38 +102,48 @@ impl TitleBar {
}
}
/// `builder` with the decided frame: decorations off for the app's own, and on macOS the content
/// under a transparent title bar without its title.
pub fn viewport(decision: &Decision, builder: egui::ViewportBuilder) -> egui::ViewportBuilder {
craft_window::policy::apply(builder, &decision.frame)
}
/// The strip's height: the body text with room around it, 28 to 32 points (so the macOS traffic
/// lights and Windows-sized caption buttons fit it).
pub fn height(ui: &Ui) -> f32 {
(ui.text_style_height(&egui::TextStyle::Body) + 14.0).clamp(28.0, 32.0)
}
/// The strip: menus between the app icon and the mode label, the window buttons at the ends the
/// layout names, and as the title bar its empty space moving the window.
/// The strip: the app icon, then the menus. Where the system draws the frame it is the menu bar;
/// otherwise it is the window's title bar (craft-ui's), with the caption buttons where the frame
/// has them and resize zones along the window's edges.
pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let bar = app.title_bar.clone();
let (left, right) = match &bar {
TitleBar::App(layout) => (layout.left.as_slice(), layout.right.as_slice()),
_ => (&[][..], &[][..]),
};
egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| {
let rect = ui.max_rect();
// First, so the strip's controls drawn over it keep their own clicks.
if bar != TitleBar::System {
craft_window::title_bar::empty_area(ui, rect);
}
let ends = |n: usize| n as f32 * BUTTON_WIDTH;
let inset = if bar == TitleBar::Integrated { TRAFFIC_LIGHTS } else { ends(left.len()) + PAD };
let content = Rect::from_min_max(pos2(rect.left() + inset, rect.top()), pos2(rect.right() - ends(right.len()) - PAD, rect.bottom()));
ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(Align::Center)), |ui| {
paint_icon(ui);
crate::menus::menu_bar(app, ui);
let frame = WindowHost::of(ui.ctx()).frame();
if matches!(frame, craft_window::policy::Frame::Native) {
egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| {
let rect = ui.max_rect();
let content = Rect::from_min_max(pos2(rect.left() + PAD, rect.top()), pos2(rect.right() - PAD, rect.bottom()));
ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
paint_icon(ui);
crate::menus::menu_bar(app, ui);
});
});
caption_buttons(ui, left, rect.left(), rect);
caption_buttons(ui, right, rect.right() - ends(right.len()), rect);
return;
}
egui::Panel::top("menu_bar").show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| {
let bar = craft_ui::shell::TitleBar::new()
.show(ui, |ui, _| {
paint_icon(ui);
crate::menus::menu_bar(app, ui);
})
.output;
if bar.close_requested {
ui.ctx().send_viewport_cmd(ViewportCommand::Close);
}
});
if matches!(bar, TitleBar::App(_)) {
// Windows' frame answers the resize edges itself (the runtime's hit test).
if matches!(frame, craft_window::policy::Frame::Integrated(_)) && !cfg!(windows) {
resize_zones(ui);
}
}
@@ -166,92 +180,6 @@ fn maximized(ctx: &egui::Context) -> bool {
ctx.input(|i| i.viewport().maximized.unwrap_or(false))
}
/// Caption button ids (stable, so tests and agents can find them).
fn caption_id(b: Button) -> Id {
Id::unique(("titlebar_caption", b as u8))
}
/// `buttons` from `x` rightwards, the strip's full height, flush with its top so a maximized
/// window's corner hits the outermost one.
fn caption_buttons(ui: &mut Ui, buttons: &[Button], x: f32, bar: Rect) {
let tk = Tokens::get(ui.ctx());
let max = maximized(ui.ctx());
let focused = ui.input(|i| i.viewport().focused.unwrap_or(true));
for (i, &b) in buttons.iter().enumerate() {
let r = Rect::from_min_size(pos2(x + i as f32 * BUTTON_WIDTH, bar.top()), vec2(BUTTON_WIDTH, bar.height()));
let resp = ui.interact(r, caption_id(b), Sense::click());
let tip = match b {
Button::Minimize => tr("Minimize"),
Button::Maximize if max => tr("Restore"),
Button::Maximize => tr("Maximize"),
Button::Close => tr("Close"),
};
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip));
let close = b == Button::Close;
let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) {
(true, _) if close => tk.danger.gamma_multiply(0.8),
(_, true) if close => tk.danger,
(true, _) => tk.button,
(_, true) => tk.row_hover,
_ => Color32::TRANSPARENT,
};
ui.painter().rect_filled(r, 0.0, fill);
// White on the red, as every system's close button; dimmed while the window is inactive.
let ink = if close && resp.hovered() {
Color32::WHITE
} else if focused {
tk.text
} else {
tk.text_dim
};
paint_glyph(ui, b, max, r.center(), ink);
if resp.on_hover_text(tip).clicked() {
ui.ctx().send_viewport_cmd(match b {
Button::Minimize => ViewportCommand::Minimized(true),
Button::Maximize => ViewportCommand::Maximized(!max),
// The same request as the system's close button.
Button::Close => ViewportCommand::Close,
});
}
}
}
/// The 10-point line glyphs, one physical pixel wide per whole step of the screen's scale and on
/// pixel centres, so they stay crisp at any scale.
fn paint_glyph(ui: &Ui, b: Button, maximized: bool, at: egui::Pos2, ink: Color32) {
let ppp = ui.ctx().pixels_per_point();
let px = ppp.round().max(1.0);
let stroke = Stroke::new(px / ppp, ink);
// An odd width centres the line in a pixel, an even one on a pixel edge.
let snap = |v: f32| if px as u32 % 2 == 1 { v.round_to_pixel_center(ppp) } else { v.round_to_pixels(ppp) };
let g = Rect::from_min_max(pos2(snap(at.x - 5.0), snap(at.y - 5.0)), pos2(snap(at.x + 5.0), snap(at.y + 5.0)));
let p = ui.painter();
match b {
Button::Minimize => {
p.line_segment([g.left_center(), g.right_center()].map(|q| pos2(q.x, snap(q.y))), stroke);
}
// Restore: a front square with the corner of the one behind it.
Button::Maximize if maximized => {
let front = Rect::from_min_max(pos2(g.left(), snap(g.top() + 2.0)), pos2(snap(g.right() - 2.0), g.bottom()));
p.rect_stroke(front, 0.0, stroke, egui::StrokeKind::Middle);
let (l, t) = (snap(g.left() + 2.0), front.top());
p.line(
vec![pos2(l, t), pos2(l, g.top()), g.right_top(), pos2(g.right(), snap(g.bottom() - 2.0)), pos2(front.right(), snap(g.bottom() - 2.0))],
stroke,
);
}
Button::Maximize => {
p.rect_stroke(g, 0.0, stroke, egui::StrokeKind::Middle);
}
Button::Close => {
p.line_segment([g.left_top(), g.right_bottom()], stroke);
p.line_segment([g.right_top(), g.left_bottom()], stroke);
}
}
}
/// The edge and corner zones of a window with content rect `w`: (zone, direction, cursor). Corners
/// come last so they win where they overlap the edges.
fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] {
use ResizeDirection::*;
let (e, c) = (EDGE, CORNER);
@@ -292,17 +220,6 @@ fn resize_zones(ui: &mut Ui) {
/// Once per frame after the UI, on macOS with the integrated strip: the traffic lights centred on
/// the strip, inset from its left as far as from its top, and AppKit's `movable` flag following
/// what is under the pointer (`movable` keeps the value last set).
#[cfg(target_os = "macos")]
pub fn sync_native(bar: &TitleBar, ui: &Ui, frame: &eframe::Frame, movable: &mut Option<bool>) {
if *bar != TitleBar::Integrated {
return;
}
let h = height(ui);
// AppKit's buttons are 14 points tall.
frame.set_traffic_lights_position(ui.ctx(), egui::Rangef::new(0.0, h), (h - 14.0) / 2.0);
craft_window::title_bar::sync_movable(ui.ctx(), movable);
}
#[cfg(test)]
mod tests {
use super::*;
@@ -331,16 +248,6 @@ mod tests {
assert_eq!(desktop, expected);
}
#[test]
fn only_the_app_frame_turns_decorations_off() {
let b = TitleBar::App(Layout::default()).viewport(egui::ViewportBuilder::default());
assert_eq!(b.decorations, Some(false));
let b = TitleBar::Integrated.viewport(egui::ViewportBuilder::default());
assert_eq!((b.decorations, b.fullsize_content_view, b.title_shown), (Some(true), Some(true), Some(false)));
let b = TitleBar::System.viewport(egui::ViewportBuilder::default());
assert_eq!((b.decorations, b.fullsize_content_view), (Some(true), None));
}
#[test]
fn resize_corners_win_over_edges() {
let w = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0));
+3 -3
View File
@@ -321,10 +321,10 @@ pub(crate) mod tests {
fn moved_panels() -> Dock {
let mut workspace = default_workspace();
let actions = [
Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: DockPlacement::Tab { before: None } },
Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] },
Action::move_beside(Panel::Layers, Panel::Assets, DockPlacement::tab(None)),
Action::float(Panel::Properties, egui::Rect::from_min_size(egui::pos2(900.0, 120.0), egui::vec2(320.0, 400.0))),
];
workspace.apply_all(actions, permissions).unwrap();
workspace.apply_all(actions, false, permissions).unwrap();
let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap());
assert!(!dock.replaced_unreadable(), "the moved layout is valid");
+41 -18
View File
@@ -1,8 +1,10 @@
//! Software updates on the desktop: the check at start, Help > Check for Updates and the update
//! prompt. An update that is ready starts its install helper when the app is dropped at exit.
//! prompt, as craft-update's dialogs on the app's [`DialogHost`](craft_ui::dialog::DialogHost). An
//! update that is ready starts its install helper when the app is dropped at exit.
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::TextureCraftApp;
@@ -47,9 +49,9 @@ fn holds_keyboard(status: &Status, prompt_open: bool) -> bool {
pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) {
let rt = &mut app.updates_rt;
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
rt.updater.check_now();
} else if rt.startup_check {
rt.updater.check_at_start(ctx);
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
}
@@ -67,21 +69,42 @@ fn safe_to_close(app: &TextureCraftApp) -> bool {
!app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none()
}
/// One pass of the update flow, before the dialog host runs: answers the result dialog closed in
/// the last pass, drives the update prompt, and keeps the result dialog open and current while the
/// updater has something to report.
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
let safe = safe_to_close(app);
match app.updates_rt.updater.show_if(ctx, safe) {
// 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 it is safe to
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
Some(DialogResult::Ok(CheckChoice::Update)) => {
app.updates_rt.updater.request_install(safe);
}
Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
// Closing the dialog dismisses the outcome it showed
Some(_) => app.updates_rt.updater.dismiss_status(),
None => {}
}
match app.updates_rt.updater.run(&mut app.framework_dialogs, safe) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Action::None => {}
_ => {}
}
let rt = &mut app.updates_rt;
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) {
CheckResultResponse::None => {}
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => rt.check_requested = true,
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
}
let updater = &app.updates_rt.updater;
let shows = result_window_shows(updater.status(), updater.prompt_open());
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
let dialogs = &mut app.framework_dialogs;
if shows && !dialogs.is_open::<UpdateCheckDialog>() {
dialogs.open(UpdateCheckDialog::new(env!("CARGO_PKG_VERSION")));
} else if !shows && dialogs.is_open::<UpdateCheckDialog>() {
dialogs.cancel::<UpdateCheckDialog>(ctx);
}
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
}
@@ -123,7 +146,7 @@ mod tests {
let root = std::env::temp_dir().join(format!("texturecraft-updates-{}-{test}", std::process::id()));
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.modified = modified;
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().updates_rt.updater =
Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json"));
h.run_steps(2);
@@ -177,7 +200,7 @@ mod tests {
let mut h = harness(false, "prompt", ask);
offer(&mut h);
assert!(h.state().updates_rt.updater.prompt_open());
h.get_by_label("LATER").click();
h.get_by_label("Later").click();
h.run_steps(2);
assert!(!h.state().updates_rt.updater.prompt_open());
}
@@ -193,7 +216,7 @@ mod tests {
h.key_press(egui::Key::F8);
h.step();
assert_eq!(h.state().ui.mode, Mode::Painting, "the prompt holds the keyboard");
h.get_by_label("LATER").click();
h.get_by_label("Later").click();
h.run_steps(2);
assert!(!crate::docking::input_blocked(h.state(), &h.ctx));
h.key_press(egui::Key::F8);
@@ -216,7 +239,7 @@ mod tests {
h.key_press(egui::Key::Backspace);
h.step();
assert_eq!(points(&h), 2, "the prompt holds the keyboard");
h.get_by_label("LATER").click();
h.get_by_label("Later").click();
h.run_steps(2);
h.key_press(egui::Key::Backspace);
h.step();
+7 -7
View File
@@ -2612,7 +2612,7 @@ mod tests {
for tool in [Tool::Paint, Tool::PolygonFill] {
let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let app = harness.state_mut();
app.session.tool.tool = tool;
let history = app.session.history_labels().len();
@@ -2641,7 +2641,7 @@ mod tests {
// The harness draws the UI, so another test's interface language must not be active
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let app = harness.state_mut();
app.ui.mode = crate::state::Mode::Painting;
app.session.view = ViewMode::Mask(LayerId(7));
@@ -2667,7 +2667,7 @@ mod tests {
execute(&mut session, "layer.add.fill", &json!(null)).unwrap();
let effect = texturecraft_engine::core::LayerId(execute(&mut session, "mask.add.colorSelection", &json!(null)).unwrap()["effect"].as_u64().unwrap());
session.target = StackTarget::Effect(effect);
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(2);
crate::id_color_pick::IdColorPick::start(harness.state_mut(), effect, None);
@@ -2684,7 +2684,7 @@ mod tests {
fn a_waiting_eyedropper_keeps_a_2d_view_click_from_painting() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.state_mut().session.tool.tool = Tool::PolygonFill;
harness.run_steps(4);
@@ -2730,7 +2730,7 @@ mod tests {
let effect = texturecraft_engine::core::LayerId(result["committed"]["effect"].as_u64().unwrap());
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") };
paths.resize(8, paths[0].clone());
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let context = egui::Context::default();
let mut previous = Vec::<std::sync::Weak<Vec<Vec<Option<Vec3>>>>>::new();
@@ -2779,7 +2779,7 @@ mod tests {
Session::new_project("Decal selection", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0));
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = builder.with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
let mut png = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
@@ -2929,7 +2929,7 @@ mod tests {
// Hold the language lock while drawing the harness
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let app = harness.state_mut();
app.ui.mode = crate::state::Mode::Baking;
let before = bake_visualization(app).unwrap();
+4 -4
View File
@@ -435,7 +435,7 @@ mod tests {
#[test]
fn mesh_picks_only_update_the_current_new_project_request() {
let session = Session::closed().unwrap();
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let app = harness.state_mut();
crate::new_project_advanced::open(app);
app.ui.new_project.mesh_request_id = 2;
@@ -457,7 +457,7 @@ mod tests {
#[test]
fn environment_pick_after_close_does_not_edit_the_placeholder() {
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let old_project_id = harness.state().session.project_id;
@@ -479,7 +479,7 @@ mod tests {
#[test]
fn environment_pick_from_replaced_project_does_not_edit_the_new_project() {
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let old_project_id = harness.state().session.project_id;
@@ -497,7 +497,7 @@ mod tests {
#[test]
fn bake_mesh_picks_after_close_do_not_edit_the_placeholder() {
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let old_project_id = harness.state().session.project_id;
assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some());
let cage = harness.state().session.mesh_obj_bytes().unwrap();
+93 -2
View File
@@ -1,8 +1,7 @@
//! 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 egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, StrokeKind, Ui, Vec2, vec2};
use crate::drawn_icon::DrawnIcon;
use crate::i18n::tr;
@@ -279,6 +278,98 @@ pub fn icon_badge_dropdown_button(ui: &mut Ui, icon: &str, badge: &str, label: &
})
}
/// The background, border and icon colour of an icon button in one interaction state.
#[derive(Clone, Copy, Debug, PartialEq)]
struct ButtonVisuals {
fill: Color32,
stroke: Stroke,
icon: Color32,
}
/// The look of an icon button in each state. Selection takes precedence over press and hover.
#[derive(Clone, Copy, Debug)]
struct IconButtonStyle {
normal: ButtonVisuals,
hovered: ButtonVisuals,
/// `None` keeps the hover or normal look while pressed.
pressed: Option<ButtonVisuals>,
selected: ButtonVisuals,
corner_radius: CornerRadius,
/// An inset outline while the button has keyboard focus.
focus_stroke: Stroke,
}
impl IconButtonStyle {
fn visuals(&self, selected: bool, hovered: bool, pressed: bool) -> ButtonVisuals {
if selected {
self.selected
} else if let Some(visuals) = self.pressed.filter(|_| pressed) {
visuals
} else if hovered {
self.hovered
} else {
self.normal
}
}
}
/// An icon-only button painted in TextureCraft's own colours. The label is its accessible name; the caller paints
/// the icon, attaches a tooltip and acts on the response. Selection is the caller's.
struct IconButton<'a> {
label: &'a str,
size: Vec2,
selected: bool,
style: &'a IconButtonStyle,
}
impl<'a> IconButton<'a> {
fn new(label: &'a str, size: Vec2, style: &'a IconButtonStyle) -> Self {
Self { label, size, selected: false, style }
}
fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// Paints the button and returns its response. `paint_icon` gets the button's rect and the icon tint. A
/// non-finite, non-positive or oversized (over 4096 points) size gives an inert zero-size response.
fn show(self, ui: &mut Ui, paint_icon: impl FnOnce(&Ui, Rect, Color32)) -> Response {
let valid = self.size.is_finite() && self.size.x > 0.0 && self.size.y > 0.0 && self.size.x <= 4096.0 && self.size.y <= 4096.0;
let (rect, response) = ui.allocate_exact_size(if valid { self.size } else { Vec2::ZERO }, if valid { Sense::click() } else { Sense::hover() });
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, valid && ui.is_enabled(), self.selected, self.label));
if !valid {
return response;
}
let visuals = self.style.visuals(self.selected, response.hovered(), response.is_pointer_button_down_on());
let stroke = bounded_stroke(visuals.stroke, rect);
if visuals.fill != Color32::TRANSPARENT {
ui.painter().rect_filled(rect, self.style.corner_radius, visuals.fill);
}
if !stroke.is_empty() {
ui.painter().rect_stroke(rect, self.style.corner_radius, stroke, StrokeKind::Inside);
}
paint_icon(ui, rect, visuals.icon);
if response.has_focus() && rect.width() > 4.0 && rect.height() > 4.0 {
let focus_rect = rect.shrink(2.0);
let stroke = bounded_stroke(self.style.focus_stroke, focus_rect);
if !stroke.is_empty() {
ui.painter().rect_stroke(focus_rect, self.style.corner_radius, stroke, StrokeKind::Inside);
}
}
response
}
}
/// `stroke` no wider than half of `rect`'s smaller side; none when its width is not positive.
fn bounded_stroke(stroke: Stroke, rect: Rect) -> Stroke {
if stroke.width.is_finite() && stroke.width > 0.0 {
Stroke::new(stroke.width.min(rect.width().min(rect.height()) * 0.5), stroke.color)
} else {
Stroke::NONE
}
}
/// Transparent at rest, a hover well, and the active-tool well when pressed or selected
fn icon_button_style(tokens: &Tokens) -> IconButtonStyle {
let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon };
+8 -16
View File
@@ -82,26 +82,18 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved
app.session.modified
}
/// The close decision, once per frame in `logic` (which also runs while the window is minimized):
/// a close with unsaved changes waits on the dialog, in a window brought back so it can be
/// answered. A close nothing holds open quits through the platform's own path (craft-quit).
pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) {
let closing = ctx.input(|i| i.viewport().close_requested());
/// The close decision, which the runtime asks for when the root window was asked to close (it runs in `logic`,
/// also while the window is minimized): a close with unsaved changes waits on the dialog (`true`), and the runtime
/// brings the window back so it can be answered. A close nothing holds open goes ahead through the platform's own
/// quit.
pub(crate) fn close_requested(app: &mut TextureCraftApp) -> bool {
// A stroke still open at the close, or released in this frame, is a change to ask about.
if closing
&& app.session.stroke_active()
if app.session.stroke_active()
&& let Err(error) = app.session.end_stroke()
{
app.toast(error.to_string(), true);
}
if closing && ask_to_save(app, crate::state::Unsaved::Quit) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
if ctx.input(|i| i.viewport().minimized == Some(true)) {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
}
craft_quit::on_close_request(ctx);
ask_to_save(app, crate::state::Unsaved::Quit)
}
/// Quitting, opening or closing a project with unsaved changes asks whether to save them first
@@ -711,7 +703,7 @@ mod tests {
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// Match English labels independently of the system locale
h.state_mut().ui.prefs.language = "en".into();
+1 -1
View File
@@ -19,7 +19,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
}
session.view = ViewMode::UvChecker;
let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(3);
harness
+1 -1
View File
@@ -9,7 +9,7 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout};
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.run_steps(4);
harness
+1 -1
View File
@@ -18,7 +18,7 @@ const STARTUP_FRAMES: usize = 4;
#[test]
fn display_picks_the_tone_mapping_from_a_dropdown() {
let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The labels below are English; a first run would speak the system's language
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().ui.dock.focus(Panel::Display);
+1 -1
View File
@@ -17,7 +17,7 @@ fn changed_params() -> AlphaParams {
/// The app showing the Alpha tab of Properties, with `brush`
fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().session.tool.brush = brush;
harness.state_mut().ui.props_tab = PropsTab::Alpha;
+1 -1
View File
@@ -23,7 +23,7 @@ fn anchor_harness() -> (Harness<'static, TextureCraftApp>, LayerId, LayerId, Lay
execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap();
let reader = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": top, "anchor": anchor.0})).unwrap()["effect"].as_u64().unwrap());
execute(&mut session, "layer.select", &json!({"layer": low, "target": anchor.0})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, anchor, LayerId(top.as_u64().unwrap()), reader)
+1 -1
View File
@@ -11,7 +11,7 @@ use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp};
/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`.
fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc<Progress>) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let progress = Arc::new(Progress::new());
let (tx, receiver) = std::sync::mpsc::channel();
+3 -3
View File
@@ -12,7 +12,7 @@ fn harness(map: Option<BakedMap>) -> Harness<'static, TextureCraftApp> {
session.doc.project.texture_sets[0].bake = Default::default();
session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64;
session.doc.project.texture_sets[0].bake.maps.select(map);
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
harness.state_mut().ui.dock.focus(Panel::MeshMapSettings);
@@ -221,7 +221,7 @@ fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() {
256,
)
.unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
let before = harness.state().session.doc.project.clone();
@@ -272,7 +272,7 @@ fn bake_texture_sets_list_uv_tiles_and_their_resolutions() {
.unwrap();
texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap();
let before = session.doc.project.clone();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
+2 -2
View File
@@ -17,7 +17,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
texture_set.bake.maps.select([BakedMap::Id]);
}
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
harness.state_mut().ui.dock.focus(Panel::MeshMapBakers);
@@ -174,7 +174,7 @@ fn a_partial_bake_does_not_count_preserved_unchecked_maps() {
set.bake.common.resolution = BakeResolution::R64;
set.bake.maps.select([BakedMap::Id]);
set.bake_excluded_tiles.insert(1002);
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.state_mut().start_bake(vec![0]);
+2 -2
View File
@@ -22,7 +22,7 @@ fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2,
#[test]
fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let c = h.state().viewport_rect.center();
let (brush, yaw, history) = {
@@ -50,7 +50,7 @@ fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() {
fn app(layout: texturecraft_ui_egui::state::ViewLayout) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.layout = layout;
h.run_steps(4);
h
@@ -69,7 +69,7 @@ fn changed_brush() -> BrushSettings {
/// The app showing the brush in Properties, set to `brush`
fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The labels below are English; a first run would speak the system's language
harness.state_mut().ui.prefs.language = "en".into();
+2 -2
View File
@@ -11,7 +11,7 @@ use texturecraft_ui_egui::TextureCraftApp;
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
@@ -108,7 +108,7 @@ fn alt_shift_drag_orbits_in_quarter_turns() {
/// A harness whose frames are 10 ms apart, so a 0.35 s glide spans about 35 frames and a drag fits inside it.
fn slow_glide_harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(0.01).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
+1 -1
View File
@@ -15,7 +15,7 @@ const MARKER_STROKE: f32 = 1.2;
fn clone_app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.layout = ViewLayout::Only2D;
execute(&mut harness.state_mut().session, "tool.clone", &serde_json::Value::Null).unwrap();
harness.run_steps(4);
+1 -1
View File
@@ -10,7 +10,7 @@ use texturecraft_ui_egui::state::Unsaved;
fn harness(modified: bool) -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.modified = modified;
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
@@ -55,7 +55,7 @@ fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session,
fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
let (session, effect) = color_selection_session(with_id_map);
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
(harness, effect)
}
@@ -294,7 +294,7 @@ fn removing_an_image_during_id_picking_falls_back_to_material() {
#[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered views"]
fn color_selection_snapshots_and_quick_mask_pick() {
let (session, _) = color_selection_session(true);
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| {
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| {
let mut app = TextureCraftApp::new(context, session);
app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D;
app
@@ -393,7 +393,7 @@ fn the_background_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click
fn the_id_mask_slot_picks_a_texture_and_its_x_goes_back_to_the_mesh_map() {
let (mut session, effect) = color_selection_session(true);
let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click();
@@ -419,7 +419,7 @@ fn tile_is_current(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool
fn reading_the_mesh_map_shows_no_tile_as_the_current_id_mask() {
let (mut session, effect) = color_selection_session(true);
let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
assert_eq!(selection(&harness, effect).id_map, None, "the selection reads the ID mesh map");
@@ -457,7 +457,7 @@ fn the_invert_tooltip_shows_right_above_its_button() {
fn invert_tooltip_snapshot() {
let (session, _) = color_selection_session(true);
let mut harness =
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session));
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
let invert = harness.get_by_role_and_label(Role::Button, "Invert").rect();
harness.hover_at(invert.center());
@@ -474,7 +474,7 @@ fn a_hand_picked_id_mask_picks_without_a_bake() {
session.doc.baked.clear();
let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": texture})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
harness.get_by_label(PICK_COLOR).click();
@@ -496,7 +496,7 @@ fn clearing_the_only_id_mask_ends_a_waiting_pick() {
session.doc.baked.clear();
let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": texture})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
harness.get_by_label(PICK_COLOR).click();
harness.run_steps(SETTLE_FRAMES);
+1 -1
View File
@@ -17,7 +17,7 @@ fn compare_harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
let layer = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap()["layer"].clone();
let effect = LayerId(execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].as_u64().unwrap());
execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, effect)
@@ -18,7 +18,7 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
session.update();
let builder = Harness::builder().with_size(egui::vec2(1600.0, 1200.0));
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.dock.close(Panel::Layers);
harness.state_mut().ui.dock.close(Panel::TextureSetSettings);
harness.state_mut().ui.dock.focus(Panel::Properties);
@@ -13,7 +13,7 @@ const SETTLE: usize = 3;
fn app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h.state_mut().ui.dock.focus(Panel::Display);
@@ -24,7 +24,7 @@ fn display(harness: &Harness<'_, TextureCraftApp>) -> DisplaySettings {
/// The app with Display Settings open from the rail and the Post effects section unfolded
fn app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(4);
harness
+4 -4
View File
@@ -37,7 +37,7 @@ fn dragging_an_effect_row_reorders_its_stack() {
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C"));
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let order =
|harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
@@ -66,7 +66,7 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() {
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect");
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
@@ -112,7 +112,7 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() {
let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect");
execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
@@ -151,7 +151,7 @@ fn an_effect_rows_blending_options_reach_every_channel() {
let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect");
execute(&mut session, "effect.set", &json!({"effect": effect, "channel": "baseColor", "blend": "Multiply"})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
+1 -1
View File
@@ -21,7 +21,7 @@ fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) {
})
.unwrap();
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
(harness, effect)
}
+1 -1
View File
@@ -8,7 +8,7 @@ use texturecraft_engine::Session;
use texturecraft_ui_egui::{TextureCraftApp, docking::Panel, menus};
fn app() -> Harness<'static, TextureCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|cc| TextureCraftApp::new(cc, Session::closed().unwrap()));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, Session::closed().unwrap()));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h
+1 -1
View File
@@ -7,7 +7,7 @@ use texturecraft_engine::Session;
use texturecraft_ui_egui::{TextureCraftApp, menus};
fn harness(session: Session) -> Harness<'static, TextureCraftApp> {
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The exact-text checks below need English, whatever the OS language is
harness.state_mut().ui.prefs.language = "en".into();
+2 -2
View File
@@ -8,7 +8,7 @@ use texturecraft_ui_egui::TextureCraftApp;
/// The Export textures window open on SETTINGS
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h.state_mut().ui.windows.export = true;
@@ -138,7 +138,7 @@ fn export_writes_the_chosen_type_and_depth() {
#[test]
fn an_old_hidden_bit_depth_is_not_exported() {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
// Saved by an older build: "From template" with 16 bits
@@ -9,7 +9,7 @@ use texturecraft_ui_egui::state::{FileType, MapExport, SetExport};
/// The Export textures window open on the first texture set's page
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h.state_mut().ui.windows.export = true;
+1 -1
View File
@@ -11,7 +11,7 @@ const OPENPBR: &str = "OpenPBR (separate maps)";
/// The Export textures window writing into a scratch folder of its own for `name`
fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut app_harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut app_harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
app_harness.state_mut().ui.prefs.language = "en".into();
app_harness.run_steps(4);
+2 -2
View File
@@ -12,7 +12,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
}
fn harness_with_session(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h.state_mut().ui.windows.export = true;
@@ -269,7 +269,7 @@ fn reset_all_then_cancel_restores_the_ticks_and_overrides() {
#[test]
fn ticks_saved_before_settings_named_their_project_are_kept() {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
+1 -1
View File
@@ -10,7 +10,7 @@ use texturecraft_ui_egui::state::{ConsoleLine, ExportJob};
/// The Export textures window writing into a scratch folder of its own for `name`
fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
let dir = std::env::temp_dir().join(format!("tc-export-progress-{name}-{}", std::process::id()));
+1 -1
View File
@@ -8,7 +8,7 @@ use texturecraft_ui_egui::TextureCraftApp;
/// The Export textures window open on SETTINGS
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h.state_mut().ui.windows.export = true;
@@ -14,7 +14,7 @@ use library::Library;
/// The Output templates tab with two user templates, "Alpha tpl" (selected) and "Beta tpl", saved in `library`.
fn harness(library: &Library) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h.state_mut().session.load_export_presets(library.0.clone());
let base = texturecraft_engine::formats::builtin_presets().remove(0);
+1 -1
View File
@@ -26,7 +26,7 @@ impl Drop for Scratch {
/// The Export textures window writing into a scratch folder of its own for `name`
fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, Scratch) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
let dir = std::env::temp_dir().join(format!("tc-export-usd-asset-{name}-{}", std::process::id()));
+1 -1
View File
@@ -13,7 +13,7 @@ use texturecraft_ui_egui::state::Unsaved;
fn harness(modified: bool) -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.modified = modified;
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
@@ -26,7 +26,7 @@ fn a_fill_channel_takes_an_image_from_its_source_picker() {
let name = session.import_resource_bytes("rough.png", png_bytes).unwrap();
let result = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap();
let layer = LayerId(result["layer"].as_u64().unwrap());
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// Use English so first-run locale does not change queried labels
harness.state_mut().ui.prefs.language = "en".into();
@@ -51,7 +51,7 @@ fn the_source_picker_offers_only_images_that_were_decoded() {
// Bytes that are not an image never reach the decoded images
session.doc.resources.insert("broken.png".into(), std::sync::Arc::new(vec![1, 2, 3]));
texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// Use English so first-run locale does not change queried labels
harness.state_mut().ui.prefs.language = "en".into();
@@ -122,7 +122,7 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() {
texturecraft_engine::execute(&mut session, "mask.add.black", &json!({})).unwrap();
let output = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"target": "mask"})).unwrap();
let effect_id = LayerId(output["effect"].as_u64().unwrap());
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(4);
@@ -166,7 +166,7 @@ fn a_normal_image_can_be_marked_directx() {
let out = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap();
let layer = LayerId(out["layer"].as_u64().unwrap());
texturecraft_engine::execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "normal", "image": name})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
+1 -1
View File
@@ -18,7 +18,7 @@ pub(crate) fn fill_app(settings: Value, projection: Option<&str>, tab: Option<&s
if let Some(projection) = projection {
texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap();
}
let mut harness = Harness::builder().with_size(window).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(window).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The labels below are English; a first run would speak the system's language
harness.state_mut().ui.prefs.language = "en".into();
+1 -1
View File
@@ -185,7 +185,7 @@ fn filter_picker_snapshots_and_frame_timings() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, SNAPSHOT_HEIGHT)).wgpu().build_eframe(|cc| {
let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, SNAPSHOT_HEIGHT)).wgpu().with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| {
eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info());
TextureCraftApp::new(cc, session)
});
+1 -1
View File
@@ -29,7 +29,7 @@ pub(crate) fn app_with(filter: &str, target: &str, height: f32) -> (Harness<'sta
execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap();
session.target = StackTarget::Effect(effect);
let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, height)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, height)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(4);
(harness, effect)
+1 -1
View File
@@ -28,7 +28,7 @@ fn folder_harness(with_fill: bool) -> (Harness<'static, TextureCraftApp>, LayerI
LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap())
};
execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "content"})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, folder, fill)
+1 -1
View File
@@ -10,7 +10,7 @@ o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0
fn harness() -> Harness<'static, TextureCraftApp> {
let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
+1 -1
View File
@@ -22,7 +22,7 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
session.update();
let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0));
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.dock.close(Panel::Layers);
harness.state_mut().ui.dock.close(Panel::TextureSetSettings);
harness.state_mut().ui.dock.focus(Panel::Properties);
+1 -1
View File
@@ -11,7 +11,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
session.log.push("first line".into());
session.log.warn(texturecraft_engine::log::DEFAULT_SOURCE, "second line");
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h
+2 -2
View File
@@ -10,7 +10,7 @@ use texturecraft_ui_egui::docking::Panel;
/// Show document history so row clicks exercise the same command dispatch as the application
fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> {
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.dock.focus(Panel::History);
harness.run_steps(4);
harness
@@ -167,7 +167,7 @@ fn clicking_a_history_step_returns_to_it() {
texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap();
}
let done = session.history_labels().len();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.dock.focus(Panel::History);
h.run_steps(4);
let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone();
+2 -2
View File
@@ -18,7 +18,7 @@ const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other
fn app() -> Harness<'static, TextureCraftApp> {
let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
@@ -285,7 +285,7 @@ fn import_resources_snapshot() {
let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
let dir = TempDir::new("import-resources-snapshot");
let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
invoke(&mut h);
+1 -1
View File
@@ -12,7 +12,7 @@ const SEARCH_STEP: f32 = 8.0;
/// The sample project (the ball is set 0, the base set 1) with the Ball active and the paint tool, at 1600 x 960
fn sample_app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
assert_eq!(harness.state().session.ts(), 0);
assert_eq!(harness.state().session.tool.tool, Tool::Paint);
@@ -23,7 +23,7 @@ fn instance_harness(dangling: bool) -> (Harness<'static, TextureCraftApp>, Layer
session.doc.project.layers.get_mut(&instance).unwrap().kind = LayerKind::Instance { source: GONE };
}
execute(&mut session, "layer.select", &json!({"layer": instance.0, "target": "content"})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, instance, source)
@@ -8,7 +8,7 @@ use texturecraft_ui_egui::TextureCraftApp;
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
+2 -2
View File
@@ -9,7 +9,7 @@ use texturecraft_ui_egui::TextureCraftApp;
/// The sample session with its selected layer clicked in the stack, and that layer.
fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let layer = h.state().session.selected_layer().unwrap();
let name = h.state().session.doc.project.layers[&layer].name.clone();
@@ -79,7 +79,7 @@ fn layer_shortcuts_act_on_a_selected_effect() {
let layer = id(texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap(), "layer");
let p = serde_json::json!({"target": "content", "filter": "invert"});
let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect");
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len());
h.event(egui::Event::Copy);
@@ -15,7 +15,7 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let rows = ["Row A", "Row B", "Row C", "Row D"]
.map(|name| LayerId(execute(&mut session, "layer.add.paint", &json!({ "name": name })).unwrap()["layer"].as_u64().unwrap()));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
(h, rows)
}
+1 -1
View File
@@ -9,7 +9,7 @@ use texturecraft_ui_egui::TextureCraftApp;
fn harness() -> (Harness<'static, TextureCraftApp>, u64) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let layer = h.state().session.selected_layer().unwrap().0;
(h, layer)
+8 -2
View File
@@ -26,7 +26,7 @@ fn app() -> (Harness<'static, TextureCraftApp>, LayerId) {
let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap());
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, layer)
@@ -130,6 +130,12 @@ fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer()
/// A floating Layers panel this narrow cannot hold the toolbar on one row
const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0];
/// [`NARROW_LAYERS`] as a rect
fn narrow_layers() -> egui::Rect {
let [left, top, width, height] = NARROW_LAYERS;
egui::Rect::from_min_size(egui::pos2(left, top), egui::vec2(width, height))
}
/// In a narrow floating Layers panel the add-layer buttons and Remove wrap inside it, where a click still reaches them
#[test]
fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() {
@@ -138,7 +144,7 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() {
let (mut harness, _) = app();
let mut workspace = harness.state().ui.dock.workspace().clone();
workspace.apply_all([Action::Float { panel: Panel::Layers, rect: NARROW_LAYERS }], permissions).unwrap();
workspace.apply_all([Action::float(Panel::Layers, narrow_layers())], false, permissions).unwrap();
harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap());
harness.run_steps(SETTLE_FRAMES);
let [left, _, width, _] = NARROW_LAYERS;
+8 -6
View File
@@ -24,7 +24,7 @@ fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
(h, layer)
}
@@ -108,8 +108,9 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() {
execute(&mut harness.state_mut().session, "layer.group", &Value::Null).unwrap();
}
let mut workspace = harness.state().ui.dock.workspace().clone();
let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") };
let workspace = harness.state().ui.dock.workspace().clone();
let mut layout = workspace.layout().clone();
let Some(Node::Split { second, .. }) = layout.root.as_mut() else { panic!("default columns") };
let Node::Split { size, second: column, .. } = second.as_mut() else { panic!("viewport and right column") };
*size = SplitSize::Ratio(0.99);
@@ -117,6 +118,7 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() {
let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets and the rest") };
let Node::Split { size: layers_share, .. } = below_sets.as_mut() else { panic!("layers and properties") };
*layers_share = SplitSize::Ratio(0.9);
let workspace = texturecraft_ui_egui::docking::Workspace::from_parts(layout, workspace.hidden().to_vec(), workspace.floated().to_vec());
harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap());
// Closing Properties lets the column shrink to the Layers minimum
@@ -151,7 +153,7 @@ fn hidpi_harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"));
execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Active one"})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_pixels_per_point(2.0).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_pixels_per_point(2.0).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
(h, layer)
}
@@ -257,7 +259,7 @@ fn narrow_harness() -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer");
execute(&mut session, "layer.rename", &json!({"layer": layer, "name": LONG_NAME})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h
@@ -295,7 +297,7 @@ fn an_effect_name_cut_short_shows_in_full_on_hover() {
let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer");
execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap();
execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": LONG_EFFECT_NAME})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
+1 -1
View File
@@ -40,7 +40,7 @@ fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraft
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
// Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(STARTUP_FRAMES);
(harness, effect)
}
+1 -1
View File
@@ -9,7 +9,7 @@ use texturecraft_ui_egui::docking::Panel;
fn app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
{
let log = &mut h.state_mut().session.log;
+1 -1
View File
@@ -205,7 +205,7 @@ fn click_widget(harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, la
fn panel_close_button(harness: &Harness<'_, TextureCraftApp>, title: egui::Rect) -> egui::Rect {
harness
.get_all_by_role(egui::Role::Button)
.filter(|button| button.accesskit_node().label().as_deref() == Some("Close Panel"))
.filter(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("Close ")))
.map(|button| button.rect())
.filter(|close| close.min.x > title.max.x && title.y_range().contains(close.center().y))
.min_by(|a, b| a.min.x.total_cmp(&b.min.x))
+1 -1
View File
@@ -22,7 +22,7 @@ fn harness(mask: bool) -> Harness<'static, TextureCraftApp> {
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
execute(&mut session, "effect.add.fill", &json!({"value": 0.5})).unwrap();
}
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
+3 -3
View File
@@ -26,7 +26,7 @@ fn app_with_mask_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, L
let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": projection})).unwrap();
let effect = LayerId(added["effect"].as_u64().unwrap());
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The labels below are English; a first run would speak the system's language
harness.state_mut().ui.prefs.language = "en".into();
@@ -146,7 +146,7 @@ fn a_mask_fill_reading_a_content_anchor_picks_its_channel() {
let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": top, "target": "mask", "anchor": anchor})).unwrap();
let effect = LayerId(added["effect"].as_u64().unwrap());
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": top, "target": effect.0})).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
let Source::Anchor { channel, .. } = mask_fill(&harness, effect).0 else { panic!("an anchor source") };
@@ -176,7 +176,7 @@ fn an_inherited_mask_fill_lists_only_anchors_below_its_owner() {
let instance = texturecraft_engine::execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone();
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap();
session.target = texturecraft_engine::StackTarget::Effect(effect);
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
@@ -26,7 +26,7 @@ fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) {
let folder = LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap());
execute(&mut session, "mask.add.white", &json!({"layer": folder.0})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "mask"})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().ui.props_tab = PropsTab::Material;
harness.run_steps(STARTUP_FRAMES);
+1 -1
View File
@@ -9,7 +9,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap();
session.target = StackTarget::Mask;
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
harness
+1 -1
View File
@@ -10,7 +10,7 @@ use texturecraft_ui_egui::state::Mode;
fn app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness =
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false).build_eframe(|cc| TextureCraftApp::new(cc, session));
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
harness
}
+1 -1
View File
@@ -17,7 +17,7 @@ const WINDOW: egui::Vec2 = vec2(1280.0, 800.0);
/// The app showing only one view, so that the view fills the viewport rect the 3D view reports
fn app(layout: ViewLayout) -> (Harness<'static, TextureCraftApp>, Rect) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(WINDOW).with_pixels_per_point(1.0).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW).with_pixels_per_point(1.0).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint;
harness.state_mut().ui.layout = ViewLayout::Only3D;
harness.run_steps(4);
@@ -19,7 +19,7 @@ fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> {
let mesh = dir.join("Ball.obj");
std::fs::write(&mesh, TWO_MATERIALS).unwrap();
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.windows.new_project = true;
h.state_mut().ui.new_project.resolution = 256;
h.state_mut().ui.new_project.file = Some(mesh.display().to_string());
@@ -129,7 +129,7 @@ fn new_project_baked_maps_snapshots() {
let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
std::fs::create_dir_all(&output_dir).unwrap();
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| {
let adapter = cc.wgpu_render_state.as_ref().unwrap().adapter.get_info();
eprintln!("snapshot adapter: {adapter:?}");
TextureCraftApp::new(cc, session)
@@ -21,7 +21,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(size).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(2);
let ctx = h.ctx.clone();
+1 -1
View File
@@ -15,7 +15,7 @@ use template_library::TemplateLibrary;
/// OUTPUT TEMPLATES with the user template "Mine" selected
fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h.state_mut().session.load_export_presets(library.0.clone());
+3 -179
View File
@@ -1,22 +1,18 @@
//! Every docked panel group sits under one header bar: its names at the left, the shown one raised as a box when the group has several, a close × at the right
//! Every docked panel group's header ends in its close button, and the Properties header names what it shows
use craft_behavior::dock::{Action, DockPlacement};
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::{Dock, Panel, permissions};
use texturecraft_ui_egui::docking::Panel;
use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, panel_close_button};
const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0);
/// A floating window over the viewport, `[x, y, width, height]`
const FLOATING_RECT: [f32; 4] = [600.0, 200.0, 320.0, 400.0];
fn app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The labels below are English; a first run would speak the system's language
harness.state_mut().ui.prefs.language = "en".into();
@@ -85,178 +81,6 @@ fn the_properties_header_names_the_selected_effects_type() {
tab_rect(&harness, "Properties - Levels");
}
/// How far a header under another panel reaches above its tab strip: the 6 px gutter less a 2 px separation (docking/header_band.rs)
const HEADER_RISE: f32 = 4.0;
/// Room between a later tab's box and its tab's left edge (docking/shown_group_tab.rs, private to the crate)
const BOX_INSET: f32 = 4.0;
/// Rounded boxes painted this frame over `tab` whose top is `rise` above it: the raised box of a shown tab
fn tab_boxes(harness: &Harness<'_, TextureCraftApp>, tab: egui::Rect, rise: f32) -> Vec<egui::Rect> {
harness
.output()
.shapes
.iter()
.filter_map(|shape| match &shape.shape {
egui::Shape::Rect(rect) => {
let rises = (rect.rect.top() - (tab.top() - rise)).abs() < 0.5;
let raised = rises && rect.corner_radius != egui::CornerRadius::ZERO && tab.x_range().contains(rect.rect.center().x);
raised.then_some(rect.rect)
}
_ => None,
})
.collect()
}
#[test]
fn a_groups_shown_tab_rises_as_a_box_and_the_others_and_a_lone_panels_do_not() {
let mut harness = app();
let layers = tab_rect(&harness, "Layers");
let settings = tab_rect(&harness, "Texture Set Settings");
assert_eq!(tab_boxes(&harness, layers, HEADER_RISE).len(), 1, "the shown Layers tab has its box, from the top of its header band");
assert_eq!(tab_boxes(&harness, settings, HEADER_RISE).len(), 0, "the hidden tab is its name only");
assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Properties - "), HEADER_RISE).len(), 0, "a panel alone keeps its plain header");
click_at(&mut harness, settings.center());
harness.run_steps(SETTLE_FRAMES);
assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Texture Set Settings"), HEADER_RISE).len(), 1, "the box goes with the shown tab");
assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Layers"), HEADER_RISE).len(), 0);
}
#[test]
fn the_selected_dock_tab_keeps_its_keyboard_focus_outline_visible() {
let mut harness = app();
let layers = tab_rect(&harness, "Layers");
let tab_id = egui::Id::unique("texturecraft-docking").with(("tab", Panel::Layers));
harness.ctx.memory_mut(|memory| memory.request_focus(tab_id));
harness.run_steps(SETTLE_FRAMES);
assert_eq!(harness.ctx.memory(|memory| memory.focused()), Some(tab_id));
let raised_box = tab_boxes(&harness, layers, HEADER_RISE)[0];
let shapes = &harness.output().shapes;
let box_index = shapes.iter().position(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) if rect.rect == raised_box)).unwrap();
assert!(
shapes[box_index + 1..].iter().any(|shape| {
matches!(&shape.shape, egui::Shape::Rect(rect)
if rect.stroke.width > 0.0 && layers.contains_rect(rect.rect) && rect.rect.contains(layers.center()))
}),
"the focus outline is painted above the selected tab"
);
}
#[test]
fn the_first_tabs_box_starts_on_the_panels_edge_and_a_later_tabs_box_keeps_its_inset() {
let mut harness = app();
let layers = tab_rect(&harness, "Layers");
let boxes = tab_boxes(&harness, layers, HEADER_RISE);
assert!(!boxes.is_empty(), "the shown Layers tab has its box");
assert!(boxes.iter().all(|shown| (shown.left() - layers.left()).abs() < 0.5), "{boxes:?} starts on the panel's left edge {}", layers.left());
let settings = tab_rect(&harness, "Texture Set Settings");
click_at(&mut harness, settings.center());
harness.run_steps(SETTLE_FRAMES);
let boxes = tab_boxes(&harness, settings, HEADER_RISE);
assert!(!boxes.is_empty(), "the shown Texture Set Settings tab has its box");
assert!(boxes.iter().all(|shown| (shown.left() - (settings.left() + BOX_INSET)).abs() < 0.5), "{boxes:?} keeps its air from the Layers tab");
}
/// The middle of the first capital's ink in each painted text reading `name`
fn capital_middles(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec<f32> {
harness
.output()
.shapes
.iter()
.filter_map(|shape| match &shape.shape {
egui::Shape::Text(text) if text.galley.text() == name => {
let row = text.galley.rows.first()?;
let glyph = row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase())?;
Some(text.pos.y + row.pos.y + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0)
}
_ => None,
})
.collect()
}
/// Names' capitals and the close × share the header band's middle: the tab strip plus, under another panel, the gutter above it less the separation
#[test]
fn header_names_capitals_and_close_buttons_sit_on_the_header_bands_middle() {
let harness = app();
let headers = [
("Texture Sets", "TEXTURE SETS", 0.0),
("Layers", "LAYERS", HEADER_RISE),
("Texture Set Settings", "TEXTURE SET SETTINGS", HEADER_RISE),
("Properties - ", "PROPERTIES - PAINT", HEADER_RISE),
];
for (tab, name, rise) in headers {
let tab = tab_rect(&harness, tab);
let middle = (tab.top() - rise + tab.bottom()) / 2.0;
let capitals = capital_middles(&harness, name);
assert!(!capitals.is_empty(), "{name} is painted");
assert!(capitals.iter().all(|capital| (capital - middle).abs() < 0.75), "{name}'s capitals at {capitals:?}, its band's middle at {middle}");
}
let properties = tab_rect(&harness, "Properties - ");
let close = panel_close_button(&harness, properties);
let middle = (properties.top() - HEADER_RISE + properties.bottom()) / 2.0;
assert!((close.center().y - middle).abs() < 0.5, "the close × at {}, the band's middle at {middle}", close.center().y);
}
/// A floating group's names sit on one line: the shown name, painted again over its tab, and the dimmed one beside it (the dimmed one kept its galley's middle)
#[test]
fn a_floating_groups_names_share_one_line() {
let mut harness = app();
let mut workspace = harness.state().ui.dock.workspace().clone();
let actions = [
Action::Float { panel: Panel::Properties, rect: FLOATING_RECT },
Action::Move { panel: Panel::TextureSetSettings, anchor: Panel::Properties, placement: DockPlacement::Tab { before: None } },
Action::Activate { panel: Panel::Properties },
];
workspace.apply_all(actions, permissions).unwrap();
harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap());
harness.run_steps(SETTLE_FRAMES);
let shown = capital_middles(&harness, "PROPERTIES - PAINT");
let dimmed = capital_middles(&harness, "TEXTURE SET SETTINGS");
assert!(!shown.is_empty() && !dimmed.is_empty(), "both names are painted");
assert!(shown.iter().chain(&dimmed).all(|capital| (capital - shown[0]).abs() < 0.5), "the shown name's capitals at {shown:?}, the other's at {dimmed:?}");
}
/// The tab menu's panel names keep their plain layout: only the header bar pads a name to centre its capitals on the band
#[test]
fn a_tab_menus_panel_names_keep_their_plain_layout() {
let mut harness = app();
let properties = tab_rect(&harness, "Properties - ");
let button = egui::PointerButton::Secondary;
harness.hover_at(properties.center());
for pressed in [true, false] {
harness.event(egui::Event::PointerButton { pos: properties.center(), button, pressed, modifiers: egui::Modifiers::NONE });
harness.run_steps(1);
}
harness.run_steps(SETTLE_FRAMES);
let move_to = harness.get_by_role_and_label(Role::Button, "Move Panel to Group").rect();
harness.hover_at(move_to.center());
harness.run_steps(SETTLE_FRAMES);
let entry = harness.get_by_role_and_label(Role::Button, "Layers").rect();
let padded: Vec<f32> = harness
.output()
.shapes
.iter()
.filter_map(|shape| match &shape.shape {
egui::Shape::Text(text) if text.galley.text() == "LAYERS" && entry.contains(text.pos) => Some(text.galley.job.first_row_min_height),
_ => None,
})
.collect();
assert!(!padded.is_empty(), "the menu paints the Layers entry");
assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}");
}
/// Where the label on `name`'s row and to its right ends, for each label named `name`
fn row_ends(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec<f32> {
let names = harness.get_all_by_role_and_label(Role::Label, name).map(|node| node.rect());
+3 -3
View File
@@ -22,7 +22,7 @@ fn harness() -> AppHarness<'static> {
execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
// Tall enough that the 2D view's texture square takes A, B and C
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.layout = ViewLayout::Only2D;
h.run_steps(4);
h
@@ -156,7 +156,7 @@ fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() {
let before = session.doc.clone();
let path = session.tool.path.clone();
let history = session.history_labels();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.layout = ViewLayout::Split;
harness.run_steps(4);
let view_3d = harness.state().viewport_rect;
@@ -213,7 +213,7 @@ fn split_harness() -> (AppHarness<'static>, Pos2, Pos2) {
session.update();
execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.layout = ViewLayout::Split;
harness.run_steps(4);
let view_3d = harness.state().viewport_rect;
+1 -1
View File
@@ -14,7 +14,7 @@ fn path_rows_edit_and_remove_paths() {
let r = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.4], [0.8, 0.5]], "commit": true})).unwrap();
let eid = LayerId(r["committed"]["effect"].as_u64().unwrap());
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let editing = |h: &Harness<'_, TextureCraftApp>| h.state().session.tool.path.editing;
let count = |h: &Harness<'_, TextureCraftApp>| h.state().session.paths(eid).map_or(0, <[_]>::len);
+1 -1
View File
@@ -24,7 +24,7 @@ fn frame(harness: &mut Harness<'_, TextureCraftApp>, pen: Option<(TouchPhase, Op
/// Paint in the 2D view with `input` and return the summed base color alpha it added.
fn paint_2d(input: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) -> f64 {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.state_mut().session.tool.brush.min_size = 0.0;
harness.run_steps(4);
+2 -2
View File
@@ -9,7 +9,7 @@ use texturecraft_ui_egui::TextureCraftApp;
/// The sample project in the default split layout at 1600 x 960 with the polygon fill tool
fn polygon_fill_app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().session.tool.tool = Tool::PolygonFill;
harness.run_steps(4);
harness
@@ -138,7 +138,7 @@ fn polygon_fill_snapshots() {
std::fs::create_dir_all(&directory).unwrap();
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info();
eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info);
harness.state_mut().session.tool.tool = Tool::PolygonFill;
+1 -1
View File
@@ -27,7 +27,7 @@ fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> {
// The view has no accessible name of its own; these tests drive it by position
let builder = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false);
let mut harness = builder.build_eframe(|context| {
let mut harness = builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| {
let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone());
creation.storage = Some(storage);
TextureCraftApp::new(&creation, session)
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more