SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Color picker: add Hex alongside U8 and F (#7445) (#7450)
mynoc75035ac4a58d
diff --git a/assets/locales/pending/hex-color-picker.json b/assets/locales/pending/hex-color-picker.jsonnew file mode 100644index 0000000000..83c211c67a--- /dev/null+++ b/assets/locales/pending/hex-color-picker.json@@ -0,0 +1,42 @@+{+ "en": {+ "color.hex": "Hex",+ "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",+ "color.hex_hint": "#rrggbb"+ },+ "ar": {+ "color.hex": "Hex",+ "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",+ "color.hex_hint": "#rrggbb"+ },+ "de": {+ "color.hex": "Hex",+ "color.hex_help": "#rrggbb oder #rrggbbaa eingeben; sechs Ziffern behalten die Deckkraft bei",+ "color.hex_hint": "#rrggbb"+ },+ "he": {+ "color.hex": "Hex",+ "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",+ "color.hex_hint": "#rrggbb"+ },+ "ja": {+ "color.hex": "Hex",+ "color.hex_help": "#rrggbb または #rrggbbaa を入力。6 桁の場合は不透明度を維持",+ "color.hex_hint": "#rrggbb"+ },+ "ko": {+ "color.hex": "Hex",+ "color.hex_help": "#rrggbb 또는 #rrggbbaa 입력. 6자리 값은 불투명도 유지",+ "color.hex_hint": "#rrggbb"+ },+ "vi": {+ "color.hex": "Hex",+ "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",+ "color.hex_hint": "#rrggbb"+ },+ "zh": {+ "color.hex": "Hex",+ "color.hex_help": "输入 #rrggbb 或 #rrggbbaa;六位数保留不透明度",+ "color.hex_hint": "#rrggbb"+ }+}diff --git a/crates/ui-egui/src/dialogs_appearance.rs b/crates/ui-egui/src/dialogs_appearance.rsindex 13d36d2559..e9cd30d452 100644--- a/crates/ui-egui/src/dialogs_appearance.rs+++ b/crates/ui-egui/src/dialogs_appearance.rs@@ -398,9 +398,9 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel}}ui_kit::row(ui, "Colour", |ui| {- let mut rgb = k.color;- if ui_kit::color_field(ui, &mut rgb).changed() {- k.color = rgb;+ let response =+ if k.pbr.is_none() { ui_kit::color_field_with_opacity(ui, &mut k.color, &mut k.opacity) } else { ui_kit::color_field(ui, &mut k.color) };+ if response.changed() {detach_preset(k);k.look = None;k.remove_override = false;@@ -767,6 +767,69 @@ mod tests {}}+ #[test]+ fn hex_picker_preserves_precise_opacity_and_applies_alpha_without_losing_rgb_or_pbr() {+ let mut h = crate::scenario::Harness::new();+ h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap();+ h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":"#abcdef","opacity":0.123456,"appearance":"Named tint"})).unwrap();+ h.app.session.selection = vec![Sel::Body { name: "Body1".into() }];+ h.app.start("appearance.assign");+ h.frames(3);+ h.step(&json!({"click":{"handle":"dialog:color:Colour"}})).unwrap();+ for mode in ["Hex", "F", "U8", "Hex"] {+ h.step(&json!({"click":{"handle":format!("color:format:{mode}")}})).unwrap();+ let Kind::Appearance(k) = &h.app.dialog.as_ref().unwrap().kind else { panic!("appearance editor") };+ assert_eq!((k.color, k.opacity, k.look.as_deref()), ([171, 205, 239], 0.123456, Some("Named tint")));+ }+ let paste = |h: &mut crate::scenario::Harness, text: &str| {+ h.step(&json!({"click":{"handle":"color:hex"}})).unwrap();+ h.step(&json!({"key":"A","cmd":true,"ctrl":true})).unwrap();+ h.frame_with(vec![egui::Event::Paste(text.into())]);+ };+ for text in ["#abc", "#abcdefz0"] {+ paste(&mut h, text);+ h.frames(2);+ let Kind::Appearance(k) = &h.app.dialog.as_ref().unwrap().kind else { panic!("appearance editor") };+ assert_eq!((k.color, k.opacity, k.look.as_deref()), ([171, 205, 239], 0.123456, Some("Named tint")));+ assert!(h.widget(text).is_some(), "invalid text remains editable");+ }+ for (text, color, opacity) in [+ ("#AbCdEf", [171, 205, 239], 0.123456),+ ("#AbCdEf80", [171, 205, 239], 128.0 / 255.0),+ ("#0102fe00", [1, 2, 254], 0.0),+ ("#fE8001", [254, 128, 1], 0.0),+ ] {+ paste(&mut h, text);+ let Kind::Appearance(k) = &h.app.dialog.as_ref().unwrap().kind else { panic!("appearance editor") };+ assert_eq!((k.color, k.opacity), (color, opacity), "{text} applies immediately without premultiplying RGB");+ if text == "#AbCdEf" {+ assert_eq!(k.look.as_deref(), Some("Named tint"), "re-entering unchanged RGB is not a manual colour change");+ }+ if text.len() == 9 {+ assert!(k.look.is_none() && k.preset_id.is_none(), "an alpha-only colour edit also detaches the named look");+ }+ }+ let copy = crate::scenario::handle_at("color:copy").unwrap();+ h.frame_with(crate::test_support::pointer(copy, true));+ h.frame_with(crate::test_support::pointer(copy, false));+ assert!(+ h.output.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyText(text) if text.eq_ignore_ascii_case("#fe8001")))+ );+ let Kind::Appearance(k) = &mut h.app.dialog.as_mut().unwrap().kind else { panic!("appearance editor") };+ k.opacity = 0.25;+ h.frames(2);+ assert!(h.widget("#fe800140").is_some(), "external opacity edits synchronise the displayed Hex text");+ h.step(&json!({"click":{"handle":"dialog:color:Colour"}})).unwrap();+ h.step(&json!({"click":{"handle":"appearance:pbr"}})).unwrap();+ h.step(&json!({"click":{"handle":"dialog:color:Colour"}})).unwrap();+ paste(&mut h, "#22334480");+ let Kind::Appearance(k) = &h.app.dialog.as_ref().unwrap().kind else { panic!("appearance editor") };+ assert_eq!((k.color, k.opacity, k.pbr), ([254, 128, 1], 1.0, Some(PbrParameters::default())));+ paste(&mut h, "#223344ff");+ let Kind::Appearance(k) = &h.app.dialog.as_ref().unwrap().kind else { panic!("appearance editor") };+ assert_eq!((k.color, k.opacity, k.pbr), ([34, 51, 68], 1.0, Some(PbrParameters::default())));+ }+#[test]fn immediate_apply_then_ok_has_one_undo_and_retains_precise_opacity() {let mut a = app();diff --git a/crates/ui-egui/src/render_ui/appearance.rs b/crates/ui-egui/src/render_ui/appearance.rsindex 5c5c7a03c4..36265c03b2 100644--- a/crates/ui-egui/src/render_ui/appearance.rs+++ b/crates/ui-egui/src/render_ui/appearance.rs@@ -24,6 +24,13 @@ pub(super) struct View {replacements: Vec<dialogs_appearance::Look>,}+#[cfg(test)]+impl View {+ pub(super) fn draft(&self) -> Option<&Look> {+ self.draft.as_ref()+ }+}+#[derive(Clone, Debug, Default)]pub(super) struct Targets {items: Vec<Sel>,@@ -498,7 +505,9 @@ fn draw(app: &mut SolveApp, ui: &mut egui::Ui, view: &mut View, selected: &Targelet editable = step != LookStep::Material && (!edit_targets.items.is_empty() || !edit_targets.components.is_empty());ui.add_enabled_ui(editable, |ui| {ui_kit::row(ui, app.tr("render.inspector_colour"), |ui| {- let response = ui_kit::color_hex_field(ui, &mut draft.color, mixed(&looks, |l| l.color).then(|| app.tr("render.tree_mixed")));+ let opacity = draft.pbr.is_none().then_some(&mut draft.opacity);+ let response =+ ui_kit::mixed_color_field(ui, &mut draft.color, opacity, mixed(&looks, |l| l.color).then(|| app.tr("render.tree_mixed")));view.dirty |= response.changed();commit |= ended(&response, ui);});diff --git a/crates/ui-egui/src/render_workspace_inspector_tests.rs b/crates/ui-egui/src/render_workspace_inspector_tests.rsindex 4bbf02c32d..006904a169 100644--- a/crates/ui-egui/src/render_workspace_inspector_tests.rs+++ b/crates/ui-egui/src/render_workspace_inspector_tests.rs@@ -1532,7 +1532,8 @@ fn appearance_inspector_hex_edits_validate_and_commit_once() {h.frames(3);let before = h.app.session.doc.to_json();let undo = h.app.session.undo.len();- let hex = format!("dialog:color_hex:{}", h.app.tr("render.inspector_colour"));+ appearance_picker_open(&mut h);+ let hex = "color:hex";h.step(&json!({"click":{"handle":hex}})).unwrap();h.step(&json!({"key":"A","cmd":true,"ctrl":true})).unwrap();h.step(&json!({"text":"#GG0000"})).unwrap();@@ -1550,6 +1551,9 @@ fn appearance_inspector_hex_edits_validate_and_commit_once() {h.app.session.selection.push(Sel::Body { name: "Other".into() });h.frames(3);let mixed_before = h.app.session.doc.to_json();+ if crate::scenario::handle_at(hex).is_none() {+ appearance_picker_open(&mut h);+ }h.step(&json!({"click":{"handle":hex}})).unwrap();h.step(&json!({"key":"Tab"})).unwrap();assert_eq!(h.app.session.doc.to_json(), mixed_before);@@ -1560,6 +1564,128 @@ fn appearance_inspector_hex_edits_validate_and_commit_once() {assert_eq!(h.app.session.doc.appearances.bodies["Other"].color, [0x12, 0x34, 0x56]);}+fn appearance_picker_open(h: &mut Harness) {+ h.step(&json!({"click":{"handle":format!("dialog:color:{}", h.app.tr("render.inspector_colour"))}})).unwrap();+ h.frames(2);+ h.step(&json!({"click":{"handle":"color:format:Hex"}})).unwrap();+}++fn appearance_picker_paste(h: &mut Harness, text: &str) {+ h.step(&json!({"click":{"handle":"color:hex"}})).unwrap();+ h.step(&json!({"key":"A","cmd":true,"ctrl":true})).unwrap();+ h.frame_with(vec![egui::Event::Paste(text.into())]);+}++#[test]+fn appearance_inspector_shared_picker_preserves_exact_opacity_and_commits_alpha() {+ use solidcraft_engine::Sel;+ let mut h = fixture();+ h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#abcdef","opacity":0.123456,"appearance":"Tint"})).unwrap();+ h.app.session.selection = vec![Sel::Body { name: "Subject".into() }];+ h.app.run("view.render_stage", json!({"stage":"look"})).unwrap();+ h.frames(3);+ let mass = h.app.run("component.properties", json!({})).unwrap();+ appearance_picker_open(&mut h);+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ for mode in ["F", "U8", "Hex"] {+ h.step(&json!({"click":{"handle":format!("color:format:{mode}")}})).unwrap();+ let draft = h.app.render_workspace.view.inspector.selection_appearance.draft().unwrap();+ assert_eq!((draft.color, draft.opacity, draft.pbr), ([171, 205, 239], 0.123456, None));+ }+ for text in ["#abc", "#abcdefz0"] {+ appearance_picker_paste(&mut h, text);+ h.frames(2);+ let draft = h.app.render_workspace.view.inspector.selection_appearance.draft().unwrap();+ assert_eq!((draft.color, draft.opacity), ([171, 205, 239], 0.123456));+ assert!(h.widget(text).is_some(), "invalid text remains editable inside the picker");+ assert_eq!(h.app.session.doc.to_json(), before);+ assert_eq!(h.app.session.undo.len(), undo);+ }+ for (text, color, opacity) in [+ ("#0102fe", [1, 2, 254], 0.123456),+ ("#0102fe80", [1, 2, 254], 128.0 / 255.0),+ ("#fE8001", [254, 128, 1], 128.0 / 255.0),+ ("#22334400", [34, 51, 68], 0.0),+ ] {+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ appearance_picker_paste(&mut h, text);+ let draft = h.app.render_workspace.view.inspector.selection_appearance.draft().unwrap();+ assert_eq!((draft.color, draft.opacity, draft.pbr), (color, opacity, None), "{text} updates the exact draft immediately");+ assert_eq!(h.app.session.doc.to_json(), before, "typing does not commit the model");+ assert_eq!(h.app.session.undo.len(), undo);+ h.step(&json!({"key":"Enter"})).unwrap();+ h.frames(2);+ let look = &h.app.session.doc.appearances.bodies["Subject"];+ assert_eq!((look.color, look.opacity, look.pbr), (color, opacity, None));+ assert_eq!(h.app.session.undo.len(), undo + 1, "one committed edit for {text}");+ }+ assert_eq!(h.app.run("component.properties", json!({})).unwrap(), mass);+}++#[test]+fn appearance_inspector_shared_picker_pbr_rejects_nonopaque_alpha() {+ use solidcraft_engine::Sel;+ let mut h = fixture();+ h.app+ .run("appearance.assign", json!({"bodies":["Subject"],"color":"#123456", "pbr":{"metallic":0.2,"roughness":0.4,"dielectric_ior":1.6}}))+ .unwrap();+ h.app.session.selection = vec![Sel::Body { name: "Subject".into() }];+ h.app.run("view.render_stage", json!({"stage":"look"})).unwrap();+ h.frames(3);+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ let pbr = h.app.session.doc.appearances.bodies["Subject"].pbr;+ appearance_picker_open(&mut h);+ for text in ["#abcdef80", "#abcdef00"] {+ appearance_picker_paste(&mut h, text);+ let draft = h.app.render_workspace.view.inspector.selection_appearance.draft().unwrap();+ assert_eq!((draft.color, draft.opacity, draft.pbr), ([18, 52, 86], 1.0, pbr));+ assert!(h.widget(text).is_some());+ h.step(&json!({"key":"Enter"})).unwrap();+ assert_eq!(h.app.session.doc.to_json(), before);+ assert_eq!(h.app.session.undo.len(), undo);+ }+ appearance_picker_paste(&mut h, "#abcdefFF");+ h.step(&json!({"key":"Enter"})).unwrap();+ let look = &h.app.session.doc.appearances.bodies["Subject"];+ assert_eq!((look.color, look.opacity, look.pbr), ([171, 205, 239], 1.0, pbr));+ assert_eq!(h.app.session.undo.len(), undo + 1);+}++#[test]+fn appearance_inspector_shared_picker_has_no_outer_hex_editor_and_keeps_mixed_values_visible() {+ use solidcraft_engine::Sel;+ let mut h = fixture();+ h.app.run("solid.box", json!({"body_name":"Other","length":5,"width":5,"height":5,"corner":[30,0,0]})).unwrap();+ for (body, color) in [("Subject", "#123456"), ("Other", "#abcdef")] {+ h.app.run("appearance.assign", json!({"bodies":[body],"color":color,"opacity":0.123456})).unwrap();+ }+ h.app.session.selection = vec![Sel::Body { name: "Subject".into() }, Sel::Body { name: "Other".into() }];+ h.app.run("view.render_stage", json!({"stage":"look"})).unwrap();+ h.frames(3);+ let outer = format!("dialog:color_hex:{}", h.app.tr("render.inspector_colour"));+ assert!(crate::scenario::handle_at(&outer).is_none(), "Hex editing belongs only inside the shared picker");+ assert!(crate::scenario::rect_of("dialog:note:color:mixed").is_some(), "mixed colour remains visibly labelled beside the swatch");+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ appearance_picker_open(&mut h);+ assert!(crate::scenario::handle_at(&outer).is_none());+ assert!(crate::scenario::handle_at("color:hex").is_some());+ h.step(&json!({"click":{"handle":"color:hex"}})).unwrap();+ h.step(&json!({"key":"Tab"})).unwrap();+ assert_eq!(h.app.session.doc.to_json(), before, "opening and leaving mixed input is inert");+ assert_eq!(h.app.session.undo.len(), undo);+ appearance_picker_paste(&mut h, "#123456");+ h.step(&json!({"key":"Enter"})).unwrap();+ for body in ["Subject", "Other"] {+ let look = &h.app.session.doc.appearances.bodies[body];+ assert_eq!((look.color, look.opacity, look.pbr), ([18, 52, 86], 0.123456, None));+ }+ assert_eq!(h.app.session.undo.len(), undo + 1, "accepting the first colour still sets mixed targets once");+}+#[test]fn appearance_inspector_component_and_face_overrides_remove_to_material_from_real_controls() {use solidcraft_engine::{Sel, geom::Vec3};diff --git a/crates/ui-egui/src/ui_kit/color.rs b/crates/ui-egui/src/ui_kit/color.rsindex f73c27646a..aaf5a54532 100644--- a/crates/ui-egui/src/ui_kit/color.rs+++ b/crates/ui-egui/src/ui_kit/color.rs@@ -1,4 +1,4 @@-//! Opaque document RGB editing. Interface paint uses tokens; the gradients are colour data.+//! Document RGB and optional separate opacity editing. Interface paint uses tokens; gradients are colour data.use super::{layout::label, metrics::dimension};use crate::ui_kit::{Container, Surface};use crate::{i18n, scenario, theme::Tokens};@@ -43,6 +43,26 @@ pub(crate) fn linear_color_field(ui: &mut Ui, rgb: &mut [f64; 3], maximum: f64)/// Shared colour button and outside-click-dismissed popover. Retains the enclosing row handle.pub(crate) fn color_field(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response {+ color_field_inner(ui, rgb, None, false)+}++/// The same picker, editing the caller's exact opacity without premultiplying RGB.+/// Call the opaque `color_field` instead when transparency is prohibited (including PBR).+pub(crate) fn color_field_with_opacity(ui: &mut Ui, rgb: &mut [u8; 3], opacity: &mut f64) -> Response {+ color_field_inner(ui, rgb, Some(opacity), false)+}++/// The same picker with a non-editable mixed-value label. Pass no opacity for opaque/PBR callers.+/// Explicitly accepting the first colour still reports an edit when targets have mixed colours.+pub(crate) fn mixed_color_field(ui: &mut Ui, rgb: &mut [u8; 3], opacity: Option<&mut f64>, mixed: Option<&str>) -> Response {+ let response = color_field_inner(ui, rgb, opacity, mixed.is_some());+ if let Some(mixed) = mixed {+ super::text(ui, mixed, super::Text::Note("color:mixed"));+ }+ response+}++fn color_field_inner(ui: &mut Ui, rgb: &mut [u8; 3], opacity: Option<&mut f64>, mixed: bool) -> Response {let t = Tokens::get();let (rect, mut response) = ui.allocate_exact_size(vec2(t.control_height + t.space_6, t.control_height), Sense::click());ui.painter().rect(@@ -68,7 +88,7 @@ pub(crate) fn color_field(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response {).show(|ui| {super::scope(ui, |ui| {- edited = color_popover(ui, rgb);+ edited = if opacity.is_some() || mixed { color_popover_with_opacity(ui, rgb, opacity, mixed) } else { color_popover(ui, rgb) };});});if edited {@@ -78,42 +98,13 @@ pub(crate) fn color_field(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response {if ui.style().explanation_tooltips { response.on_hover_text(i18n::tr("color.edit")) } else { response }}-/// A colour swatch and editable hexadecimal field; incomplete text remains local until valid.-pub(crate) fn color_hex_field(ui: &mut Ui, rgb: &mut [u8; 3], mixed: Option<&str>) -> Response {- let id = ui.id().with(("color_hex", label(ui)));- let current = format!("#{:02X}{:02X}{:02X}", rgb[0], rgb[1], rgb[2]);- let is_mixed = mixed.is_some();- let initial = || if is_mixed { String::new() } else { current.clone() };- let (observed, was_mixed, mut hex) = ui.ctx().data(|d| d.get_temp::<([u8; 3], bool, String)>(id)).unwrap_or_else(|| (*rgb, is_mixed, initial()));- if observed != *rgb || was_mixed != is_mixed {- hex = initial();- }- let mut response = color_field(ui, rgb);- if response.changed() {- hex = format!("#{:02X}{:02X}{:02X}", rgb[0], rgb[1], rgb[2]);- }- let mut field = super::bounded_cell_editor(ui, id.with("field"), &mut hex, mixed.unwrap_or("#RRGGBB"), false, 32);- scenario::publish_target(&format!("dialog:color_hex:{}", label(ui)), field.rect);- let mut valid = false;- if field.changed() {- let text = hex.trim();- let digits = text.strip_prefix('#').unwrap_or(text);- if digits.len() == 6- && let Ok(value) = u32::from_str_radix(digits, 16)- {- *rgb = [(value >> 16) as u8, (value >> 8) as u8, value as u8];- valid = true;- response.mark_changed();- }- }- field.flags.set(egui::response::Flags::CHANGED, valid);- ui.ctx().data_mut(|d| d.insert_temp(id, (*rgb, is_mixed, hex)));- response.union(field)-}-/// Popover body, also rendered independently by the gallery. Format is global, alpha is opaque./// Tokens: form_card_width, control_*, form_*, on_accent, border, radius_xl, font_small, space_*.pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {+ color_popover_with_opacity(ui, rgb, None, false)+}++fn color_popover_with_opacity(ui: &mut Ui, rgb: &mut [u8; 3], mut opacity: Option<&mut f64>, mixed: bool) -> bool {let t = Tokens::get();ui.style_mut().drag_value_text_style = egui::TextStyle::Monospace;let id = ui.id().with("color_hsv");@@ -122,23 +113,37 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {let (saved, hsv) = ui.ctx().data(|d| d.get_temp::<([u8; 3], HsvaGamma)>(id)).unwrap_or((*rgb, color.into()));let mut hsv = if saved == *rgb { hsv } else { color.into() };let before = hsv;+ let before_rgb = *rgb;+ let before_opacity = opacity.as_deref().copied();+ let hex_id = ui.id().with("color_hex");+ let mut hex = ui.ctx().data(|d| d.get_temp::<HexEdit>(hex_id)).unwrap_or_else(|| HexEdit::new(*rgb, before_opacity));+ hex.sync(*rgb, before_opacity);+ let format_id = egui::Id::new("color_hex_format");+ let mut hexadecimal = ui.ctx().data(|d| d.get_temp::<bool>(format_id)).unwrap_or(false);let mut linear = ui.global_style().visuals.numeric_color_space == egui::style::NumericColorSpace::Linear;+ let mut accepted_mixed = false;ui.vertical(|ui| {ui.spacing_mut().item_spacing.y = t.space_10;ui.horizontal(|ui| {- let mut selected = usize::from(linear);- ui.allocate_ui(vec2(t.control_height * 3.0, t.control_height), |ui| {- super::segmented(ui, &mut selected, &["U8", "F"], super::Segments { compact: true, primary: true, ..Default::default() });+ let mut selected = if hexadecimal { 2 } else { usize::from(linear) };+ ui.allocate_ui(vec2(t.control_height * 4.0 + t.space_12, t.control_height), |ui| {+ super::segmented(+ ui,+ &mut selected,+ &["U8", "F", i18n::tr("color.hex")],+ super::Segments { compact: true, primary: true, ..Default::default() },+ );let rect = ui.min_rect();- for (index, key) in ["color.gamma", "color.linear"].iter().enumerate() {+ for (index, (key, name)) in [("color.gamma", "U8"), ("color.linear", "F"), ("color.hex_help", "Hex")].iter().enumerate() {let rect =- egui::Rect::from_min_size(rect.min + vec2(index as f32 * rect.width() / 2.0, 0.0), vec2(rect.width() / 2.0, rect.height()));+ egui::Rect::from_min_size(rect.min + vec2(index as f32 * rect.width() / 3.0, 0.0), vec2(rect.width() / 3.0, rect.height()));ui.interact(rect, ui.id().with(("format_tip", index)), Sense::hover()).on_hover_text(i18n::tr(key));- scenario::publish_handle(&format!("color:format:{}", if index == 0 { "U8" } else { "F" }), rect.center());+ scenario::publish_handle(&format!("color:format:{name}"), rect.center());}});- linear = selected == 1;- if selected != usize::from(ui.global_style().visuals.numeric_color_space == egui::style::NumericColorSpace::Linear) {+ hexadecimal = selected == 2;+ if !hexadecimal && (selected == 1) != linear {+ linear = selected == 1;ui.ctx().all_styles_mut(|s| {s.visuals.numeric_color_space =if linear { egui::style::NumericColorSpace::Linear } else { egui::style::NumericColorSpace::GammaByte }@@ -151,7 +156,13 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {if copy.clicked() {let [r, g, b] = *rgb;let [lr, lg, lb, _] = egui::Rgba::from(color).to_array();- ui.ctx().copy_text(if linear { format!("{lr:.03}, {lg:.03}, {lb:.03}") } else { format!("{r}, {g}, {b}") });+ ui.ctx().copy_text(if hexadecimal {+ hex.accepted.clone()+ } else if linear {+ format!("{lr:.03}, {lg:.03}, {lb:.03}")+ } else {+ format!("{r}, {g}, {b}")+ });}});});@@ -162,29 +173,54 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {rgb.map(f64::from)};let mut edited = false;- ui.columns(3, |columns| {- for ((ui, channel), name) in columns.iter_mut().zip(channels.iter_mut()).zip(["R", "G", "B"]) {- ui.vertical(|ui| {- ui.spacing_mut().item_spacing.y = t.space_3;- ui.add(egui::Label::new(egui::RichText::new(name).size(t.font_small).color(t.form_dim)));- let response = ui.add_sized(- vec2(dimension(ui.available_width()), t.control_height),- egui::DragValue::new(channel)- .range(0.0..=if linear { 1.0 } else { 255.0 })- .speed(if linear { 0.003 } else { 0.5 })- .custom_parser(crate::prefs::parse_number)- .custom_formatter(move |v, _| if linear { format!("{v:.03}") } else { format!("{v:.0}") }),- );- response.widget_info(|| {- let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), *channel);- info.label = Some(name.into());- info+ if hexadecimal {+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = t.space_3;+ ui.add(egui::Label::new(egui::RichText::new(i18n::tr("color.hex")).size(t.font_small).color(t.form_dim)));+ let response = super::cell_editor(ui, hex_id.with("input"), &mut hex.draft, i18n::tr("color.hex_hint"), false)+ .on_hover_text(i18n::tr("color.hex_help"));+ publish("color:hex", &response);+ if response.changed()+ && let Some((value, alpha)) = parse_hex(&hex.draft)+ && (opacity.is_some() || alpha.is_none_or(|a| a == 255))+ {+ accepted_mixed = mixed;+ *rgb = value;+ if let (Some(opacity), Some(alpha)) = (opacity.as_deref_mut(), alpha) {+ *opacity = f64::from(alpha) / 255.0;+ }+ hex.alpha = alpha.is_some();+ hex.set(*rgb, opacity.as_deref().copied());+ if *rgb != before_rgb {+ hsv = crate::theme::srgb(rgb.map(|c| f32::from(c) / 255.0)).into();+ }+ }+ });+ } else {+ ui.columns(3, |columns| {+ for ((ui, channel), name) in columns.iter_mut().zip(channels.iter_mut()).zip(["R", "G", "B"]) {+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = t.space_3;+ ui.add(egui::Label::new(egui::RichText::new(name).size(t.font_small).color(t.form_dim)));+ let response = ui.add_sized(+ vec2(dimension(ui.available_width()), t.control_height),+ egui::DragValue::new(channel)+ .range(0.0..=if linear { 1.0 } else { 255.0 })+ .speed(if linear { 0.003 } else { 0.5 })+ .custom_parser(crate::prefs::parse_number)+ .custom_formatter(move |v, _| if linear { format!("{v:.03}") } else { format!("{v:.0}") }),+ );+ response.widget_info(|| {+ let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), *channel);+ info.label = Some(name.into());+ info+ });+ publish(&format!("color:channel:{name}"), &response);+ edited |= response.changed();});- publish(&format!("color:channel:{name}"), &response);- edited |= response.changed();- });- }- });+ }+ });+ }if edited {let [r, g, b] = channels;*rgb = if linear {@@ -195,6 +231,8 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {};hsv = crate::theme::srgb(rgb.map(|c| f32::from(c) / 255.0)).into();}+ // Only graphical edits convert HSV back to RGB. Typed byte values stay exact.+ let mut graphical_edit = false;let width = dimension(ui.available_width());let (square, response) = ui.allocate_exact_size(vec2(width, t.control_height * 7.0 + t.space_4), Sense::click_and_drag());if (response.clicked() || response.dragged())@@ -202,7 +240,7 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {{hsv.s = ((pos.x - square.left()) / square.width()).clamp(0.0, 1.0);hsv.v = (1.0 - (pos.y - square.top()) / square.height()).clamp(0.0, 1.0);- edited = true;+ graphical_edit = true;}gradient(ui, square, |x, y| Color32::from(HsvaGamma { h: hsv.h, s: x, v: 1.0 - y, a: 1.0 }));marker(ui, pos2(square.left() + hsv.s * square.width(), square.bottom() - hsv.v * square.height()), t.space_6);@@ -214,16 +252,17 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {&& let Some(pos) = response.interact_pointer_pos(){hsv.h = ((pos.x - hue.left()) / hue.width()).clamp(0.0, 1.0);- edited = true;+ graphical_edit = true;}gradient(ui, hue, |x, _| Color32::from(HsvaGamma { h: x, s: 1.0, v: 1.0, a: 1.0 }));marker(ui, pos2(hue.left() + hsv.h * hue.width(), hue.center().y), t.space_8);response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(hsv.h), i18n::tr("color.hue")));publish("color:hue", &response);response.on_hover_text(i18n::tr("color.hue"));- if edited {+ if graphical_edit {let c = Color32::from(hsv);*rgb = [c.r(), c.g(), c.b()];+ hex.set(*rgb, opacity.as_deref().copied());}let (strip, response) = ui.allocate_exact_size(vec2(width, t.form_close_size), Sense::hover());ui.painter().rect(@@ -236,9 +275,64 @@ pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool {publish("color:current", &response);response.on_hover_text(i18n::tr("color.selected"));});+ hex.sync(*rgb, opacity.as_deref().copied());ui.ctx().data_mut(|d| d.insert_temp(id, (*rgb, hsv)));+ ui.ctx().data_mut(|d| {+ d.insert_temp(hex_id, hex);+ d.insert_temp(format_id, hexadecimal);+ });scenario::publish_rect("color:popover", ui.min_rect());- hsv != before+ *rgb != before_rgb || opacity.as_deref().copied() != before_opacity || hsv != before || accepted_mixed+}++/// Text drafts are independent of model values. Copy retains the last accepted representation,+/// even while an incomplete/invalid draft is visible. Never round-trip opacity through its byte.+#[derive(Clone)]+struct HexEdit {+ draft: String,+ accepted: String,+ rgb: [u8; 3],+ opacity: Option<f64>,+ alpha: bool,+}++impl HexEdit {+ fn new(rgb: [u8; 3], opacity: Option<f64>) -> Self {+ let mut edit = Self { draft: String::new(), accepted: String::new(), rgb, opacity, alpha: opacity.is_some_and(|a| a != 1.0) };+ edit.set(rgb, opacity);+ edit+ }++ fn set(&mut self, rgb: [u8; 3], opacity: Option<f64>) {+ let [r, g, b] = rgb;+ self.accepted = format!("#{r:02x}{g:02x}{b:02x}");+ if self.alpha {+ let a = (opacity.unwrap_or(1.0).clamp(0.0, 1.0) * 255.0).round() as u8;+ self.accepted.push_str(&format!("{a:02x}"));+ }+ self.draft.clone_from(&self.accepted);+ self.rgb = rgb;+ self.opacity = opacity;+ }++ fn sync(&mut self, rgb: [u8; 3], opacity: Option<f64>) {+ if self.rgb != rgb || self.opacity != opacity {+ // An external opacity edit must be visible, including after six-digit input.+ if opacity.is_some() && self.opacity != opacity {+ self.alpha = true;+ }+ self.set(rgb, opacity);+ }+ }+}++fn parse_hex(text: &str) -> Option<([u8; 3], Option<u8>)> {+ let digits = text.strip_prefix('#')?;+ if !matches!(digits.len(), 6 | 8) || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {+ return None;+ }+ let byte = |at: usize| digits.get(at..at + 2).and_then(|value| u8::from_str_radix(value, 16).ok());+ Some(([byte(0)?, byte(2)?, byte(4)?], if digits.len() == 8 { Some(byte(6)?) } else { None }))}fn marker(ui: &Ui, at: egui::Pos2, radius: f32) {diff --git a/crates/ui-egui/src/ui_kit/color_tests.rs b/crates/ui-egui/src/ui_kit/color_tests.rsindex aee5958540..07bb7f1e2d 100644--- a/crates/ui-egui/src/ui_kit/color_tests.rs+++ b/crates/ui-egui/src/ui_kit/color_tests.rs@@ -13,6 +13,44 @@ fn click(ctx: &egui::Context, key: &str, rgb: &mut [u8; 3]) {frame(ctx, pointer(at, false), |ui| color_popover(ui, rgb));}+fn paste_hex(ctx: &egui::Context, rgb: &mut [u8; 3], text: &str) -> bool {+ click(ctx, "color:hex", rgb);+ let modifiers = egui::Modifiers { command: true, ctrl: true, ..Default::default() };+ let mut changed = false;+ frame(+ ctx,+ vec![+ egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: false, repeat: false, modifiers },+ egui::Event::Paste(text.into()),+ ],+ |ui| changed |= color_popover(ui, rgb),+ );+ changed+}++fn copy(ctx: &egui::Context, rgb: &mut [u8; 3]) -> Option<String> {+ let at = scenario::handle_at("color:copy").unwrap();+ frame(ctx, pointer(at, true), |ui| color_popover(ui, rgb));+ let output = crate::test_support::frame(+ ctx,+ egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0))),+ events: pointer(at, false),+ focused: true,+ ..Default::default()+ },+ |ui| {+ ui.set_width(280.0);+ crate::ui_kit::scope(ui, |ui| color_popover(ui, rgb));+ },+ );+ output.platform_output.commands.into_iter().find_map(|command| match command {+ egui::OutputCommand::CopyText(text) => Some(text),+ _ => None,+ })+}+#[test]fn linear_field_preserves_hdr_precision_without_edits_and_bounds_hostile_limits() {let ctx = crate::fonts::test_context();@@ -29,11 +67,97 @@ fn format_toggle_is_global_and_does_not_change_colour() {let ctx = crate::fonts::test_context();let mut rgb = [204, 208, 214];frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));+ assert_eq!(ctx.style_of(egui::Theme::Light).visuals.numeric_color_space, egui::style::NumericColorSpace::GammaByte);+ assert!(scenario::handle_at("color:channel:R").is_some());+ assert!(scenario::handle_at("color:hex").is_none());click(&ctx, "color:format:F", &mut rgb);assert_eq!(ctx.style_of(egui::Theme::Light).visuals.numeric_color_space, egui::style::NumericColorSpace::Linear);assert_eq!(rgb, [204, 208, 214]);+ click(&ctx, "color:format:Hex", &mut rgb);+ let mut other = [1, 2, 3];+ frame(&ctx, vec![], |ui| ui.push_id("another_picker", |ui| color_popover(ui, &mut other)));+ assert!(scenario::handle_at("color:hex").is_some(), "Hex selection is shared with other pickers");+ for name in ["R", "G", "B"] {+ assert!(scenario::handle_at(&format!("color:channel:{name}")).is_none());+ }+ for key in ["color:sv", "color:hue", "color:current"] {+ assert!(scenario::rect_of(key).is_some(), "Hex retains {key}");+ }+ assert_eq!(other, [1, 2, 3]);+ frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));click(&ctx, "color:format:U8", &mut rgb);assert_eq!(ctx.style_of(egui::Theme::Light).visuals.numeric_color_space, egui::style::NumericColorSpace::GammaByte);+ assert_eq!(rgb, [204, 208, 214]);+ assert!(scenario::handle_at("color:channel:R").is_some());+ assert!(scenario::handle_at("color:hex").is_none());+}++#[test]+fn hex_edits_apply_complete_byte_values_and_reject_invalid_or_nonopaque_pastes() {+ let ctx = crate::fonts::test_context();+ let mut rgb = [100, 120, 140];+ frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));+ click(&ctx, "color:format:Hex", &mut rgb);+ for (text, expected) in [+ ("#0102fe", [1, 2, 254]),+ ("#fE8001", [254, 128, 1]),+ ("#00ff01", [0, 255, 1]),+ ("#000000", [0, 0, 0]),+ ("#ffffff", [255, 255, 255]),+ ("#1b2C3DfF", [27, 44, 61]),+ ] {+ assert!(paste_hex(&ctx, &mut rgb, text), "{text} applies without Enter");+ assert_eq!(rgb, expected, "{text} retains exact bytes without a colour-space round trip");+ }+ for text in [+ "",+ "#",+ "#12345",+ "#1234567",+ "123456",+ "##123456",+ "#12345g",+ "#+102fe",+ "#0102+e",+ "#é1234",+ "#123456fff",+ "#123456 ",+ "#112233ffignored",+ "#fedcba80",+ "#fedcba00",+ ] {+ assert!(!paste_hex(&ctx, &mut rgb, text), "{text:?} is not an accepted colour edit");+ frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));+ assert_eq!(rgb, [27, 44, 61], "{text:?} must not apply even its RGB part");+ }+ assert_eq!(copy(&ctx, &mut rgb).map(|text| text.to_ascii_lowercase()), Some("#1b2c3dff".into()));++ assert!(!paste_hex(&ctx, &mut rgb, "#12"));+ frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));+ frame(&ctx, vec![egui::Event::Text("3456".into())], |ui| color_popover(ui, &mut rgb));+ assert_eq!(rgb, [18, 52, 86], "an incomplete draft survives idle frames and remains editable");+}++#[test]+fn hex_text_and_copy_follow_picker_and_external_colour_edits() {+ let ctx = crate::fonts::test_context();+ let mut rgb = [255, 0, 0];+ frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));+ click(&ctx, "color:format:Hex", &mut rgb);+ assert!(!paste_hex(&ctx, &mut rgb, "#12"));+ click(&ctx, "color:hue", &mut rgb);+ assert_ne!(rgb, [255, 0, 0]);+ let [r, g, b] = rgb;+ assert_eq!(copy(&ctx, &mut rgb).map(|text| text.to_ascii_lowercase()), Some(format!("#{r:02x}{g:02x}{b:02x}")));+ rgb = [240, 128, 17];+ frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb));+ assert_eq!(copy(&ctx, &mut rgb).map(|text| text.to_ascii_lowercase()), Some("#f08011".into()));+ assert!(!paste_hex(&ctx, &mut rgb, "#f08011ff"), "changing representation alone is not a colour edit");+ click(&ctx, "color:format:F", &mut rgb);+ click(&ctx, "color:format:U8", &mut rgb);+ click(&ctx, "color:format:Hex", &mut rgb);+ assert_eq!(copy(&ctx, &mut rgb).map(|text| text.to_ascii_lowercase()), Some("#f08011ff".into()));+ assert_eq!(rgb, [240, 128, 17], "mode switches preserve exact RGB and the active Hex representation");}#[test]@@ -111,29 +235,10 @@ fn channel_edits_use_gamma_bytes_or_linear_values_and_copy_in_the_active_format();frame(&ctx, key(egui::Key::Enter), |ui| color_popover(ui, &mut rgb));assert_eq!(rgb, if linear { [188, 20, 30] } else { [128, 20, 30] });- let copy = scenario::handle_at("color:copy").unwrap();- frame(&ctx, pointer(copy, true), |ui| color_popover(ui, &mut rgb));- let mut output = ctx.run_ui(- egui::RawInput {- screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0))),- events: pointer(copy, false),- focused: true,- ..Default::default()- },- |ui| {- ui.set_width(280.0);- crate::ui_kit::scope(ui, |ui| color_popover(ui, &mut rgb));- },- );let [r, g, b] = rgb;let [lr, lg, lb, _] = egui::Rgba::from(Color32::from_rgb(r, g, b)).to_array();let want = if linear { format!("{lr:.03}, {lg:.03}, {lb:.03}") } else { format!("{r}, {g}, {b}") };- assert!(- output.platform_output.commands.iter().any(|c| matches!(c,egui::OutputCommand::CopyText(text) if text == &want)),- "{:?}",- output.platform_output.commands- );- output.textures_delta.clear();+ assert_eq!(copy(&ctx, &mut rgb), Some(want));}}diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rsindex 5eab9dee5e..b216ddf103 100644--- a/crates/ui-egui/src/ui_kit/gallery.rs+++ b/crates/ui-egui/src/ui_kit/gallery.rs@@ -186,9 +186,6 @@ const ELEMENTS: &[Element] = &[element!("text_button", |ui, _| {text_button(ui, "Reset", true);}),- element!("color_hex_field", |ui, _| {- color_hex_field(ui, &mut [52, 92, 160], None);- }),element!("mixed_slider", |ui, _| {mixed_slider(ui, &mut 0.5, 0.0..=1.0, None);}),@@ -1095,6 +1092,12 @@ const ELEMENTS: &[Element] = &[element!("color_field", |ui, _| {color_field(ui, &mut [120, 150, 180]);}),+ element!("color_field_with_opacity", |ui, _| {+ color_field_with_opacity(ui, &mut [120, 150, 180], &mut 0.5);+ }),+ element!("mixed_color_field", |ui, _| {+ mixed_color_field(ui, &mut [120, 150, 180], Some(&mut 0.5), Some("Mixed"));+ }),element!("slider", |ui, _| {slider(ui, &mut 0.5, 0.0..=1.0, Default::default());}),diff --git a/docs/ui-kit.md b/docs/ui-kit.mdindex 23f5edcdfb..b9afecd8f5 100644--- a/docs/ui-kit.md+++ b/docs/ui-kit.md@@ -168,7 +168,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera| `length_field`, `angle_field` | Length in design units, angle in degrees | form control/font tokens || `slider` + `Slider` options | One token-painted track/thumb over native slider/value interaction; optional step, caller formatting, whole-step manipulation and hidden value editor | `control_height`, `space_24/8/4/2`, form control/font tokens || `placement_field` | Stable focus ID; drawing tool owns Enter/Tab validation and completion | `control_fill`, `font_body`, `text`, `control_height`, spacing |-| `color_field`, `color_popover` | Opaque document RGB swatch and kit popover; global U8/F segments, copy, gamma-byte or linear RGB fields, painter-drawn HSV square/hue and current strip; outside click dismisses | `control_*`, `form_*`, `border`, `on_accent`, `space_*` |+| `color_field`, `color_field_with_opacity`, `mixed_color_field`, `color_popover` | Document RGB swatch and kit popover; global U8/F/Hex segments, active-format copy, gamma-byte or linear RGB fields or one Hex editor, painter-drawn HSV square/hue and current strip; outside click dismisses. The opacity-aware field edits the caller's separate `f64` opacity, never premultiplied RGB. Six Hex digits preserve exact opacity; eight set alpha to `aa / 255`. RGB-only callers reject non-FF alpha without applying RGB. Incomplete text remains editable without changing the last valid colour. The mixed-aware wrapper adds a non-editable label and reports accepting the first colour as an edit, so the caller can set all selected targets. | `control_*`, `form_*`, `border`, `on_accent`, `space_*` || choice: `segmented`, `Segments` | Equal text choices; `states` supplies mixed selection, `enabled` keeps unsupported choices faded and inert, `disabled_reasons` also disables choices and supplies hover explanations, `compact` clips instead of falling back to a dropdown, `primary` uses accent/on-accent for the selected segment | `control_*`, `selected_bg/ink`, `font_label`, `space_4/8` || `segmented_icons`, `IconSegment` | Equal icon choices and mixed states | segment tokens, icon palette || `checkbox`, `checkbox_indeterminate`, `checkbox_row`, `checkbox_grid`, `options` | One box/tick painter for inline, mixed, full-row, grid and menu choices | `space_14/3/2`, `radius_sm`, `control_fill/border`, `form_primary/ink`, `hover`, `on_accent` |@@ -753,7 +753,9 @@ while the kit owns every dimension, colour and inset.The Appearance Inspector uses the shared `inspector_header` (selection icon/name,workspace chip, Menu and close action) and `Panel::editor_footer` (48 pt pinned-band). `color_hex_field` pairs the colour popover with a bounded hex editor;+band). `mixed_color_field` uses the one shared colour popover with a non-editable+mixed-value label, not an outer Hex editor. Non-PBR Appearance passes exact opacity;+PBR passes no opacity and remains opaque. All Hex parsing and draft state stay in the kit.`mixed_slider` pairs the standard slider with the mixed-aware scalar editor.`editor_section` uses a 24 pt heading and 6 pt field gaps.`workspace_chip`, `text_button`, `section_heading`, `pending_section`,