Files
OneCAD-Simulation/crates/ui-egui/src/icons.rs
T
bf325bb234 Craft-family shell, native file dialogs, samples and one-click Solve (#46)
* Native file pickers, background opening, drag and drop and recent files

Open (models, SolidCraft designs and tagged meshes in one picker), Save, Save As, Write
Deck and Recover go through the host's file pickers (rfd in the desktop app, injected as
Services so the UI crate stays portable and tests answer them). Files open on a copy of the
session in a worker thread and replace it only on success; files dropped on the window or
named on the command line open the same way. A recent-files list, an unsaved-changes prompt,
Cmd/Ctrl+O/S/Shift+S. Programmatic calls never open a picker: ui.start opens the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* Samples and one-click Solve: results reachable from the window

file.sample {name} opens a ready-to-run sample (the two parts, the cantilever with static and
frequency steps, the bar impact) in place of the model; solve.run solves every step in order.
Help > Samples, the empty viewport's start screen and the Tools > Samples entry open them
(asking first over unsaved changes); Solve runs in the background like a file opening and the
Results tab comes up. --sample [parts|cantilever|impact] on the command line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* The Craft-family shell: title bar, workspace ribbon, browser, context panel, timeline

The window now follows SolidCraft's and VectorCraft's layout and themes:
- title bar with the mark, quick actions (File menu, save, undo, redo, Solve, search,
  theme, help), the model's document tab and the version; integrated under the macOS
  traffic lights, own caption buttons and resize zones elsewhere (titlebar.rs);
- workspaces (Prepare, Model, Analysis, Results) with their tabs, and panels of icon
  buttons whose labelled drop-downs list the whole catalogue, coming-soon entries greyed
  with their milestone; panels collapse, then go into a » menu, when narrow;
- the browser: geometry and mesh with eye toggles, definitions with counts, results;
- no permanent Commands list: command search (S, Cmd/Ctrl+K) and a command line;
- the context panel on the right only with context: the command form, results controls,
  the selected definition's properties with Edit and Delete;
- navigation bar and orientation gizmo in the viewport; the journal timeline at the bottom
  with undo positions;
- SolidCraft's light and dark tokens; craft-ui (IconButton, Tab, WidgetPalette).
Menus and the search are view state (ui.set {menu, palette}), so captures show them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* Shell polish, docs and licences

Menus painted as the family's (flat File menu with recent files, decks and samples), the
legend sized to its text, two-line panel labels inside the ribbon, glyphs the UI font has,
offscreen captures without fade-in, ui.start runs in-window file actions (samples, recover,
solve) but never a native picker, ui.select. Control protocol, architecture, ROADMAP, AGENTS
and ATTRIBUTION updated; THIRD-PARTY-LICENSES.txt with craft-ui and rfd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* Title bar mark from the application icon; fluid steps and domains in the shell

The title bar draws the app icon's bracket (assets/app-icon/icon-small.svg's faces) as
SolidCraft draws its mark; the window keeps its title-bar flags after the rebase.
solve.run solves fluid steps too (solve.fluid); the browser lists fluid domains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* Simplify: cached per-frame data, one command per timeline roll, workspace setters

- Icon textures are kept per pixel size (the shell draws several sizes a frame; the cache
  used to clear on every size change and rasterise again).
- Opening a model or recovering one starts from an empty session instead of copying the
  current one; the replaced session is freed off the window thread.
- Element counts, timeline items, search results and the selected definition's properties
  are cached until what they show changes; timeline tooltips are built on hover; long lists
  in properties are summarised.
- edit.undo and edit.redo take a count: a timeline click is one command.
- solve.run dispatches on the step's procedure (no string round trip) and reports its name.
- The workspace and tab change together through UiState::select_tab/select_workspace
  (ui.set {workspace} alone now sticks); no per-frame syncing.
- One busy guard, Kind::verbs, a fit flag for background jobs, ModelApp::home_view, the title
  bar's actions as an enum, dead code removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* Title bar: Solve and tools at the right end; no traffic-light inset in full screen

The owner's feedback on the title bar: Solve, search, theme and help sit at its right end
before the version; on macOS the left group (mark, name, quick actions) moves into the
traffic lights' room in full screen, where there are none, and back when leaving it. The
layout is a pure function (bar_layout) tested for both states, narrow windows and custom
caption buttons. ui.fullscreen {on} for agents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* Caps labels in Inter SemiBold

egui has no bold weight of its default font, so the ribbon's tabs and panel labels, the
workspace switcher and its menu, menu headings, the browser header, the context panel's
headers and the Solve label were thin, especially in the light theme. They now use a label
font family: Inter SemiBold 4.1 (SIL OFL 1.1, unmodified, fonts/OFL.txt, ATTRIBUTION.md),
with egui's fonts as fallback, installed with the theme on the live and offscreen contexts.
theme::label_font falls back to the default font until the family is bound (fonts take
effect from the next pass), so nothing can panic. Panels widen to their label's longest word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

* docs: regenerate features.md after rebase

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmAttHhUZTokgPeEJia8sm

---------

Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:11:15 -04:00

189 lines
7.7 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Toolbar icons: original artwork drawn with VectorCraft (`assets/icons`, `cargo xtask icons`),
//! embedded at build time and rasterised with resvg.
//!
//! Icons are drawn in four palette roles (line, accent, soft fill, warm), each in one fixed colour.
//! Before rasterising, every role colour is replaced by the theme token it stands for (`icon`,
//! `accent`, `icon_fill`, `warm`, as SolidCraft paints its icons), so the same SVG serves the dark
//! and light themes and the greyed "coming soon" state. Icons named `ui.*` belong to the window
//! itself (navigation bar, title bar), the others to catalogue entries. Textures are cached per
//! icon, theme, state and pixel size.
use std::collections::HashMap;
use egui::{Color32, TextureHandle};
use resvg::{tiny_skia, usvg};
use crate::theme::Tokens;
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
/// The palette roles' colours in the SVG files. Keep in step with `PALETTE` in
/// `xtask/src/icons.rs`.
pub const PALETTE: [&str; 4] = ["#dde2ea", "#4f9ce8", "#2d4e70", "#f0b44a"];
/// Largest icon side rasterised (pixels).
const MAX_PX: u32 = 256;
/// The icon's SVG text.
pub fn svg(id: &str) -> Option<&'static str> {
ICONS.binary_search_by(|(k, _)| (*k).cmp(id)).ok().and_then(|i| ICONS.get(i)).map(|(_, s)| *s)
}
/// The colours the palette roles (line, accent, soft, warm) take in a theme, greyed when the
/// entry is not available yet.
pub fn colours(t: &Tokens, enabled: bool) -> [Color32; 4] {
if enabled { [t.icon, t.accent, t.icon_fill, t.warm] } else { [t.border, t.border, t.panel_header, t.border] }
}
/// The SVG with each palette colour replaced by its role's colour.
pub fn recolour(svg: &str, colours: [Color32; 4]) -> String {
let mut out = svg.to_string();
for (from, to) in PALETTE.iter().zip(colours) {
let hex = format!("#{:02x}{:02x}{:02x}", to.r(), to.g(), to.b());
out = out.replace(&format!("\"{from}\""), &format!("\"{hex}\""));
}
out
}
/// Rasterise an SVG to a `px` × `px` image.
pub fn rasterise(svg: &str, px: u32) -> Result<egui::ColorImage, String> {
let px = px.clamp(1, MAX_PX);
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).map_err(|e| e.to_string())?;
let mut pixmap = tiny_skia::Pixmap::new(px, px).ok_or("empty icon")?;
let size = tree.size();
let scale = px as f32 / size.width().max(size.height()).max(f32::EPSILON);
resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());
Ok(egui::ColorImage::from_rgba_premultiplied([px as usize, px as usize], pixmap.data()))
}
/// How an icon is drawn.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Look {
/// In the theme's colours.
Normal,
/// Greyed: coming soon or unavailable.
Greyed,
/// On the title bar, which is dark in both themes: the dark theme's colours.
AppBar,
}
impl Look {
pub fn of(enabled: bool) -> Look {
if enabled { Look::Normal } else { Look::Greyed }
}
fn colours(self, dark: bool) -> [Color32; 4] {
match self {
Look::Normal => colours(&Tokens::get(dark), true),
Look::Greyed => colours(&Tokens::get(dark), false),
Look::AppBar => colours(&Tokens::dark(), true),
}
}
}
/// Icon textures by (id, look, pixel size) for one theme; `None` when the icon is missing or
/// does not rasterise, so it is not tried again every frame. The window draws icons at several
/// sizes at once (ribbon, browser, menus), so each size keeps its own texture; a change of theme
/// drops them all.
#[derive(Default)]
pub struct IconCache {
dark: Option<bool>,
textures: HashMap<(&'static str, Look, u32), Option<TextureHandle>>,
}
impl IconCache {
pub fn get(&mut self, ctx: &egui::Context, id: &'static str, dark: bool, look: Look, px: u32) -> Option<TextureHandle> {
if self.dark != Some(dark) {
self.textures.clear();
self.dark = Some(dark);
}
self.textures
.entry((id, look, px))
.or_insert_with(|| {
let svg = svg(id)?;
let image = rasterise(&recolour(svg, look.colours(dark)), px).map_err(|e| log::warn!("icon {id}: {e}")).ok()?;
Some(ctx.load_texture(format!("icon:{id}:{dark}:{look:?}:{px}"), image, egui::TextureOptions::LINEAR))
})
.clone()
}
}
/// Paint icon `id` into `rect` (a square); a missing icon draws a thin box so nothing is blank.
pub fn paint(app: &mut crate::ModelApp, ui: &egui::Ui, id: &'static str, rect: egui::Rect, look: Look) {
paint_tinted(app, ui, id, rect, look, Color32::WHITE);
}
/// [`paint`] multiplied by `tint` (a translucent white dims it).
pub fn paint_tinted(app: &mut crate::ModelApp, ui: &egui::Ui, id: &'static str, rect: egui::Rect, look: Look, tint: Color32) {
let ctx = ui.ctx();
let px = (rect.width().max(rect.height()) * ctx.pixels_per_point()).round().clamp(1.0, MAX_PX as f32) as u32;
let p = ui.painter();
match app.icons.get(ctx, id, app.ui.dark, look, px) {
Some(tex) => {
p.image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint);
}
None => {
let t = Tokens::get(app.ui.dark);
p.rect_stroke(rect.shrink(3.0), 3.0, egui::Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use modelcraft_engine::catalogue::CATALOGUE;
#[test]
fn every_catalogue_entry_has_an_icon_and_every_icon_an_entry() {
for c in CATALOGUE {
assert!(svg(c.id).is_some(), "no icon assets/icons/{}.svg", c.id);
}
for (id, _) in ICONS {
assert!(id.starts_with("ui.") || CATALOGUE.iter().any(|c| c.id == *id), "assets/icons/{id}.svg belongs to no catalogue entry");
}
assert!(ICONS.windows(2).all(|w| w[0].0 < w[1].0), "sorted for the binary search");
}
/// Icons use only the palette, so recolouring reaches every colour, and they rasterise.
#[test]
fn icons_use_only_palette_colours_and_rasterise() {
for (id, text) in ICONS {
for part in text.split('"').skip(1).step_by(2) {
if part.starts_with('#') {
assert!(PALETTE.contains(&part), "{id}: colour {part} is not in the palette");
}
}
let image = rasterise(text, 24).unwrap();
assert!(image.pixels.iter().any(|p| p.a() > 0), "{id} draws nothing");
}
}
/// Each role takes its own token, so recolouring never merges two roles into one colour.
#[test]
fn every_role_takes_a_distinct_theme_colour() {
for t in [Tokens::dark(), Tokens::light()] {
let c = colours(&t, true);
for i in 0..c.len() {
for j in i + 1..c.len() {
assert_ne!(c[i], c[j], "roles {i} and {j}");
}
}
}
}
#[test]
fn recolouring_follows_the_theme_and_greys_planned_entries() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0 L24 24" stroke="#4f9ce8" fill="#2d4e70"/></svg>"##;
let light = Tokens::light();
let out = recolour(svg, colours(&light, true));
let hex = |c: Color32| format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());
assert!(out.contains(&format!("stroke=\"{}\"", hex(light.accent))) && out.contains(&format!("fill=\"{}\"", hex(light.icon_fill))), "{out}");
let grey = recolour(svg, colours(&light, false));
let dim = light.border;
assert!(grey.contains(&format!("stroke=\"#{:02x}{:02x}{:02x}\"", dim.r(), dim.g(), dim.b())), "{grey}");
assert!(rasterise("not svg", 24).is_err());
assert_eq!(rasterise(svg, 100_000).unwrap().size, [MAX_PX as usize; 2]);
}
}