Start with no project open; File > Close returns to the empty state

Removes the start window and the startup sample project. With no project open the views are empty (view picker only), Layers and Properties are empty, project-only menu items and commands are disabled, and the status bar shows only the version.
This commit is contained in:
vangel76 committed 2026-11-17 22:00:22 +01:00
1 parent 8347da6e93
commit bac934d5a5
23 files changed
+324 -182

No files matched your search

+2 -2
View File
@@ -146,7 +146,7 @@ The full list of what's in it is in [`docs/features.md`](docs/features.md).
git clone https://github.com/storytold/texturecraft
cd texturecraft
cargo run --release -p texturecraft # desktop app (opens a sample project)
cargo run --release -p texturecraft # desktop app (starts with no project)
cargo run --release -p texturecraft -- model.glb # a new project from a mesh
cargo run --release -p texturecraft -- --control 7878 # + JSON control channel
cargo run --release -p texturecraft-cli -- mcp # MCP server (stdio)
@@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
```
You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts
You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one; **File ▸ Close** returns to this empty state); **File ▸ New project** starts
from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none).
Japanese, Chinese, Korean and Arabic interface text uses the fonts of
+3 -15
View File
@@ -41,8 +41,9 @@ pub fn start() {
async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
// The WebAssembly has downloaded and compiled when this runs.
step(0.5, "Preparing the sample project…").await;
let session = initial_session()?;
step(0.5, "Preparing the app…").await;
// The app starts with no project, like File > Close
let session = Session::closed();
step(0.8, "Starting the renderer…").await;
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
@@ -56,7 +57,6 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
options,
Box::new(|cc| {
let mut app = TextureCraftApp::new(cc, session);
app.ui.windows.start = app.ui.prefs.start_window;
if let Some(rs) = &cc.wgpu_render_state {
let backend = rs.adapter.get_info().backend;
log::info!("TextureCraft: wgpu backend {backend:?}");
@@ -137,18 +137,6 @@ fn guard_unsaved_changes() {
on_unload.forget();
}
/// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are
/// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a
/// fast desktop CPU, 128 ~7.5 s).
fn initial_session() -> Result<Session, String> {
texturecraft_engine::sample_session(1024, 128)
.or_else(|e| {
log::warn!("sample project failed: {e}");
Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 1024)
})
.map_err(|e| e.to_string())
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
+6 -19
View File
@@ -1,6 +1,6 @@
//! TextureCraft desktop app.
//!
//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control <port>] [--empty] [--version]`
//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control <port>] [--version]`
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -38,7 +38,6 @@ fn version() -> String {
struct Args {
file: Option<String>,
control: Option<u16>,
empty: bool,
gpu: Option<String>,
power_pref: Option<eframe::wgpu::PowerPreference>,
}
@@ -48,7 +47,7 @@ fn parse_args() -> Result<Option<Args>, String> {
}
fn parse_args_from<I: IntoIterator<Item = String>>(it: I) -> Result<Option<Args>, String> {
let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None };
let mut args = Args { file: None, control: None, gpu: None, power_pref: None };
let mut it = it.into_iter();
while let Some(a) = it.next() {
match a.as_str() {
@@ -75,7 +74,8 @@ fn parse_args_from<I: IntoIterator<Item = String>>(it: I) -> Result<Option<Args>
let p = it.next().ok_or("--power-pref needs high, low, or none")?;
args.power_pref = Some(gpu::parse_power_preference(&p)?);
}
"--empty" => args.empty = true,
// Kept so old command lines still work: the app starts without a project anyway
"--empty" => {}
f if !f.starts_with('-') => args.file = Some(f.to_string()),
other => return Err(format!("unknown option `{other}`")),
}
@@ -90,18 +90,8 @@ fn initial_session(args: &Args) -> Session {
Err(e) => eprintln!("texturecraft: could not open {f}: {e}"),
}
}
if !args.empty
&& let Ok(s) = texturecraft_engine::sample_session(2048, 512)
{
return s;
}
match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) {
Ok(s) => s,
Err(e) => {
eprintln!("texturecraft: {e}");
std::process::exit(1);
}
}
// No file given (or it did not open): start with no project, like File > Close
Session::closed()
}
fn icon() -> Option<egui::IconData> {
@@ -220,8 +210,6 @@ fn main() {
std::process::exit(2);
}
let control = args.control;
// The start window offers new, open and recent projects, unless a file was given or a script drives the app
let start = args.file.is_none() && control.is_none();
let r = eframe::run_native(
APP_NAME,
options,
@@ -238,7 +226,6 @@ fn main() {
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
let mut app = TextureCraftApp::new(cc, session);
app.title_bar = title_bar;
app.ui.windows.start = start && app.ui.prefs.start_window;
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()));
+34 -2
View File
@@ -88,6 +88,38 @@ pub fn command_specs() -> &'static [CommandSpec] {
})
}
/// Commands that run in the empty state (no project open): they open or create a project, or
/// only read the libraries and the user's presets.
fn works_without_project(id: &str) -> bool {
matches!(
id,
"file.open"
| "file.new"
| "project.new"
| "project.sample"
| "project.inspect"
| "project.templates"
| "export.presets"
| "export.preset.get"
| "export.preset.save"
| "export.preset.remove"
| "brush.preset.list"
| "alpha.list"
| "filter.list"
| "material.list"
| "mask.smart.list"
| "text.fonts"
)
}
/// Whether `spec` can run on `s`: no project open refuses everything but [`works_without_project`]
pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), String> {
if !s.project_open && !works_without_project(spec.id) {
return Err("no project is open".into());
}
(spec.enabled)(s)
}
pub fn find(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
@@ -96,7 +128,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
/// `merge: true` its edits continue the previous undo step of the same label (drags).
pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result<Value> {
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false));
let result = (spec.run)(s, params);
s.merge_edits = outer;
@@ -116,7 +148,7 @@ pub fn list(s: &Session, filter: Option<&str>) -> Value {
"menu": c.menu,
"shortcut": c.shortcut,
"params": c.params,
"enabled": (c.enabled)(s).is_ok(),
"enabled": check_enabled(c, s).is_ok(),
})
})
.collect();
+1 -2
View File
@@ -660,8 +660,7 @@ use unsupported as export_textures;
use unsupported as export_mesh;
fn close(s: &mut Session, _: &Value) -> Result<Value> {
let next = Session::new_project("Untitled", primitives::material_ball(), "builtin:material_ball", None, 2048)?;
s.switch_to(next);
s.switch_to(Session::closed());
Ok(Value::Null)
}
+1 -1
View File
@@ -65,7 +65,7 @@ pub mod view_cmds;
pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
pub use bake_preview::{BakePreview, PreviewShow};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use commands::{CommandSpec, check_enabled, command_specs, execute, find};
pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use path_tool::PathState;
+13
View File
@@ -363,6 +363,10 @@ pub struct Session {
/// Point changes of the path being edited: (earlier states for undo, undone states for redo)
pub(crate) path_steps: (Vec<crate::path_tool::PathState>, Vec<crate::path_tool::PathState>),
pub path: Option<String>,
/// False in the empty state (the app at start, or after File > Close): the document is a
/// tiny placeholder that panels do not show, and only the commands that open or create a
/// project run (see [`crate::commands::check_enabled`]).
pub project_open: bool,
pub modified: bool,
/// Bumps on every document change.
pub revision: u64,
@@ -421,6 +425,7 @@ impl Session {
path_draft: None,
path_steps: Default::default(),
path: None,
project_open: true,
modified: false,
revision: 1,
log: Vec::new(),
@@ -431,6 +436,14 @@ impl Session {
})
}
/// The empty state: no project is open. Holds a tiny placeholder document that the UI never
/// shows; every command except opening or creating a project is refused.
pub fn closed() -> Session {
let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 128).expect("the placeholder project is valid");
session.project_open = false;
session
}
/// Replace this session with `next` (another project), keeping the viewport size and the
/// user's export presets and project templates.
pub fn switch_to(&mut self, mut next: Session) {
+3
View File
@@ -7,6 +7,9 @@ use crate::{Session, StackTarget, Tool};
impl Session {
/// Whether `tool` can act on the selection (or on the quick mask while it is being edited)
pub fn tool_usable(&self, tool: Tool) -> bool {
if !self.project_open {
return false;
}
match tool {
// The picker reads the composite under the cursor, whatever is selected
Tool::ColorPicker => return true,
+50
View File
@@ -0,0 +1,50 @@
//! The empty state (no project open): only commands that open or create a project run, and
//! File > Close returns to it.
use serde_json::json;
use texturecraft_engine::{EngineError, Session, Tool, check_enabled, command_specs, execute, find};
fn open_project() -> Session {
Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap()
}
#[test]
fn a_closed_session_refuses_commands_that_need_a_project() {
let mut s = Session::closed();
assert!(!s.project_open);
for id in ["layer.add.paint", "file.save", "file.close", "edit.undo", "tool.paint", "bake.run", "file.exportTextures", "viewport.view", "camera.add"] {
let error = execute(&mut s, id, &json!({})).unwrap_err();
assert!(matches!(error, EngineError::Disabled { .. }), "{id}: {error}");
}
assert!(!s.can_undo(), "nothing was changed");
assert!(!s.tool_usable(Tool::Paint), "no tool can act without a project");
}
#[test]
fn a_closed_session_lists_only_the_opening_commands_as_enabled() {
let s = Session::closed();
for id in ["file.open", "file.new", "project.new", "project.sample"] {
assert!(check_enabled(find(id).unwrap(), &s).is_ok(), "{id} runs with no project");
}
let enabled: Vec<&str> = command_specs().iter().filter(|spec| check_enabled(spec, &s).is_ok()).map(|spec| spec.id).collect();
assert!(!enabled.iter().any(|id| id.starts_with("layer.") || id.starts_with("tool.") || id.starts_with("bake.")), "{enabled:?}");
}
#[test]
fn creating_a_project_from_the_closed_state_opens_it() {
let mut s = Session::closed();
execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap();
assert!(s.project_open);
execute(&mut s, "layer.add.paint", &json!({})).unwrap();
}
#[test]
fn close_returns_to_the_empty_state_and_keeps_the_user_presets() {
let mut s = open_project();
s.modified = true;
execute(&mut s, "file.close", &json!({})).unwrap();
assert!(!s.project_open && !s.modified && s.path.is_none());
assert!(execute(&mut s, "file.close", &json!({})).is_err(), "closing again has nothing to close");
execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap();
assert!(s.project_open, "a project can be created again");
}
+1
View File
@@ -6,6 +6,7 @@ mod bake_checks;
mod bake_resolution;
mod bake_settings;
mod bake_tiles;
mod closed_session;
mod color_selection;
mod content_effects;
mod export_colour_space;
+18 -2
View File
@@ -41,6 +41,10 @@ const TAG_COLORS: [Color32; 8] = [
];
pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
// The empty state lists nothing
if !app.session.project_open {
return;
}
let tk = Tokens::get(ui.ctx());
let sets: Vec<(String, String, bool)> = app
.session
@@ -143,7 +147,8 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
// Wrap in a narrow column so rows stay within the panel
ui.horizontal_wrapped(|ui| {
let project_open = app.session.project_open;
ui.add_enabled_ui(project_open, |ui| ui.horizontal_wrapped(|ui| {
// Keep menu buttons as compact as the adjacent icon buttons
ui.spacing_mut().button_padding.x = 4.0;
ui.spacing_mut().item_spacing.x = 4.0;
@@ -175,7 +180,11 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, 22.0).clicked() {
app.run("layer.remove", Value::Null);
}
});
}));
// The empty state has no layers: the toolbar stays, greyed
if !project_open {
return;
}
ui.add_space(2.0);
let ts = app.session.ts();
let stack: Vec<LayerId> = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default();
@@ -1481,6 +1490,9 @@ pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 {
/// The Properties tab title: what the panel edits
pub(crate) fn properties_title(app: &TextureCraftApp) -> String {
if !app.session.project_open {
return tr("Properties").to_string();
}
let project = &app.session.doc.project;
let tool = app.session.tool.tool;
let tool_usable = app.session.tool_usable(tool);
@@ -1507,6 +1519,10 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) {
/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act)
pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
if !app.session.project_open {
ui.label(RichText::new(tr("No properties found")).color(tokens.text_dim));
return;
}
let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned());
let tool = app.session.tool.tool;
let tool_usable = app.session.tool_usable(tool);
+5
View File
@@ -480,6 +480,11 @@ const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4);
/// The body of every panel except the viewport, in the dock or on the rail
pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
// No project open: the library and the log work, the other panels about a project stay empty
let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties);
if !app.session.project_open && !works_empty {
return;
}
egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel {
Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui),
Panel::Assets => crate::shelf::body(app, ui),
+8
View File
@@ -303,6 +303,10 @@ impl TextureCraftApp {
if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") {
self.pbr_import = None;
}
// The empty state has no baking or rendering to show
if id == "file.close" {
self.ui.mode = state::Mode::Painting;
}
if let Some(from) = glide_from.filter(|f| *f != self.session.camera) {
self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time });
self.session.camera = from;
@@ -760,6 +764,10 @@ impl eframe::App for TextureCraftApp {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
let t0 = now_ms();
// Baking and rendering need a project (a saved layout may start in one of them)
if !self.session.project_open {
self.ui.mode = state::Mode::Painting;
}
if !self.ui.hide_ui {
titlebar::show(self, ui);
banner(self, ui);
+7 -2
View File
@@ -113,6 +113,11 @@ fn is_ui(id: &str) -> bool {
id.starts_with("ui.")
}
/// Shell items that act on the open project: greyed while none is open
fn ui_needs_project(id: &str) -> bool {
matches!(id, "ui.export" | "ui.projectConfig" | "ui.uvChecker" | "ui.mode.bake" | "ui.mode.render")
}
/// Whether an item can run now
pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
if let Some(panel) = crate::docking::view_panel(id) {
@@ -124,7 +129,7 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
}
if is_ui(id) {
return true;
return app.session.project_open || !ui_needs_project(id);
}
// Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act
@@ -133,7 +138,7 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
return false;
}
texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok())
texturecraft_engine::find(id).is_some_and(|command| texturecraft_engine::check_enabled(command, &app.session).is_ok())
}
/// Whether an id is implemented at all (parity report).
-6
View File
@@ -79,9 +79,6 @@ pub struct Windows {
/// Browser File › Export Mesh: the download format choice.
#[serde(default)]
pub export_mesh: bool,
/// The start window: new, open, recent projects (the app opens it at launch).
#[serde(skip)]
pub start: bool,
/// Edit > Project Configuration: what is chosen so far, applied by OK.
#[serde(skip)]
pub project_config: Option<ProjectConfig>,
@@ -122,8 +119,6 @@ pub struct Prefs {
pub accent: crate::theme::Accent,
/// The system draws the window's title bar instead of TextureCraft (desktop; read at startup).
pub system_title_bar: bool,
/// Show the start window at launch.
pub start_window: bool,
/// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at
/// startup). Empty or relative: `Documents/TextureCraft`.
pub data_folder: String,
@@ -146,7 +141,6 @@ impl Default for Prefs {
brightness: crate::theme::Brightness::default(),
accent: crate::theme::Accent::default(),
system_title_bar: false,
start_window: true,
data_folder: String::new(),
reserved_cores: 1,
project_open_limit_gib: texturecraft_engine::formats::DEFAULT_PROJECT_OPEN_LIMIT_GIB,
+5 -18
View File
@@ -466,7 +466,11 @@ pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| {
ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP;
crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect());
if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() {
let export_on = crate::menus::enabled(app, "ui.export");
let export = ui.add_enabled_ui(export_on, |ui| {
icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE)
});
if export.inner.clicked() {
app.ui.windows.export = !app.ui.windows.export;
}
@@ -515,23 +519,6 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
.size(11.0)
.color(tk.text_dim),
);
ui.separator();
let m = app.session.memory();
let mb = |b: usize| b as f64 / (1024.0 * 1024.0);
let total = mb(m.total());
let decimals = if total < 10.0 { 1 } else { 0 };
let mb1 = |b: usize| format!("{:.1}", mb(b));
ui.label(RichText::new(trf("Layer memory: {mb} MB", &[("mb", &format!("{total:.decimals$}"))])).size(11.0).color(tk.text_dim)).on_hover_ui(
|ui| {
ui.label(trf(
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
&[("pixels", &mb1(m.pixels)), ("composites", &mb1(m.composites)), ("cache", &mb1(m.cache))],
));
},
);
ui.separator();
ui.label(RichText::new(trf("UI {ms} ms", &[("ms", &format!("{:.1}", app.ui_ms))])).size(11.0).color(tk.text_dim));
ui.add_space(vec2(0.0, 0.0).x);
});
});
});
-1
View File
@@ -126,7 +126,6 @@ mod tests {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).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.state_mut().ui.windows.start = false;
h.run_steps(2);
h
}
+41 -3
View File
@@ -60,6 +60,15 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
crate::toolbar::paint_bar(app, ui);
}
// No project open: empty views with only their view-mode picker
if !app.session.project_open {
if app.render.is_active() {
crate::render_mode::stop(app);
}
empty_views(app, ui);
return;
}
let stroke_end = ui.scope_id().with("paint_2d_stroke_end");
// A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture.
let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) {
@@ -133,6 +142,27 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
}
}
/// The views while no project is open: no mesh, no texture, each with its view-mode picker
fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let full = ui.available_rect_before_wrap();
let regions: Vec<(Rect, &str)> = match app.ui.layout {
ViewLayout::Only3D => vec![(full, "v3d")],
ViewLayout::Only2D => vec![(full, "v2d")],
ViewLayout::Split => {
let middle = (full.left() + full.width() * 0.5).round();
vec![
(Rect::from_min_max(full.min, pos2(middle - SPLIT_LINE_HALF_WIDTH, full.max.y)), "v3d"),
(Rect::from_min_max(pos2(middle + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max), "v2d"),
]
}
};
for (rect, id) in regions {
ui.painter().rect_filled(rect, 0.0, tokens.viewport);
view_header(app, ui, rect, id);
}
}
/// Half the split divider's line width: each view starts this far from the line's centre
const SPLIT_LINE_HALF_WIDTH: f32 = 1.0;
@@ -425,10 +455,13 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
let Some(header) = view_header_rect(rect) else { return };
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center)));
// With no project open there is no camera to pick: the view keeps only its view-mode picker
let project_open = app.session.project_open;
let current = texturecraft_engine::camera_cmds::current(&app.session);
let names: Vec<String> = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect();
let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str);
egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| {
if project_open {
egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| {
if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() {
app.run("camera.select", json!({}));
}
@@ -441,7 +474,8 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
if ui.selectable_label(false, tr("Save view as camera")).clicked() {
app.run("camera.add", json!({}));
}
});
});
}
// Bake mode lights the project mesh with the neutral material unless the painted one is asked for
let baking = app.ui.mode == crate::state::Mode::Baking;
@@ -457,11 +491,15 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
app.ui.bake_visualization.neutral_shown = true;
app.run("viewport.view", json!({"mode": "material"}));
}
if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() {
if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() && project_open {
// Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone
app.ui.bake_visualization.neutral_shown &= !baking;
app.run("viewport.view", json!({"mode": "material"}));
}
// Nothing else to show without a project
if !project_open {
return;
}
ui.separator();
if baking {
mesh_map_entries(app, ui);
+4 -76
View File
@@ -19,7 +19,6 @@ use crate::theme::{Accent, Brightness, Tokens, caption};
use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, slider};
pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
start(app, ctx);
new_project(app, ctx);
about(app, ctx);
settings(app, ctx);
@@ -389,78 +388,6 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
}
}
/// What the start window was asked for.
enum Start {
Menu(&'static str),
#[cfg(not(target_arch = "wasm32"))]
Recent(String),
Close,
}
/// The start window: a new project, a project file or a recent one, or the sample that is open.
fn start(app: &mut TextureCraftApp, ctx: &egui::Context) {
if !app.ui.windows.start {
return;
}
#[cfg(not(target_arch = "wasm32"))]
let tokens = Tokens::get(ctx);
let mut open = true;
let mut action = None;
dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| {
ui.horizontal(|ui| {
if ui.add(primary_button(ui, tr("New project..."))).clicked() {
action = Some(Start::Menu("ui.newProject"));
}
if ui.button(tr("Open...")).clicked() {
action = Some(Start::Menu("file.open"));
}
});
#[cfg(not(target_arch = "wasm32"))]
if file_dialogs_available() {
ui.add_space(8.0);
ui.label(caption(tr("Recent projects")));
if app.ui.recent.is_empty() {
ui.label(RichText::new(tr("No recent projects yet")).color(tokens.text_dim));
}
for path in &app.ui.recent {
let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path);
if ui
.add(egui::Button::selectable(false, format!("{} {name}", ic::FILE)).min_size(vec2(ui.available_width(), 0.0)))
.on_hover_text(path)
.clicked()
{
action = Some(Start::Recent(path.clone()));
}
}
}
ui.add_space(8.0);
ui.separator();
ui.horizontal(|ui| {
ui.checkbox(&mut app.ui.prefs.start_window, tr("Show at startup"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Continue with the sample project")).clicked() {
action = Some(Start::Close);
}
});
});
});
if let Some(action) = action {
app.ui.windows.start = false;
match action {
Start::Menu(id) => crate::menus::invoke(app, ctx, id),
#[cfg(not(target_arch = "wasm32"))]
Start::Recent(path) => open_path(app, &path),
Start::Close => {}
}
}
if !open {
app.ui.windows.start = false;
}
}
fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
if !app.ui.windows.new_project {
return;
@@ -659,9 +586,6 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) {
.on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar"));
ui.end_row();
}
ui.label(tr("Start window"));
ui.checkbox(&mut p.start_window, tr("Show at startup"));
ui.end_row();
});
ui.add_space(8.0);
ui.label(caption(tr("Viewport")));
@@ -1216,6 +1140,10 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur
pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) {
let tk = Tokens::get(ctx);
// Nothing to export without a project (closed, or a saved layout that left it open)
if !app.session.project_open {
app.ui.windows.export = false;
}
if !app.ui.windows.export {
return;
}
+119
View File
@@ -0,0 +1,119 @@
//! The app starts with no project and no popup; File > Close goes back to that empty state.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_ui_egui::{TextureCraftApp, menus};
fn harness(session: Session) -> Harness<'static, TextureCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
h
}
fn empty() -> Harness<'static, TextureCraftApp> {
harness(Session::closed())
}
fn open_project() -> Harness<'static, TextureCraftApp> {
harness(texturecraft_engine::sample_session(256, 64).unwrap())
}
fn invoke(h: &mut Harness<'static, TextureCraftApp>, id: &str) {
let ctx = h.ctx.clone();
menus::invoke(h.state_mut(), &ctx, id);
h.run_steps(3);
}
#[test]
fn starts_with_no_project_and_no_popup() {
let h = empty();
let ui = &h.state().ui;
assert!(!h.state().session.project_open);
assert!(!ui.windows.new_project && !ui.windows.about && !ui.windows.settings && !ui.windows.export, "no window opens by itself");
assert!(h.query_by_label("Continue with the sample project").is_none() && h.query_by_label("Recent projects").is_none(), "no start window");
assert!(h.query_by_label("No properties found").is_some(), "Properties says it has nothing");
}
#[test]
fn project_items_are_disabled_without_a_project() {
let h = empty();
let app = h.state();
for id in [
"file.save", "file.saveAs", "file.saveCopy", "file.close", "ui.export", "file.exportMesh", "ui.projectConfig", "edit.undo", "edit.redo", "file.reimportMesh",
"ui.mode.bake", "ui.mode.render", "ui.uvChecker", "viewport.frame", "viewport.displayMaterial", "tool.paint", "tool.eraser", "viewport.quickMask",
"layer.add.paint", "layer.add.fill", "layer.remove", "bake.run", "resource.import", "material.load",
] {
assert!(!menus::enabled(app, id), "{id} needs a project");
}
for id in ["ui.newProject", "file.open", "project.sample", "ui.settings", "ui.about", "ui.quit", "ui.mode.paint", "ui.layout.split"] {
assert!(menus::enabled(app, id), "{id} works without a project");
}
let open = open_project();
for id in ["file.save", "file.close", "ui.export", "layer.add.paint", "ui.mode.bake"] {
assert!(menus::enabled(open.state(), id), "{id} is on with a project");
}
}
#[test]
fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() {
let empty = empty();
assert!(empty.query_by_label("Default camera").is_none(), "no camera picker");
assert!(empty.query_all_by_label("Material").count() >= 1, "the view picker stays");
let open = open_project();
assert!(open.query_by_label("Default camera").is_some(), "with a project the camera picker is there");
}
#[test]
fn the_status_bar_has_the_version_but_no_frame_time_or_layer_memory() {
for h in [empty(), open_project()] {
assert!(h.query_by_label_contains("Version:").is_some());
assert!(h.query_by_label_contains("Layer memory").is_none());
assert!(h.query_by_label_contains(" ms").is_none(), "no frame time");
}
}
#[test]
fn close_unloads_the_project_back_to_the_empty_state() {
let mut h = open_project();
assert!(h.state().session.project_open && h.state().session.set_count() == 2);
invoke(&mut h, "file.close");
assert!(!h.state().session.project_open, "Close leaves no project open");
assert!(h.state().session.path.is_none() && !h.state().session.modified);
assert!(h.query_by_label("No properties found").is_some());
assert!(h.query_by_label("Default camera").is_none());
assert!(!menus::enabled(h.state(), "file.save"));
}
#[test]
fn creating_or_opening_a_project_from_the_empty_state_works() {
let mut h = empty();
assert!(h.state_mut().run("project.new", json!({"mesh": "cube", "resolution": 128})).is_some());
h.run_steps(3);
assert!(h.state().session.project_open);
assert!(menus::enabled(h.state(), "file.save") && h.query_by_label("Default camera").is_some());
invoke(&mut h, "file.close");
invoke(&mut h, "ui.newProject");
assert!(h.state().ui.windows.new_project, "New project opens its dialog from the empty state");
let mut h = empty();
invoke(&mut h, "project.sample");
assert!(h.state().session.project_open && h.state().session.set_count() == 2, "the sample is still one menu click away");
}
#[test]
fn using_every_panel_and_menu_item_in_the_empty_state_does_not_panic() {
let mut h = empty();
for item in menus::CATALOG.iter().filter(|item| item.label != "-" && !matches!(item.id, "ui.quit" | "file.open" | "project.sample" | "ui.layout.load" | "ui.help.checkForUpdates")) {
invoke(&mut h, item.id);
}
for mode in ["ui.mode.bake", "ui.mode.render", "ui.mode.paint"] {
invoke(&mut h, mode);
}
for id in ["ui.layout.2d", "ui.layout.3d", "ui.layout.split"] {
invoke(&mut h, id);
}
assert!(!h.state().session.project_open, "none of these opened a project");
assert!(!h.state().session.can_undo(), "and none changed it");
}
+1 -1
View File
@@ -37,7 +37,7 @@ mod shift_lines_2d;
mod shortcut_keys;
mod skew_paint;
mod split_divider;
mod start_window;
mod empty_start;
mod tool_availability;
mod toolbar;
-30
View File
@@ -1,30 +0,0 @@
//! The start window: New project opens its dialog, Continue keeps the open project, and the
//! startup choice is a setting.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
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));
h.state_mut().ui.windows.start = true;
h.run_steps(3);
h
}
#[test]
fn start_window_choices() {
let mut h = harness();
h.get_by_label("New project...").click();
h.run_steps(3);
assert!(!h.state().ui.windows.start && h.state().ui.windows.new_project, "New project opens its dialog");
let mut h = harness();
h.get_by_label("Show at startup").click();
h.get_by_label("Continue with the sample project").click();
h.run_steps(3);
assert!(!h.state().ui.windows.start && !h.state().ui.windows.new_project);
assert!(!h.state().ui.prefs.start_window, "unticked: not shown next time");
assert_eq!(h.state().session.doc.project.texture_sets.len(), 2, "the sample stays open");
}
+2 -2
View File
@@ -149,8 +149,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
strip, and Settings › Interface › System title bar for the system's frame instead.
- **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed
them.
- A **start window** at launch: a new project, a project file, a recent project or the sample
(Settings › Interface › Start window).
- **No project at launch**: empty views, panels and toolbars until you create or open one (File ›
New project, Open, Recent projects, Open sample project); File › Close returns to that state.
- A **data folder** of your choice for autosaves, smart materials, presets, templates and UI
layouts, on any drive (Settings › Folders; `Documents/TextureCraft` by default).
- A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip.