From 5f890e584e6c0ef545b23eee3087ad9d677a2ecc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:32:25 +0700 Subject: [PATCH 1/2] Web: ask to save before replacing the project or closing the tab The browser build threw unsaved changes away on New project, Open, Close, Open sample project or a dropped file, and when the tab closed. They now wait on the desktop's Save / Don't save / Cancel dialog (Save downloads the project), and closing or reloading the tab with unsaved changes makes the browser ask first. --- apps/texturecraft-web/Cargo.toml | 2 +- apps/texturecraft-web/src/web.rs | 21 +++++++++++++++++- crates/ui-egui/src/lib.rs | 5 ++++- crates/ui-egui/src/menus.rs | 1 - crates/ui-egui/src/state.rs | 5 ++++- crates/ui-egui/src/web_files.rs | 31 +++++++++++++++++++++------ crates/ui-egui/src/windows.rs | 8 +++---- crates/ui-egui/tests/close_unsaved.rs | 15 +++++++++++++ docs/features.md | 3 ++- 9 files changed, 75 insertions(+), 16 deletions(-) diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index b2d47259..e5512768 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -24,4 +24,4 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", " wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "EventTarget", "AddEventListenerOptions"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "BeforeUnloadEvent", "EventTarget", "AddEventListenerOptions"] } diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index 37752314..bc1372a5 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -1,5 +1,6 @@ //! The eframe web runner: canvas lookup, backend selection, the loading screen's startup steps, -//! browser shortcuts the app takes over, and startup errors shown in the page. +//! browser shortcuts the app takes over, the unsaved-changes guard on close, and startup errors +//! shown in the page. use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; @@ -14,6 +15,7 @@ const PROGRESS_ID: &str = "texturecraft_progress"; pub fn start() { eframe::WebLogger::init(log::LevelFilter::Info).ok(); capture_app_shortcuts(); + guard_unsaved_changes(); wasm_bindgen_futures::spawn_local(async { let Some(document) = web_sys::window().and_then(|w| w.document()) else { log::error!("no document"); @@ -118,6 +120,23 @@ fn capture_app_shortcuts() { on_key.forget(); } +/// Closing or reloading the tab with unsaved changes makes the browser ask first (it shows its +/// own message; pages can't word it). +fn guard_unsaved_changes() { + let Some(window) = web_sys::window() else { return }; + let on_unload = Closure::::new(|e: web_sys::BeforeUnloadEvent| { + if texturecraft_ui_egui::web_files::unsaved() { + e.prevent_default(); + // Browsers that predate `preventDefault` here read the return value. + e.set_return_value("unsaved"); + } + }); + if let Err(e) = window.add_event_listener_with_callback("beforeunload", on_unload.as_ref().unchecked_ref()) { + log::warn!("couldn't guard unsaved changes on close: {e:?}"); + } + 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). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5aa9f754..e6e99567 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -381,7 +381,10 @@ impl eframe::App for TextureCraftApp { self.autosave(now); i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] - keymap::sync_captured(&self.ui.keymap); + { + keymap::sync_captured(&self.ui.keymap); + web_files::sync_unsaved(self); + } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); menus::shortcuts(self, ctx); profile::drive(self, ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d5e5fe3c..3f83a1ad 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -117,7 +117,6 @@ pub fn implemented(id: &str) -> bool { /// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { - #[cfg(not(target_arch = "wasm32"))] if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ef0ab709..6db973dd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -76,7 +76,7 @@ pub struct Windows { /// The start window: new, open, recent projects (the app opens it at launch). #[serde(skip)] pub start: bool, - /// What waits on the unsaved-changes dialog: save, don't save or cancel (desktop). + /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, } @@ -88,7 +88,10 @@ pub enum Unsaved { /// A menu command (New project, Open, Close, Open sample project). Command(String), /// Open this project or mesh file. + #[cfg(not(target_arch = "wasm32"))] Open(String), + /// Open a project or mesh file's bytes (picked or dropped in the browser): its name and bytes. + Load(String, std::sync::Arc>), } /// Edit › Settings. diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 371a646a..3a7f9d6c 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -53,7 +53,7 @@ pub fn poll(app: &mut TextureCraftApp) { for (name, bytes, pick) in picked { let done = match pick { Pick::Open => { - load(app, &name, &bytes); + load(app, &name, bytes); continue; } Pick::Environment => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), @@ -106,12 +106,12 @@ fn use_environment(app: &mut TextureCraftApp, name: &str) { } /// Import an image as a project resource, or replace the session with a `.tcraft` project or a -/// mesh file's bytes (errors become toasts). -pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) { +/// mesh file's bytes, after asking to save unsaved changes (errors become toasts). +pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { let path = std::path::Path::new(name); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); if IMAGE_EXTS.contains(&ext.as_str()) { - match app.session.import_resource_bytes(name, bytes.to_vec()) { + match app.session.import_resource_bytes(name, bytes) { Ok(res) => { app.ui.dock.focus(crate::docking::Panel::Assets); app.toast(trf("Imported {name}", &[("name", &res)]), false); @@ -120,8 +120,12 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) { } return; } + let bytes = std::sync::Arc::new(bytes); + if crate::windows::ask_to_save(app, crate::state::Unsaved::Load(name.into(), bytes.clone())) { + return; + } let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled"); - let next = if ext == PROJECT_EXT { Session::from_project_bytes(bytes) } else { Session::from_mesh_bytes(name, bytes, MESH_RESOLUTION, stem) }; + let next = if ext == PROJECT_EXT { Session::from_project_bytes(&bytes) } else { Session::from_mesh_bytes(name, &bytes, MESH_RESOLUTION, stem) }; match next { Ok(next) => { app.session.switch_to(next); @@ -183,7 +187,9 @@ fn zip_files(files: &[ExportedFile]) -> Result, String> { } #[cfg(target_arch = "wasm32")] -pub use web::{download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_preset, open, save_project}; +pub use web::{ + download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_preset, open, save_project, sync_unsaved, unsaved, +}; #[cfg(target_arch = "wasm32")] mod web { @@ -191,6 +197,19 @@ mod web { use serde_json::Value; use wasm_bindgen::JsCast as _; + /// Whether the project has unsaved changes, for the page's `beforeunload` listener. + static UNSAVED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + + /// Refresh [`unsaved`] (once per frame). + pub fn sync_unsaved(app: &TextureCraftApp) { + UNSAVED.store(app.session.modified, std::sync::atomic::Ordering::Relaxed); + } + + /// Whether closing or reloading the page would lose unsaved changes. + pub fn unsaved() -> bool { + UNSAVED.load(std::sync::atomic::Ordering::Relaxed) + } + /// File › Open: the browser's file picker; the file loads on a later frame (see [`poll`]). pub fn open(ctx: &egui::Context) { pick(ctx, tr("Projects and meshes"), OPEN_EXTS, false, Pick::Open); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 68fd1214..6d44fc5f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -29,13 +29,11 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.mode == Mode::Baking { bake_bar(app, ctx); } - #[cfg(not(target_arch = "wasm32"))] unsaved(app, ctx); } /// Hold `then` (quitting, opening or closing a project) behind the unsaved-changes dialog when /// the project has unsaved changes; false when it can go ahead now. -#[cfg(not(target_arch = "wasm32"))] pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved) -> bool { if app.session.modified { app.ui.windows.unsaved = Some(then); @@ -43,8 +41,8 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved app.session.modified } -/// Quitting, opening or closing a project with unsaved changes asks whether to save them first. -#[cfg(not(target_arch = "wasm32"))] +/// Quitting, opening or closing a project with unsaved changes asks whether to save them first +/// (in the browser, Save downloads the project). fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { @@ -91,7 +89,9 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { match then { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), + #[cfg(not(target_arch = "wasm32"))] Unsaved::Open(path) => open_path(app, &path), + Unsaved::Load(name, bytes) => crate::web_files::load(app, &name, std::sync::Arc::unwrap_or_clone(bytes)), } } diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/close_unsaved.rs index 468634cc..9f518f18 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/close_unsaved.rs @@ -60,6 +60,21 @@ fn closing_without_changes_does_not_ask() { assert!(h.state().ui.windows.unsaved.is_none()); } +/// A project picked or dropped in the browser arrives as bytes; it waits on the same dialog. +#[test] +fn a_dropped_project_waits_on_the_dialog() { + let mut h = harness(true); + let dropped = texturecraft_engine::Session::new_project("Dropped", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + texturecraft_ui_egui::web_files::load(h.state_mut(), "dropped.tcraft", dropped.to_project_bytes().unwrap()); + h.run_steps(4); + assert!(matches!(h.state().ui.windows.unsaved, Some(Unsaved::Load(ref name, _)) if name == "dropped.tcraft"), "the dialog is open"); + assert_ne!(h.state().session.doc.project.name, "Dropped", "the project stays until answered"); + h.get_by_label("Don't save").click(); + h.run_steps(2); + assert_eq!(h.state().session.doc.project.name, "Dropped", "Don't save opens it"); + assert!(h.state().ui.windows.unsaved.is_none()); +} + #[test] fn closing_the_project_with_changes_asks_first() { let mut h = harness(true); diff --git a/docs/features.md b/docs/features.md index 090fdf77..4fd44e27 100644 --- a/docs/features.md +++ b/docs/features.md @@ -69,7 +69,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps and imported images. **Project templates** start new work from a saved setup. Closing the app, or opening, starting or closing another project, with unsaved changes asks whether to save them - first. + first (in the browser too, where Save downloads the project and closing or reloading the tab + asks before the changes are lost). ## Bake and export From 5e37a93e45c62aeb299b8be5ce6fa0c1987157ac Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:40:21 +0700 Subject: [PATCH 2/2] Color picker: our own picker with a copy icon from the icon set The picker's copy button was an emoji the bundled fonts don't draw, and it lives inside egui's picker. The swatch now opens a compact picker of its own: R, G and B values with a Phosphor copy button, a saturation/value square and a hue strip. Hue and saturation survive black, white and grays. The copy tooltip is translated into all nine other UI languages. --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/widgets.rs | 77 +++++++++++++++++++++++++++- crates/ui-egui/tests/color_picker.rs | 66 +++++++++++++++++++----- 11 files changed, 136 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 8abd47fe..c5594df2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -186,6 +186,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "التباين"), ("Contrast/Luminosity", "التباين / الإضاءة"), ("Converted maps", "الخرائط المحوّلة"), + ("Copy RGB values", "نسخ قيم RGB"), ("Copy from", "نسخ من"), ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 5a8b20e2..24f53398 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -198,6 +198,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Kontrast"), ("Contrast/Luminosity", "Kontrast/Luminanz"), ("Converted maps", "Konvertierte Maps"), + ("Copy RGB values", "RGB-Werte kopieren"), ("Copy from", "Kopieren aus"), ("Copy layer(s)", "Ebene(n) kopieren"), ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b100dba9..8a8aeb41 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -195,6 +195,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contraste"), ("Contrast/Luminosity", "Contraste/Luminosidad"), ("Converted maps", "Mapas convertidos"), + ("Copy RGB values", "Copiar los valores RGB"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar capa(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 486621d8..48dc5041 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -198,6 +198,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contraste"), ("Contrast/Luminosity", "Contraste/Luminosité"), ("Converted maps", "Cartes converties"), + ("Copy RGB values", "Copier les valeurs RVB"), ("Copy from", "Copier depuis"), ("Copy layer(s)", "Copier le(s) calque(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 3044f373..7bf2ccf8 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -201,6 +201,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contrasto"), ("Contrast/Luminosity", "Contrasto/Luminosità"), ("Converted maps", "Mappe convertite"), + ("Copy RGB values", "Copia i valori RGB"), ("Copy from", "Copia da"), ("Copy layer(s)", "Copia livello/i"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index db9a40f8..0bd7b115 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -198,6 +198,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "コントラスト"), ("Contrast/Luminosity", "コントラスト/輝度"), ("Converted maps", "変換マップ"), + ("Copy RGB values", "RGB 値をコピー"), ("Copy from", "コピー元"), ("Copy layer(s)", "レイヤーをコピー"), ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a8951370..1a9d3a98 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -189,6 +189,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "대비"), ("Contrast/Luminosity", "대비/광도"), ("Converted maps", "변환된 맵"), + ("Copy RGB values", "RGB 값 복사"), ("Copy from", "복사 원본"), ("Copy layer(s)", "레이어 복사"), ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e238c6ac..122d1160 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -195,6 +195,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contraste"), ("Contrast/Luminosity", "Contraste/Luminosidade"), ("Converted maps", "Mapas convertidos"), + ("Copy RGB values", "Copiar os valores RGB"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar camada(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 9a093a9f..974deb55 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -168,6 +168,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "对比度"), ("Contrast/Luminosity", "对比度/亮度"), ("Converted maps", "转换贴图"), + ("Copy RGB values", "复制 RGB 值"), ("Copy from", "复制自"), ("Copy layer(s)", "复制图层"), ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eb9469e8..86cc4310 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -209,8 +209,7 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) -> // Open state lives in memory (`toggle_id` above); `from_response` alone shows it always. egui::Popup::from_response(&resp).id(popup).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { // Wider than the R, G, B row at any value, so the popup keeps one size and place. - ui.spacing_mut().slider_width = 275.0; - if egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque) { + if color_picker(ui, popup.with("picker"), &mut c, 275.0) { let lin = [c.r(), c.g(), c.b()].map(|v| texturecraft_engine::texel::srgb_to_linear(v as f32 / 255.0)); *linear = lin; changed = true; @@ -219,6 +218,80 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) -> changed } +/// A color picker `width` wide: R, G, B (sRGB 0–255) with a copy button, a saturation/value +/// square and a hue strip. Returns true when the color changed. +fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool { + use egui::ecolor::{hsv_from_rgb, rgb_from_hsv}; + let tk = Tokens::get(ui.ctx()); + let mut srgb = [c.r(), c.g(), c.b()]; + let hsv_of = |srgb: [u8; 3]| hsv_from_rgb(srgb.map(|v| v as f32 / 255.0)); + // Remembered with the color it was for, so hue and saturation survive black, white and grays. + let (mut h, mut s, mut v) = ui.data(|d| d.get_temp::<(Color32, (f32, f32, f32))>(id)).filter(|(k, _)| k == c).map_or_else(|| hsv_of(srgb), |(_, hsv)| hsv); + let mut typed = false; + let mut dragged = false; + ui.horizontal(|ui| { + for (x, prefix) in srgb.iter_mut().zip(["R ", "G ", "B "]) { + typed |= ui.add(egui::DragValue::new(x).speed(0.5).prefix(prefix)).changed(); + } + if icon_button(ui, egui_phosphor::regular::COPY, crate::i18n::tr("Copy RGB values"), false, 20.0).clicked() { + ui.copy_text(format!("{}, {}, {}", srgb[0], srgb[1], srgb[2])); + } + }); + if typed { + (h, s, v) = hsv_of(srgb); + } + let border = Stroke::new(1.0, tk.field_border); + // Saturation across, value up. + let (rect, resp) = ui.allocate_exact_size(vec2(width, width), Sense::click_and_drag()); + if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) { + (s, v) = (((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0), 1.0 - ((p.y - rect.top()) / rect.height()).clamp(0.0, 1.0)); + dragged = true; + } + gradient(ui.painter(), rect, |x, y| rgb_from_hsv((h, x, 1.0 - y))); + ui.painter().rect_stroke(rect, 0.0, border, egui::StrokeKind::Inside); + let at = rect.lerp_inside(vec2(s, 1.0 - v)); + ui.painter().circle_stroke(at, 5.0, Stroke::new(2.0, Color32::WHITE)); + ui.painter().circle_stroke(at, 6.5, Stroke::new(1.0, Color32::BLACK)); + let (rect, resp) = ui.allocate_exact_size(vec2(width, 16.0), Sense::click_and_drag()); + if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) { + h = ((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0); + dragged = true; + } + gradient(ui.painter(), rect, |x, _| rgb_from_hsv((x, 1.0, 1.0))); + ui.painter().rect_stroke(rect, 0.0, border, egui::StrokeKind::Inside); + let x = rect.left() + rect.width() * h; + ui.painter().rect_stroke(egui::Rect::from_x_y_ranges(x - 2.0..=x + 2.0, rect.y_range()), 1.0, Stroke::new(1.5, Color32::WHITE), egui::StrokeKind::Middle); + if dragged { + srgb = rgb_from_hsv((h, s, v)).map(|x| (x * 255.0 + 0.5) as u8); + } + let next = Color32::from_rgb(srgb[0], srgb[1], srgb[2]); + ui.data_mut(|d| d.insert_temp(id, (next, (h, s, v)))); + let changed = next != *c; + *c = next; + changed +} + +/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh. +fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { + const N: u32 = 24; + let mut mesh = egui::Mesh::default(); + for j in 0..=N { + for i in 0..=N { + let (x, y) = (i as f32 / N as f32, j as f32 / N as f32); + let [r, g, b] = rgb(x, y).map(|c| (c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b)); + } + } + for j in 0..N { + for i in 0..N { + let k = j * (N + 1) + i; + mesh.add_triangle(k, k + 1, k + N + 1); + mesh.add_triangle(k + 1, k + N + 2, k + N + 1); + } + } + painter.add(mesh); +} + /// Panel title row with optional trailing content. pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/tests/color_picker.rs b/crates/ui-egui/tests/color_picker.rs index dd9bbf53..6457a749 100644 --- a/crates/ui-egui/tests/color_picker.rs +++ b/crates/ui-egui/tests/color_picker.rs @@ -1,35 +1,73 @@ -//! The color picker popup keeps its place while the color changes. +//! The color picker popup keeps its place while the color changes, picks from its square and hue +//! strip, and copies its values. use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::{theme, widgets}; -/// The left edge of the picker's R value. -fn r_left(h: &Harness<'_, [f32; 3]>) -> f32 { - h.get_all_by_role(Role::SpinButton).next().unwrap().rect().left() -} - -#[test] -fn the_popup_stays_put_while_the_color_changes() { - // A swatch at the right edge of the window, like the Properties panel's. - // The picker's copy button is an emoji the bundled fonts do not draw. - let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).allow_missing_glyphs().build_ui_state( +/// A swatch at the right edge of the window, like the Properties panel's, with its picker open. +fn open_picker(color: [f32; 3]) -> Harness<'static, [f32; 3]> { + let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( |ui, color: &mut [f32; 3]| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { widgets::color_swatch(ui, "color", color, 120.0); }); }, - [1.0; 3], + color, ); + h.ctx.set_fonts(theme::font_definitions()); theme::apply(&h.ctx, theme::Brightness::default(), theme::Accent::default()); h.run_steps(2); let swatch = egui::pos2(800.0 - 60.0, 9.0); h.drag_at(swatch); h.drop_at(swatch); h.run_steps(3); - let bright = r_left(&h); + h +} + +/// The picker's R value. +fn r_value(h: &Harness<'_, [f32; 3]>) -> egui::Rect { + h.get_all_by_role(Role::SpinButton).next().unwrap().rect() +} + +/// Click at `p` and let the picker apply it. +fn click(h: &mut Harness<'_, [f32; 3]>, p: egui::Pos2) { + h.drag_at(p); + h.drop_at(p); + h.run_steps(3); +} + +#[test] +fn the_popup_stays_put_while_the_color_changes() { + let mut h = open_picker([1.0; 3]); + let bright = r_value(&h).left(); *h.state_mut() = [0.001; 3]; h.run_steps(3); - assert_eq!(r_left(&h), bright, "the picker does not move when R, G and B lose digits"); + assert_eq!(r_value(&h).left(), bright, "the picker does not move when R, G and B lose digits"); +} + +#[test] +fn the_square_and_the_hue_strip_pick_the_color() { + let mut h = open_picker([1.0; 3]); + // The square starts a row below the values; its bottom-left corner is black. + let r = r_value(&h); + let square = egui::Rect::from_min_size(egui::pos2(r.left() + 1.0, r.bottom() + 8.0), egui::vec2(273.0, 273.0)); + click(&mut h, square.left_bottom() + egui::vec2(2.0, -6.0)); + assert!(h.state().iter().all(|c| *c < 0.01), "black: {:?}", h.state()); + // Full saturation and value, then a hue a third of the way along: green. + click(&mut h, square.right_top() + egui::vec2(-1.0, 1.0)); + let strip = square.bottom() + 14.0; + click(&mut h, egui::pos2(square.left() + 275.0 / 3.0, strip)); + let [r, g, b] = *h.state(); + assert!(g > 0.9 && r < 0.05 && b < 0.05, "green: {:?}", h.state()); +} + +#[test] +fn the_copy_button_copies_the_rgb_values() { + let mut h = open_picker([1.0, 0.0, 0.0]); + h.get_by_label("Copy RGB values").click(); + h.step(); + let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == "255, 0, 0")); + assert!(copied, "{:?}", h.output().platform_output.commands); }