diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index c3e7a84296..693608574e 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -135,7 +135,7 @@ impl Session { /// Whether `name` is a built-in preset's, "Custom" (changed settings, as the panel and a traced /// object show them), or a saved preset's other than the one at `except`. - fn trace_preset_taken(&self, name: &str, except: Option) -> bool { + pub fn trace_preset_taken(&self, name: &str, except: Option) -> bool { tr::preset(name).is_some() || name.trim().eq_ignore_ascii_case("Custom") || self.trace_preset_index(name).is_some_and(|i| Some(i) != except) } diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index ad6a1e5bf3..8021f6ece5 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -11,15 +11,36 @@ use std::sync::Arc; +// PLAN: assumed import paths of the framework items below: `craft_ui::primitives::IconId`, +// `craft_ui::runtime::commands::{CommandState, CommandStates}`, `craft_ui::menu::PanelRow`, +// `craft_ui::patterns::presets::*`, `crate::widgets::edits` (widgets-w13) and `crate::chrome::rank` (chrome-w16). +use craft_keymap::CommandRef; +use craft_ui::buttons::{Button, IconButton, SplitButton, ToggleButton}; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::{Divider, Shade, Text}; +use craft_ui::form::{Field, SliderField, SliderFieldLayout}; +use craft_ui::layout_components::Row; +use craft_ui::menu::PanelRow; +use craft_ui::patterns::presets::{ + NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PickerField, PresetError, PresetPicker, PresetRow, PresetState, +}; +use craft_ui::pickers::Select; +use craft_ui::primitives::IconId; +use craft_ui::runtime::commands::{CommandState, CommandStates}; +use craft_ui::sections::Section; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; use vectorcraft_engine::cmd::TracePresetChange; -use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; -use super::{first_node, pstate, set_pstate, swatches}; +use super::first_node; use crate::VectorcraftApp; -use crate::widgets::{self, menu_item}; +use crate::chrome::rank; +use crate::widgets::edits::{self, EditPath}; + +pub(crate) mod rows; +use rows::{RowsData, RowsHost, RowsOutput, Sampler}; pub(crate) const MODES: [(&str, &str); 4] = [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; @@ -47,34 +68,16 @@ pub(crate) fn palette_label(id: &str) -> &'static str { } } -/// Document Library's Colors choices with the document's swatches: All, then the document's color -/// groups (`current` checked; `None` is All) → the choice, `Some(None)` for All. -pub(crate) fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { - let mut chosen = menu_item(ui, "All", true, current.is_none()).then_some(None); - let groups: Vec = app.session.active().map(|d| d.doc.swatch_groups.iter().map(|g| g.name.clone()).collect()).unwrap_or_default(); - if !groups.is_empty() { - ui.separator(); - } - for g in groups { - if widgets::menu_item_name(ui, &g, true, current == Some(g.as_str())) { - chosen = Some(Some(g)); - } - } - chosen -} - /// `params`' color group when the active document has it, found as `imageTrace.make` finds it (so /// named exactly, else ignoring case); `None` is All. A group of another document, or a deleted /// one, is All. fn color_group<'a>(app: &VectorcraftApp, params: &'a Value) -> Option<&'a str> { - let name = params["colorGroup"].as_str().filter(|g| !g.is_empty())?; - let lower = name.to_lowercase(); - app.session.active()?.doc.swatch_groups.iter().any(|g| g.name.to_lowercase() == lower).then_some(name) + rows::known_group(&rows::swatch_groups(app), params) } /// Panel state: the preset name, the current parameters, the view and the last result's counts. -#[derive(Clone, Default)] -struct TraceUi { +#[derive(Clone, Debug, Default)] +pub(crate) struct TraceUi { preset: String, params: Value, view: TraceView, @@ -94,34 +97,55 @@ struct TraceUi { drafts: std::collections::HashMap<(u64, NodeId), (String, Value, Value)>, } +/// The Image Trace panel's run-only state: what it shows, and the view settings of its preset picker. +#[derive(Clone, Debug, Default)] +pub(crate) struct ImageTraceUi { + pub(crate) shown: TraceUi, + pub(crate) picker: PresetState, +} + +impl ImageTraceUi { + /// Reset to Default: the settings go back to the Default preset's. Preview and Advanced are the + /// user's preferences and stay. + pub(crate) fn reset(&mut self) { + self.shown = TraceUi::default(); + } +} + /// A preset: its name, its parameters, those of its enhanced version (null if it has none), and /// whether it is built in (else the user saved it). pub(crate) type Preset = (String, Value, Value, bool); -/// The presets as `imageTrace.presets` listed them at a revision of the saved presets. -#[derive(Clone)] -struct PresetList { - revision: u64, - presets: Arc>, +/// The presets as `imageTrace.presets` listed them at a revision of the saved presets, and the rows +/// and select entries made from them. +// PLAN: the contract's `revision` field is the key of the memo `app.canvas.trace_presets`; it is not kept twice. +#[derive(Debug)] +pub(crate) struct PresetList { + pub(crate) presets: Vec, + pub(crate) rows: Vec>, + pub(crate) entries: Vec>, } -#[cfg(test)] -thread_local! { - /// How many times [`presets`] ran `imageTrace.presets` on this thread. - static PRESET_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +impl PresetList { + fn new(presets: Vec) -> Self { + // A saved preset's name is the user's, shown as it is. + let label = |p: &Preset| if p.3 { preset_label(&p.0).to_string() } else { p.0.clone() }; + let rows = presets.iter().map(|p| PresetRow::item(p.0.clone(), label(p), 0)).collect(); + let entries = presets.iter().map(|p| Entry::new(p.0.clone(), label(p))).collect(); + PresetList { presets, rows, entries } + } } /// Every preset, built-in then saved. `imageTrace.presets` runs once for each revision of the saved -/// presets ([`vectorcraft_engine::Session::trace_presets_revision`]); the list is kept in `ctx`'s -/// memory, which the panel, the Control bar, Properties and Edit → Tracing Presets share. -pub(crate) fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { - let id = egui::Id::unique("trace-presets"); +/// presets ([`vectorcraft_engine::Session::trace_presets_revision`]); the list is kept in +/// `app.canvas`, which the panel, the Control bar, Properties and Edit → Tracing Presets share. +pub(crate) fn presets(app: &mut VectorcraftApp) -> Arc { let revision = app.session.trace_presets_revision(); - if let Some(list) = ctx.data(|d| d.get_temp::(id)).filter(|l| l.revision == revision) { - return list.presets; + if let Some((key, list)) = &app.canvas.trace_presets + && *key == revision + { + return list.clone(); } - #[cfg(test)] - PRESET_READS.with(|n| n.set(n.get() + 1)); let v = app.session.execute("imageTrace.presets", &json!({})).unwrap_or_default(); let presets: Vec = v["presets"] .as_array() @@ -131,9 +155,9 @@ pub(crate) fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc bool { /// What Trace acts on in the active document, and whether any selected object is an Image Trace /// object (wherever it is in the selection). #[derive(Clone, Debug, Default, PartialEq)] -struct Target { +pub(crate) struct Target { /// The active document's uid and the object Trace acts on. object: Option<(u64, NodeId)>, /// The object is an Image Trace object. @@ -166,19 +190,16 @@ struct Target { any_trace: bool, } -#[cfg(test)] -thread_local! { - /// How many times [`find_target`] looked the target up in an active document on this thread. - static TARGET_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +/// Whether any selected object is an Image Trace object. +fn any_trace_selected(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace))) } /// The image or Image Trace object `imageTrace.make` takes from the selected roots, else the /// first selected non-traceable object's metadata. Release and Expand keep their own selection scope. fn find_target(app: &VectorcraftApp) -> Target { let Some(st) = app.session.active() else { return Target::default() }; - #[cfg(test)] - TARGET_LOOKUPS.with(|n| n.set(n.get() + 1)); - let any_trace = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace)); + let any_trace = any_trace_selected(app); let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null) .ok() .and_then(|id| st.doc.node(id)) @@ -195,17 +216,17 @@ fn find_target(app: &VectorcraftApp) -> Target { /// [`find_target`], looked up once for each document and revision of it: the panel reads it on /// every frame. -fn target(app: &VectorcraftApp, ctx: &egui::Context) -> Target { - let Some(st) = app.session.active() else { return Target::default() }; +pub(crate) fn target(app: &mut VectorcraftApp) -> Arc { + let Some(st) = app.session.active() else { return Arc::default() }; let key = (st.uid, st.revision); - match pstate::>(ctx, "image-trace-target") { - Some((k, t)) if k == key => t, - _ => { - let t = find_target(app); - set_pstate(ctx, "image-trace-target", Some((key, t.clone()))); - t - } + if let Some((k, t)) = &app.canvas.trace_target + && *k == key + { + return t.clone(); } + let t = Arc::new(find_target(app)); + app.canvas.trace_target = Some((key, t.clone())); + t } /// The one selected Image Trace object's preset ("Custom" once its settings were changed) and view. @@ -247,40 +268,30 @@ fn selected_split(app: &VectorcraftApp) -> Option { /// arrow keys move it a percent at a time. Nothing without such an object. pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(split) = selected_split(app) else { return }; - ui.horizontal(|ui| { - let label = widgets::dim_label(ui, tl!("Divider")); - // The canvas sets the divider to a ten-thousandth: a hundredth of a percent. - let mut pct = (split * 10_000.0).round() / 100.0; - // Clamping only edits keeps a divider between whole percents (a canvas drag, an agent's - // value) as it is while the panel shows: clamping always rounds it to the step each frame - // and reports a change. - let slider = egui::Slider::new(&mut pct, 0.0..=100.0).suffix("%").step_by(1.0).clamping(egui::SliderClamping::Edits); - let r = widgets::slider(ui, slider).labelled_by(label.id); - r.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), pct, tl!("Divider"))); - if cfg!(test) { - ui.ctx().data_mut(|d| { - d.insert_temp(egui::Id::unique("trace-split-slider-id"), r.id); - d.insert_temp(egui::Id::unique("trace-split-slider-rect"), r.rect); - }); - } - let phase = if r.dragged() && !r.drag_stopped() { - widgets::Live::Dragging - } else if r.drag_stopped() || r.changed() { - widgets::Live::Released - } else { - widgets::Live::Idle - }; - if phase != widgets::Live::Idle { - let split = (pct / 100.0).clamp(0.0, 1.0); - crate::panels::live_run(app, "Image Trace View", "imageTrace.setView", json!({ "view": TraceView::Split.id(), "split": split }), phase); - } + // The canvas sets the divider to a ten-thousandth: a hundredth of a percent. + let pct = (split * 10_000.0).round() / 100.0; + let edit = Field::new(tl!("Divider")) + .show(ui, |ui, _| { + SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0).layout(SliderFieldLayout::Inline).step(1.0).unit("%").show(ui).edit + }) + .inner; + let Some(edit) = edit else { return }; + // Only an edit runs the command, so a divider between whole percents (a canvas drag, an agent's + // value) stays exact while the panel shows it. + edits::apply_edits(app, &edit, EditPath::Preview, |app, pct, phase| { + let split = (pct / 100.0).clamp(0.0, 1.0); + crate::panels::live_run(app, "Image Trace View", "imageTrace.setView", json!({ "view": TraceView::Split.id(), "split": split }), phase); }); } -/// The View dropdown showing `current` → the view chosen. -fn view_dropdown(ui: &mut Ui, current: TraceView, width: f32) -> Option { - let labels = TraceView::ALL.map(view_label); - widgets::dropdown_names(ui, "trace-view", view_label(current), &labels, width).and_then(|i| TraceView::ALL.get(i).copied()) +/// The View select showing `current` → the view the user picked this pass. +fn view_pick(ui: &mut Ui, current: TraceView) -> Option { + let entries: Vec> = TraceView::ALL.iter().map(|v| Entry::new(v.id().to_string(), view_label(*v))).collect(); + let picked = Field::new(tl!("View:")) + .show(ui, |ui, _| Select::new(tl!("View"), Bind::given(current.id().to_string()), &entries).show(ui).events.committed().cloned()) + .inner + .flatten()?; + TraceView::ALL.iter().copied().find(|v| v.id() == picked) } /// Show the selected Image Trace objects with `view` (no new trace). @@ -290,12 +301,19 @@ fn set_view(app: &mut VectorcraftApp, view: TraceView) { } } +/// Run `id` with `params`; a failure goes to the status line. +fn run_reporting(app: &mut VectorcraftApp, id: &str, params: Value) { + if let Err(e) = app.run(id, params) { + app.status(e); + } +} + /// While `down`, the selected Image Trace objects show their source image on the canvas, whatever /// their View. The document and the undo history stay as they are. The panel's eye button next to /// View calls it; per the public documentation of the panel, that control is pressed and held to /// view the source image /// (). -fn hold_source(app: &mut VectorcraftApp, ctx: &egui::Context, down: bool) { +fn hold_source(app: &mut VectorcraftApp, down: bool) { let ids = app .session .active() @@ -305,7 +323,9 @@ fn hold_source(app: &mut VectorcraftApp, ctx: &egui::Context, down: bool) { .map(std::sync::Arc::new); if ids != app.ui.trace_hold_source { app.ui.trace_hold_source = ids; - ctx.request_repaint(); + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } } } @@ -357,16 +377,13 @@ fn cancel_disabled_ignore_sampler(app: &mut VectorcraftApp, params: &Value) { } /// Also runs when the panel is closed: document changes and tool changes end the pick. -pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool { - let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; +pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return }; if !sampler_valid(app, s) { cancel_ignore_sampler(app, true); } else if !sampler_tool_active(app, s) { cancel_ignore_sampler(app, false); - } else { - return false; } - true } /// A stale sampler's click must not become a paint/selection click in the restored tool. @@ -380,12 +397,12 @@ pub(crate) fn discard_stale_ignore_click(app: &mut VectorcraftApp) -> bool { true } -fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) { +fn start_ignore_sampler(app: &mut VectorcraftApp) { if app.ui.trace_ignore_sampler.is_some() { cancel_ignore_sampler(app, true); return; } - let Some((doc, target)) = target(app, ctx).object else { return }; + let Some((doc, target)) = target(app).object else { return }; let Some(revision) = app.session.active().map(|d| d.revision) else { return }; let s = crate::state::TraceIgnoreSampler { doc, target, revision, back: app.session.tool_id().to_string() }; if !sampler_valid(app, &s) { @@ -401,8 +418,6 @@ fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) { } app.session.set_tool_option("imageTraceIgnoreColor", &sampler_binding(&s)); app.session.set_tool_option("stop", &json!(s.back.as_str())); - // Bind the reply to this panel's state, also when it is drawn without the full app frame. - app.ui_ctx = Some(ctx.clone()); app.ui.trace_ignore_sampler = Some(s); if let Some(ctx) = &app.ui_ctx { ctx.request_repaint(); @@ -453,36 +468,34 @@ pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { // binding and previous tool so the next canvas click can still complete this pick. let Some(color) = sampled_ignore_color(app, s, p) else { return }; let s = s.clone(); - // The canvas UI establishes this context before a real panel click can arm the sampler. - let Some(ctx) = app.ui_ctx.clone() else { return }; cancel_ignore_sampler(app, false); - let all = presets(app, &ctx); - let mut st: TraceUi = pstate(&ctx, "image-trace"); - let Target { is_trace, stored, .. } = target(app, &ctx); - follow_preset_changes(app, &mut st, &all); + let list = presets(app); + let t = target(app); + let mut st = std::mem::take(&mut app.ui.image_trace_panel.shown); + follow_preset_changes(app, &mut st, &list.presets); let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); - sync_with_object(&mut st, stored, Some((s.doc, s.target)), &all, &changes); + sync_with_object(&mut st, t.stored.clone(), Some((s.doc, s.target)), &list.presets, &changes); st.params["ignoreColor"] = json!(color); st.preset = "Custom".into(); let preview = app.ui.image_trace_preview; - if is_trace || !preview { + if t.is_trace || !preview { st.preview_off = !preview; } - if is_trace && preview { - trace(app, &ctx, &mut st); + if t.is_trace && preview { + trace(app, &mut st); + } + app.ui.image_trace_panel.shown = st; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); } - set_pstate(&ctx, "image-trace", st); - ctx.request_repaint(); // Complete the temporary tool without treating its return as a fresh explicit tool choice. // A miss above has no switch request and remains armed. app.return_to_tool(&s.back); } /// The selected Image Trace object's View row (Control bar, Properties). -pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, current: TraceView, width: f32) { - widgets::dim_label(ui, tl!("View:")); - // No wider than what the label leaves of the row (#1358). - if let Some(v) = view_dropdown(ui, current, width.min(ui.available_width())) { +pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, view: TraceView) { + if let Some(v) = view_pick(ui, view) { set_view(app, v); } } @@ -508,8 +521,6 @@ pub(crate) fn open_settings(app: &mut VectorcraftApp) { app.ui.image_trace_advanced = true; } -/// The presets to choose from, built-in then saved (`current` highlighted) → the one chosen. Listed only -/// while the menu is open. /// A preset's name as shown: translated as a preset's name where the catalog has it so (the /// Outline preset is not the Outline view), as any other string else. pub(crate) fn preset_label(name: &str) -> &str { @@ -531,146 +542,90 @@ fn preset_buttons() -> [(&'static str, &'static str); 6] { ] } -fn preset_list(app: &mut VectorcraftApp, ui: &mut Ui, current: &str) -> Option { - let mut chosen = None; - let list = presets(app, ui.ctx()); - for (name, _, _, built_in) in list.iter() { - // A saved preset's name is the user's, shown as it is. - let label = if *built_in { preset_label(name) } else { name.as_str() }; - if ui.add(egui::Button::selectable(name == current, label)).clicked() { - chosen = Some(name.clone()); - } - } - chosen -} - -/// Manage Presets, next to the Image Trace panel's Preset dropdown: Save as New Preset… names the -/// panel's settings; Rename… and Delete act on the saved preset the dropdown shows (`saved`). -/// Built-in presets don't change. From the public documentation of saving tracing presets -/// (). -fn manage_presets(app: &mut VectorcraftApp, ui: &mut Ui, st: &TraceUi, saved: bool) { - let run = if menu_item(ui, tl!("Save as New Preset…"), true, false) { - Some(("ui.imageTracePresetDialog", json!({ "params": st.params }))) - } else if menu_item(ui, tl!("Rename…"), saved, false) { - Some(("ui.imageTracePresetDialog", json!({ "rename": st.preset }))) - } else if menu_item(ui, tl!("Delete"), saved, false) { - Some(("imageTrace.presets.delete", json!({ "name": st.preset }))) - } else { - None - }; - if let Some((id, p)) = run - && let Err(e) = app.run(id, p) - { - app.ui.status = e; - } -} - -/// Width of the Control bar's Image Trace button. -pub(crate) const TRACE_BUTTON_W: f32 = 104.0; - /// The Image Trace button for a selected image (Control bar, Properties): a click traces it with /// the Default preset, its arrow lists the presets to trace it with. -pub(crate) fn trace_button(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { - let (main, arrow) = widgets::split_button_named(ui, tl!("Image Trace"), tl!("Tracing Presets"), width); - if main.on_hover_text(tl!("Trace the image with the Default preset")).clicked() { +pub(crate) fn trace_button(app: &mut VectorcraftApp, ui: &mut Ui) { + let list = presets(app); + let out = SplitButton::new(tl!("Image Trace"), &list.entries) + .arrow_label(tl!("Tracing Presets")) + .tooltip(tl!("Trace the image with the Default preset")) + .show(ui); + if let Some(name) = out.chosen { + trace_with(app, &name); + } else if craft_ui::contract::clicked(&out.response) { trace_with(app, "Default"); } - if let Some(p) = egui::Popup::menu(&arrow).show(|ui| widgets::menu_scroll(ui, |ui| preset_list(app, ui, ""))).and_then(|r| r.inner) { - trace_with(app, &p); - } } /// The selected Image Trace object's preset (Control bar, Properties), traced with the preset /// `traced_with`, shown as the panel shows it: choosing another traces it again with that preset. -pub(crate) fn preset_dropdown(app: &mut VectorcraftApp, ui: &mut Ui, traced_with: &str, width: f32) { - let all = presets(app, ui.ctx()); +pub(crate) fn preset_dropdown(app: &mut VectorcraftApp, ui: &mut Ui, traced_with: &str) { + let list = presets(app); let params = selected_trace_params(app); let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); - let current = listed_preset(traced_with, ¶ms, &all, &changes); - // A saved preset's name is the user's, shown as it is. - let shown = if app.session.trace_preset(¤t).is_some() { current.as_str() } else { tl!(current.as_str()) }; - if let Some(p) = widgets::combo(ui, "trace-preset", shown, width, |ui| preset_list(app, ui, ¤t)) { - trace_with(app, &p); + let current = listed_preset(traced_with, ¶ms, &list.presets, &changes); + let picked = Select::new(tl!("Preset"), Bind::given(current), &list.entries).placeholder(tl!("Custom")).show(ui).events.committed().cloned(); + if let Some(name) = picked { + trace_with(app, &name); } } /// The Control bar for one selected Image Trace object: its preset, view, the Image Trace panel -/// and Expand. Whether it is one. Each label with its menu, and each button, shows only while the row -/// has room for it and `reserve` after it, and the controls after one left out are left out too. -pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) -> bool { +/// and Expand, each a group that leaves the bar whole when it is short of room → whether it is one. +pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let Some((preset, view)) = selected_trace(app) else { return false }; - let mut fit = crate::chrome::Fit::new(reserve); - if fit.room(ui, &[widgets::dim_label_width(ui, tl!("Preset:")), 150.0]) { - widgets::dim_label(ui, tl!("Preset:")); - preset_dropdown(app, ui, &preset, 150.0); - } - if fit.room(ui, &[widgets::dim_label_width(ui, tl!("View:")), 190.0]) { - view_row(app, ui, view, 190.0); - } - if fit.room(ui, &[24.0]) && widgets::icon_button(ui, "image", tl!("Image Trace"), false, 24.0).clicked() { - open_settings(app); - } - if fit.room(ui, &[widgets::flat_button_fit_width(ui, tl!("Expand"), 64.0)]) && widgets::flat_button_fit(ui, tl!("Expand"), 64.0).clicked() { - app.run("imageTrace.expand", json!({})).ok(); - } - fit.separator(ui); + Divider::vertical().show(ui); + Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| { + Field::new(tl!("Preset:")).show(ui, |ui, _| preset_dropdown(app, ui, &preset)); + }); + Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| view_row(app, ui, view)); + Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| { + if IconButton::new(IconId::new("image")).label(tl!("Image Trace")).tooltip(tl!("Image Trace")).show(ui).clicked() { + open_settings(app); + } + }); + Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| { + if Button::new(tl!("Expand")).show(ui).clicked() { + run_reporting(app, "imageTrace.expand", json!({})); + } + }); true } -fn trace(app: &mut VectorcraftApp, ctx: &egui::Context, st: &mut TraceUi) { +fn trace(app: &mut VectorcraftApp, st: &mut TraceUi) { // A group the active document does not have traces with All, as the panel shows. if color_group(app, &st.params).is_none() && !st.params["colorGroup"].is_null() { st.params["colorGroup"] = Value::Null; } // The settings are complete, so with a preset that no longer exists (a deleted saved one) they // are traced over Default, and the object shows Custom. - let all = presets(app, ctx); - let known = find_preset(&all, &st.preset).map(|p| p.0.as_str()); + let list = presets(app); + let known = find_preset(&list.presets, &st.preset).map(|p| p.0.as_str()); let preset = known.filter(|_| st.preset != "Custom").unwrap_or("Default"); let p = json!({ "preset": preset, "params": st.params, "view": st.view.id() }); match crate::trace_runs::start(app, "imageTrace.make", p, true) { // Traced off the UI thread: the result comes to [`traced`]. Ok(r) if r["background"] == true => {} - Ok(r) => adopt(app, ctx, st, &r), + Ok(r) => adopt(st, &target(app), &r), Err(e) => app.ui.status = e, } } -/// The panel takes trace `r`'s counts and the traced object's stored settings at once: Undo before +/// The panel takes trace `r`'s counts and the traced object's stored settings `target` at once: Undo before /// the next panel frame must still be recognized as a change, even when it returns to the previous /// settings. -fn adopt(app: &VectorcraftApp, ctx: &egui::Context, st: &mut TraceUi, r: &Value) { +fn adopt(st: &mut TraceUi, target: &Target, r: &Value) { st.info = Some((r["paths"].as_u64().unwrap_or(0), r["anchors"].as_u64().unwrap_or(0), r["colors"].as_u64().unwrap_or(0))); - let target = target(app, ctx); - if let Some(stored) = target.stored { - st.synced = stored; + if let Some(stored) = &target.stored { + st.synced = stored.clone(); st.object = target.object; } } /// A trace the panel started off the UI thread was applied with result `r` ([`crate::trace_runs`]). -pub(crate) fn traced(app: &VectorcraftApp, r: &Value) { - let Some(ctx) = app.ui_ctx.clone() else { return }; - let mut st: TraceUi = pstate(&ctx, "image-trace"); - adopt(app, &ctx, &mut st, r); - set_pstate(&ctx, "image-trace", st); -} - -pub(crate) fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { - let mut out = (false, false); - ui.horizontal(|ui| { - ui.add_sized([74.0, 22.0], egui::Label::new(egui::RichText::new(tl!(label)).size(12.0))); - // The theme's widget fill matches the panel, which would hide the rail. - let t = crate::theme::Tokens::get(ui.ctx()); - ui.visuals_mut().widgets.inactive.bg_fill = t.input_border; - ui.visuals_mut().selection.bg_fill = t.accent; - let r = ui.add(egui::Slider::new(v, range).suffix(suffix).integer().trailing_fill(true)); - if cfg!(test) { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(("trace-slider", label)), r.rect)); - } - out = (r.changed(), r.drag_stopped() || (r.changed() && !r.dragged())); - }); - out +pub(crate) fn traced(app: &mut VectorcraftApp, r: &Value) { + let t = target(app); + adopt(&mut app.ui.image_trace_panel.shown, &t, r); } /// The preset `name` an object was traced with, or, when no preset in `all` has that name, the name that the saved @@ -810,307 +765,152 @@ fn follow_preset(preset: &mut String, params: &Value, changes: &[&TracePresetCha } } +/// Make `name` the panel's preset with its settings → whether the list has it. +fn choose_preset(st: &mut TraceUi, all: &[Preset], name: &str) -> bool { + let Some(p) = all.iter().find(|p| p.0 == name) else { return false }; + st.preset = name.to_string(); + st.params = p.1.clone(); + true +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - let all = presets(app, ui.ctx()); - let mut st: TraceUi = pstate(ui.ctx(), "image-trace"); + let list = presets(app); + let t = target(app); + // The panel's state is taken out while the frame runs, so the rows borrow it apart from `app`. + let mut st = std::mem::take(&mut app.ui.image_trace_panel.shown); if st.params.is_null() { st.preset = "Default".into(); - st.params = all.first().map(|p| p.1.clone()).unwrap_or_default(); + st.params = list.presets.first().map(|p| p.1.clone()).unwrap_or_default(); } - let Target { object, is_trace, is_image, stored, any_trace } = target(app, ui.ctx()); + let (is_trace, is_image, any_trace) = (t.is_trace, t.is_image, t.any_trace); // The saved preset changes since the last frame apply to the panel's settings before the selected object's // settings, which `sync_with_object` resolves against every change, are adopted. - follow_preset_changes(app, &mut st, &all); - let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); - let restored = sync_with_object(&mut st, stored, object, &all, &changes); + follow_preset_changes(app, &mut st, &list.presets); + let restored = { + let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); + sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes) + }; let mut retrace = false; - // A preset button chooses its preset as the Preset dropdown does; the button of the panel's - // preset shows as selected. - ui.horizontal_wrapped(|ui| { + // A preset button chooses its preset as the Preset row does; the button of the panel's + // preset shows as on. + Row::new().wrap(true).show(ui, |ui, _| { for (label, name) in preset_buttons() { - let selected = st.preset == name; - if cfg!(test) { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(("trace-preset-button", name)), selected)); - } - if ui.add(egui::Button::selectable(selected, label)).on_hover_text(preset_label(name)).clicked() - && let Some(p) = all.iter().find(|p| p.0 == name) - { - st.preset = name.to_string(); - st.params = p.1.clone(); - retrace = true; + let was = st.preset == name; + let mut on = was; + ToggleButton::new(label, Bind::bound(&mut on)).tooltip(preset_label(name)).show(ui); + if on && !was { + retrace |= choose_preset(&mut st, &list.presets, name); } } }); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Preset:")); - let manage = 24.0; - let width = (ui.available_width() - manage - ui.spacing().item_spacing.x).min(170.0); - let is_saved = all.iter().any(|p| !p.3 && p.0 == st.preset); - let shown = if is_saved { st.preset.as_str() } else { preset_label(&st.preset) }; - let current = st.preset.clone(); - if let Some(name) = widgets::combo(ui, "it-preset", shown, width, |ui| preset_list(app, ui, ¤t)) - && let Some(p) = all.iter().find(|p| p.0 == name) - { - st.preset = name; - st.params = p.1.clone(); - retrace = true; + let mut value = list.presets.iter().any(|p| p.0 == st.preset).then(|| st.preset.clone()); + let session = &app.session; + let preset_row = NamedPresetRow::new( + tl!("Preset:"), + PresetPicker::new(tl!("Preset"), Bind::bound(&mut value), &list.rows, Bind::bound(&mut app.ui.image_trace_panel.picker)) + .field(PickerField::Name), + ) + .style(NamedPresetStyle::Menu) + .built_in(|name: &String| list.presets.iter().any(|p| p.3 && p.0 == *name)) + .check_name(|name: &str| session.trace_preset_taken(name, None).then_some(PresetError::NameTaken)) + .suggest_name(session.new_trace_preset_name()) + .show(ui); + for event in preset_row.events { + match event { + NamedPresetEvent::Apply(name) => retrace |= choose_preset(&mut st, &list.presets, &name), + NamedPresetEvent::Create { name, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": name, "params": st.params })), + NamedPresetEvent::Rename { key, text, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": key, "newName": text })), + NamedPresetEvent::Delete(name) => run_reporting(app, "imageTrace.presets.delete", json!({ "name": name })), + _ => {} } - let r = widgets::icon_button(ui, "ellipsis", tl!("Manage Presets"), false, manage); - if cfg!(test) { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("trace-manage-presets"), r.rect)); - } - egui::Popup::menu(&r).show(|ui| manage_presets(app, ui, &st, is_saved)); - }); + } // The preset's enhanced version (with Shapes and Auto Grouping) or its legacy one. - if let Some((_, legacy, better, _)) = all.iter().find(|p| p.0 == st.preset && !p.2.is_null()) { + if let Some((_, legacy, better, _)) = list.presets.iter().find(|p| p.0 == st.preset && !p.2.is_null()) { let on = *better == st.params; - if widgets::check(ui, tl!("Enhanced"), on, true) { + let mut value = on; + Checkbox::new(Bind::bound(&mut value)).label(tl!("Enhanced")).show(ui); + if value != on { st.params = if on { legacy.clone() } else { better.clone() }; retrace = true; } } - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("View:")); - let eye = 24.0; - if let Some(v) = view_dropdown(ui, st.view, (ui.available_width() - eye - ui.spacing().item_spacing.x).min(170.0)) { - st.view = v; - if any_trace { - set_view(app, v); - } - } - let held = app.ui.trace_hold_source.is_some(); - let r = widgets::icon_button_enabled(ui, "eye", tl!("Press and hold to view the source image"), held, any_trace, eye); - if cfg!(test) { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("trace-hold-source"), r.rect)); - } - hold_source(app, ui.ctx(), any_trace && r.is_pointer_button_down_on()); + let (mut picked, mut held) = (None, false); + Row::new().show(ui, |ui, _| { + picked = view_pick(ui, st.view); + let tip = tl!("Press and hold to view the source image"); + held = IconButton::new(IconId::new("eye")) + .label(tip) + .tooltip(tip) + .selected(app.ui.trace_hold_source.is_some()) + .enabled(any_trace) + .show(ui) + .held; }); + if let Some(v) = picked { + st.view = v; + if any_trace { + set_view(app, v); + } + } + hold_source(app, any_trace && held); split_row(app, ui); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Mode:")); - let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); - let label = MODES.iter().find(|m| m.0 == mode).map_or("Black and White", |m| m.1); - let labels: Vec<&str> = MODES.iter().map(|m| m.1).collect(); - if let Some(i) = widgets::dropdown(ui, "it-mode", label, &labels, 170.0) { - // Only Color mode uses a color group. - if MODES[i].0 != "color" { - st.params["colorGroup"] = Value::Null; - } - st.params["mode"] = json!(MODES[i].0); - st.preset = "Custom".into(); - retrace = true; - } - }); - let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); - let palette = st.params["palette"].as_str().unwrap_or("limited").to_string(); - if mode == "color" { - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Palette:")); - let labels = PALETTES.map(palette_label); - if let Some(p) = widgets::dropdown_names(ui, "it-palette", palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i)) { - // Every other palette refuses a color group. - if *p != "documentLibrary" { - st.params["colorGroup"] = Value::Null; - } - st.params["palette"] = json!(p); - st.preset = "Custom".into(); - retrace = true; - } - }); - if palette == "documentLibrary" { - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Library:")); - let key = st.params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string(); - if let Some(k) = - widgets::combo(ui, "it-library", &swatches::library_label(app, &key), 170.0, |ui| swatches::library_list(app, ui, &key)) - { - if k != DOCUMENT_SWATCHES { - st.params["colorGroup"] = Value::Null; - } - st.params["library"] = json!(k); - st.preset = "Custom".into(); - retrace = true; - } - }); - // The document's swatches: every one, or one color group's. - if st.params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES) == DOCUMENT_SWATCHES { - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Colors:")); - let group = color_group(app, &st.params).map(str::to_string); - let label = group.clone().unwrap_or_else(|| tl!("All").to_string()); - if let Some(g) = widgets::combo(ui, "it-color-group", &label, 170.0, |ui| color_group_list(app, ui, group.as_deref())) { - st.params["colorGroup"] = json!(g); - st.preset = "Custom".into(); - retrace = true; - } - }); - } - } - } - // Full Tone and Automatic: how many colours (Less … More); else a count or the threshold. - let (key, label, range, suffix) = match mode.as_str() { - "blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""), - "grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""), - // Flat Logo finds a handful of flat colours: more than ten is almost always noise. - "logo" => ("colors", tl!("Colors"), 2.0..=10.0, ""), - _ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"), - _ => ("colors", tl!("Colors"), 2.0..=256.0, ""), - }; - let mut v = st.params[key].as_f64().unwrap_or(0.0); - let (changed, release) = slider(ui, label, &mut v, range, suffix); - if changed { - st.params[key] = if key == "colorDetail" { json!(v.round()) } else { json!(v.round() as u64) }; - } - // Keep the preset's Enhanced row (and widget identities) until the drag finishes. - // Switching to Custom mid-drag removes that row and loses the slider's release event. - if release { - st.preset = "Custom".into(); - } - retrace |= release; - ui.add_space(4.0); - let open = app.ui.image_trace_advanced; - if widgets::section_toggle(ui, tl!("Advanced"), open) { - app.ui.image_trace_advanced = !open; + let data = RowsData::of(app); + let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); + let sampler = Sampler { enabled: is_trace || is_image, armed: app.ui.trace_ignore_sampler.is_some() }; + let advanced = Section::new(tl!("Advanced")) + .open(Bind::bound(&mut app.ui.image_trace_advanced)) + .show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler))) + .inner + .unwrap_or_default(); + // A setting is settled when its pick, check or drag ends. Switching to Custom while a slider + // still drags would remove the preset's Enhanced row from under it. + for RowsOutput { committed, .. } in [main, advanced] { + if committed { + st.preset = "Custom".into(); + retrace = true; + } } - if open { - for (key, label, range, suffix) in - [("paths", tl!("Paths"), 0.0..=100.0, "%"), ("corners", tl!("Corners"), 0.0..=100.0, "%"), ("noise", tl!("Noise"), 1.0..=100.0, " px")] - { - let mut v = st.params[key].as_f64().unwrap_or(0.0); - let (changed, release) = slider(ui, label, &mut v, range, suffix); - if changed { - st.params[key] = if key == "noise" { json!(v.round() as u64) } else { json!(v.round()) }; - } - if release { - st.preset = "Custom".into(); - } - retrace |= release; - } - // Flat Logo always paints biggest shapes first with a hair of overlap, so there is no choice. - if st.params["mode"] != "logo" { - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Method:")); - for (m, l) in [("abutting", tl!("Abutting")), ("overlapping", tl!("Overlapping"))] { - if ui.selectable_label(st.params["method"] == m, l).clicked() && st.params["method"] != m { - st.params["method"] = json!(m); - st.preset = "Custom".into(); - retrace = true; - } - } - }); - // Create: Fills and/or Strokes (one of them stays on), and the widest line stroked. - let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills"); - let strokes = create(&st.params, "strokes"); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Create:")); - for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] { - let on = create(&st.params, key); - if widgets::check(ui, label, on, !on || create(&st.params, other)) { - st.params[key] = json!(!on); - st.preset = "Custom".into(); - retrace = true; - } - } - }); - let mut v = st.params["strokeWidth"].as_f64().unwrap_or(10.0); - let (changed, release) = ui.add_enabled_ui(strokes, |ui| slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner; - if changed { - st.params["strokeWidth"] = json!(v.round()); - } - if release { - st.preset = "Custom".into(); - } - retrace |= release; - } - let snap = st.params["snapCurvesToLines"].as_bool().unwrap_or(false); - if widgets::check(ui, tl!("Snap Curves To Lines"), snap, true) { - st.params["snapCurvesToLines"] = json!(!snap); - st.preset = "Custom".into(); - retrace = true; - } - let shapes = st.params["shapes"].as_bool().unwrap_or(false); - if widgets::check(ui, tl!("Shapes"), shapes, true) { - st.params["shapes"] = json!(!shapes); - st.preset = "Custom".into(); - retrace = true; - } - let grouping = st.params["autoGrouping"].as_bool().unwrap_or(false); - if widgets::check(ui, tl!("Auto Grouping"), grouping, true) { - st.params["autoGrouping"] = json!(!grouping); - st.preset = "Custom".into(); - retrace = true; - } - // (Black and White has one colour and Flat Logo flat ones: no gradients to find.) - let gradients = st.params["gradients"].as_bool().unwrap_or(false); - if widgets::check(ui, tl!("Gradients"), gradients, mode == "grayscale" || mode == "color") { - st.params["gradients"] = json!(!gradients); - st.preset = "Custom".into(); - retrace = true; - } - // Ignore Color: white, unless another colour is picked. - ui.horizontal(|ui| { - let on = st.params["ignoreWhite"].as_bool().unwrap_or(false); - if widgets::check(ui, tl!("Ignore Color"), on, true) { - if on { - cancel_ignore_sampler(app, true); - } - st.params["ignoreWhite"] = json!(!on); - st.preset = "Custom".into(); - retrace = true; - } - if on { - let mut rgb = ignore_color(&st.params); - let picker = ui.color_edit_button_srgb(&mut rgb); - if picker.clicked() { - cancel_ignore_sampler(app, true); - } - if picker.changed() { - st.params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])); - st.preset = "Custom".into(); - retrace = true; - } - if widgets::icon_button_enabled( - ui, - "pipette", - tl!("Eyedropper: click the source image to sample the ignored color"), - app.ui.trace_ignore_sampler.is_some(), - is_trace || is_image, - 22.0, - ) - .clicked() - { - start_ignore_sampler(app, ui.ctx()); - } - } - }); + if advanced.sampler_toggled { + start_ignore_sampler(app); } - widgets::divider(ui); + if advanced.color_opened { + cancel_ignore_sampler(app, true); + } + + Divider::horizontal().show(ui); if let Some((p, a, c)) = st.info { - widgets::dim_label( - ui, - &crate::i18n::fmt( - tl!("Paths: {paths} Anchors: {anchors} Colors: {colors}"), - &[("paths", &p.to_string()), ("anchors", &a.to_string()), ("colors", &c.to_string())], - ), - ); + Text::new(crate::i18n::fmt( + tl!("Paths: {paths} Anchors: {anchors} Colors: {colors}"), + &[("paths", &p.to_string()), ("anchors", &a.to_string()), ("colors", &c.to_string())], + )) + .shade(Shade::Muted) + .show(ui); } - ui.horizontal(|ui| { + let (mut preview_toggled, mut trace_clicked, mut expand_clicked) = (false, false, false); + Row::new().show(ui, |ui, _| { let preview = app.ui.image_trace_preview; - if widgets::check(ui, tl!("Preview"), preview, true) - && let Err(e) = app.run("imageTrace.preview", json!({})) - { - app.ui.status = e; - } - let r = ui.add_enabled_ui(is_trace || is_image, |ui| widgets::flat_button(ui, tl!("Trace"), 80.0)).inner; - if r.on_disabled_hover_text(tl!("Select an image to trace")).clicked() { - trace(app, ui.ctx(), &mut st); - } - if ui.add_enabled_ui(any_trace, |ui| widgets::flat_button(ui, tl!("Expand"), 80.0)).inner.clicked() { - app.run("imageTrace.expand", json!({})).ok(); + let mut value = preview; + Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); + preview_toggled = value != preview; + let can_trace = is_trace || is_image; + let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); + if !can_trace { + trace_button = trace_button.tooltip(tl!("Select an image to trace")); } + trace_clicked = trace_button.show(ui).clicked(); + expand_clicked = Button::new(tl!("Expand")).enabled(any_trace).show(ui).clicked(); }); + if preview_toggled { + run_reporting(app, "imageTrace.preview", json!({})); + } + if trace_clicked { + trace(app, &mut st); + } + if expand_clicked { + run_reporting(app, "imageTrace.expand", json!({})); + } // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is // traced with the settings that waited in the panel. With no Image Trace object selected, it is // traced when it is selected again. An object whose settings waited while another object was @@ -1122,22 +922,39 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } cancel_disabled_ignore_sampler(app, &st.params); if retrace && is_trace && preview { - trace(app, ui.ctx(), &mut st); + trace(app, &mut st); } - set_pstate(ui.ctx(), "image-trace", st); + app.ui.image_trace_panel.shown = st; } -pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let any_trace = target(app, ui.ctx()).any_trace; - if menu_item(ui, tl!("Release"), any_trace, false) { - app.run("imageTrace.release", json!({})).ok(); +/// The panel menu's rows: Release and Expand act on the selected Image Trace objects. +pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { + vec![ + PanelRow::Command(CommandRef::new("imageTrace.release")), + PanelRow::Command(CommandRef::new("imageTrace.expand")), + PanelRow::Separator, + PanelRow::Command(CommandRef::new("ui.imageTrace.reset")), + ] +} + +/// Release and Expand need an Image Trace object in the selection: `trace_targets` refuses any other. +pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { + let enabled = any_trace_selected(app); + for id in ["imageTrace.release", "imageTrace.expand"] { + let command = CommandRef::new(id); + let state = states.get(&command).cloned().unwrap_or_else(CommandState::new).enabled(enabled); + states.set(command, state); } - if menu_item(ui, tl!("Expand"), any_trace, false) { - app.run("imageTrace.expand", json!({})).ok(); - } - ui.separator(); - if menu_item(ui, tl!("Reset to Default"), true, false) { - set_pstate(ui.ctx(), "image-trace", TraceUi::default()); +} + +/// The panel's own menu commands. +pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option> { + match id { + "ui.imageTrace.reset" => { + app.ui.image_trace_panel.reset(); + Some(Ok(Value::Null)) + } + _ => None, } } diff --git a/crates/ui-egui/src/panels/image_trace/rows.rs b/crates/ui-egui/src/panels/image_trace/rows.rs new file mode 100644 index 0000000000..109b4bb212 --- /dev/null +++ b/crates/ui-egui/src/panels/image_trace/rows.rs @@ -0,0 +1,337 @@ +//! The tracing-settings rows the Image Trace panel, its preset editor and Tracing Presets share: Mode, Palette, +//! Library, Colors and the mode's count or threshold, then the Advanced settings. Each row writes the setting into +//! the `params` it is given and reports what the user did, so a host decides when to trace or save. + +// PLAN: assumed the `craft` dependency of ui-egui enables the `color-ui` feature (`ColorPopover`, `PickedColor`); +// the manifest is outside this set's files. +use std::ops::RangeInclusive; + +use craft::color_ui::ui::{ColorPopover, PickedColor}; +use craft::theme::Srgba; +use craft_ui::buttons::ToggleButton; +use craft_ui::choice::{Checkbox, Segmented}; +use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft_ui::form::{Field, SliderField, SliderFieldLayout}; +use craft_ui::layout_components::Row; +use craft_ui::pickers::Select; +// PLAN: assumed `IconId` is re-exported from `craft_ui::primitives`. +use craft_ui::primitives::IconId; +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; + +use super::{MODES, PALETTES, ignore_color, palette_label}; +use crate::VectorcraftApp; +use crate::panels::swatches; + +/// Where the rows are shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RowsHost { + /// The Image Trace panel: a colour group the active document lacks shows as All. + Panel, + /// A dialog that edits a preset: a colour group stays by its name, whichever document is open. + Dialog, +} + +/// What the rows list: the libraries and the active document's colour groups. +#[derive(Clone)] +pub(crate) struct RowsData { + /// Document Library's choices ([`swatches::library_entries`]). + pub(crate) libraries: Vec>, + /// The active document's colour group names. + pub(crate) groups: Vec, +} + +impl RowsData { + /// The lists for the active document. + pub(crate) fn of(app: &VectorcraftApp) -> Self { + // PLAN: assumed `swatches::library_entries(app: &VectorcraftApp) -> Vec>` (color-w10). + RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app) } + } +} + +/// What the user did in the rows in one pass. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct RowsOutput { + /// A setting changed, a slider's proposals included. + pub(crate) changed: bool, + /// A setting was settled: a pick, a check, a segment or colour pick, or a slider's commit. + pub(crate) committed: bool, + /// The colour well of Ignore Color was clicked. + pub(crate) color_opened: bool, + /// The eyedropper button was toggled. + pub(crate) sampler_toggled: bool, +} + +impl RowsOutput { + fn picked(&mut self) { + self.changed = true; + self.committed = true; + } +} + +/// The Ignore Color eyedropper button of a host that can sample the source image. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Sampler { + /// The button can be used: an image or an Image Trace object is the target. + pub(crate) enabled: bool, + /// The sampler is armed. + pub(crate) armed: bool, +} + +/// The names of the active document's colour groups. +pub(super) fn swatch_groups(app: &VectorcraftApp) -> Vec { + app.session.active().map(|d| d.doc.swatch_groups.iter().map(|g| g.name.clone()).collect()).unwrap_or_default() +} + +/// `params`' colour group when `groups` has it, found as `imageTrace.make` finds it (named exactly, else ignoring +/// case); `None` is All. A group of another document, or a deleted one, is All. +pub(super) fn known_group<'a>(groups: &[String], params: &'a Value) -> Option<&'a str> { + let name = params["colorGroup"].as_str().filter(|g| !g.is_empty())?; + let lower = name.to_lowercase(); + groups.iter().any(|g| g.to_lowercase() == lower).then_some(name) +} + +/// The tooltip and name of the eyedropper button. +fn sample_tip() -> &'static str { + tl!("Eyedropper: click the source image to sample the ignored color") +} + +fn text(params: &Value, key: &str, default: &str) -> String { + params[key].as_str().unwrap_or(default).to_string() +} + +/// A number as the engine stores the setting `key`: whole for counts, else rounded. +fn number(key: &str, v: f64) -> Value { + if matches!(key, "threshold" | "colors" | "noise") { json!(v.round() as u64) } else { json!(v.round()) } +} + +fn hex(color: Srgba) -> String { + let [r, g, b] = color.to_rgb_array().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + format!("#{r:02x}{g:02x}{b:02x}") +} + +/// A check box named `label`; whether this pass flipped it. +fn check(ui: &mut Ui, label: &'static str, on: bool, enabled: bool) -> bool { + let mut value = on; + Checkbox::new(Bind::bound(&mut value)).label(label).enabled(enabled).show(ui); + value != on +} + +/// A field named `label` over a select of `entries` showing `current`; the key the user picked this pass. +fn select_row(ui: &mut Ui, label: &'static str, entries: &[Entry], current: &str, placeholder: Option<&str>) -> Option { + Field::new(label) + .show(ui, |ui, _| { + let mut select = Select::new(label, Bind::given(current.to_string()), entries); + if let Some(p) = placeholder { + select = select.placeholder(p.to_string()); + } + select.show(ui).events.committed().cloned() + }) + .inner + .flatten() +} + +/// One number setting: its key, name, range, unit and the value shown when the setting is absent. +struct Slider { + key: &'static str, + label: &'static str, + range: RangeInclusive, + unit: Option<&'static str>, + default: f64, +} + +fn slider(key: &'static str, label: &'static str, range: RangeInclusive, unit: Option<&'static str>) -> Slider { + Slider { key, label, range, unit, default: 0.0 } +} + +fn slider_row(ui: &mut Ui, params: &mut Value, spec: Slider, enabled: bool, out: &mut RowsOutput) { + let Slider { key, label, range, unit, default } = spec; + let value = params[key].as_f64().unwrap_or(default); + let events = Field::new(label) + .enabled(enabled) + .show(ui, |ui, _| { + let mut field = SliderField::new(label, Bind::given(value), range.clone()).layout(SliderFieldLayout::Inline).step(1.0).enabled(enabled); + if let Some(unit) = unit { + field = field.unit(unit); + } + field.show(ui).edit.events + }) + .inner; + let Some(events) = events else { return }; + if let Some(v) = events.value() { + params[key] = number(key, *v); + out.changed = true; + } + out.committed |= events.committed().is_some(); +} + +/// Mode, Palette (Color only), Library and Colors (Document Library only), and the mode's count or threshold. +pub(crate) fn main_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, host: RowsHost) -> RowsOutput { + let mut out = RowsOutput::default(); + let mode = text(params, "mode", "blackAndWhite"); + let modes: Vec> = MODES.iter().map(|(id, label)| Entry::new((*id).to_string(), *label)).collect(); + if let Some(k) = select_row(ui, tl!("Mode:"), &modes, &mode, None) { + // Only Color mode uses a color group. + if k != "color" { + params["colorGroup"] = Value::Null; + } + params["mode"] = json!(k); + out.picked(); + } + let palette = text(params, "palette", "limited"); + if mode == "color" { + let palettes: Vec> = PALETTES.iter().map(|id| Entry::new((*id).to_string(), palette_label(id))).collect(); + if let Some(k) = select_row(ui, tl!("Palette:"), &palettes, &palette, None) { + // Every other palette refuses a color group. + if k != "documentLibrary" { + params["colorGroup"] = Value::Null; + } + params["palette"] = json!(k); + out.picked(); + } + if palette == "documentLibrary" { + let key = text(params, "library", DOCUMENT_SWATCHES); + if let Some(k) = select_row(ui, tl!("Library:"), &data.libraries, &key, Some(&key)) { + if k != DOCUMENT_SWATCHES { + params["colorGroup"] = Value::Null; + } + params["library"] = json!(k); + out.picked(); + } + // The document's swatches: every one, or one color group's. + if key == DOCUMENT_SWATCHES { + let group = match host { + RowsHost::Panel => known_group(&data.groups, params), + RowsHost::Dialog => params["colorGroup"].as_str().filter(|g| !g.is_empty()), + } + .map(str::to_string); + let mut groups = vec![Entry::new(String::new(), tl!("All"))]; + if !data.groups.is_empty() { + groups.push(Entry::separator()); + groups.extend(data.groups.iter().map(|g| Entry::new(g.clone(), g.clone()))); + } + let current = group.clone().unwrap_or_default(); + if let Some(k) = select_row(ui, tl!("Colors:"), &groups, ¤t, group.as_deref()) { + params["colorGroup"] = if k.is_empty() { Value::Null } else { json!(k) }; + out.picked(); + } + } + } + } + // Full Tone and Automatic: how many colours (Less … More); else a count or the threshold. + let count = match mode.as_str() { + "blackAndWhite" => slider("threshold", tl!("Threshold"), 0.0..=255.0, None), + "grayscale" => slider("colors", tl!("Grays"), 2.0..=256.0, None), + // Flat Logo finds a handful of flat colours: more than ten is almost always noise. + "logo" => slider("colors", tl!("Colors"), 2.0..=10.0, None), + _ if matches!(palette.as_str(), "fullTone" | "automatic") => slider("colorDetail", tl!("Colors"), 0.0..=100.0, Some("%")), + _ => slider("colors", tl!("Colors"), 2.0..=256.0, None), + }; + slider_row(ui, params, count, true, &mut out); + out +} + +/// The Advanced settings: fidelity, method, Create, snapping, shapes, grouping, gradients and Ignore Color, with an +/// eyedropper for Ignore Color when the host passes a `sampler`. `_data` and `_host` are the arguments of +/// [`main_rows`], so a host passes the same set to both. +pub(crate) fn advanced_rows( + ui: &mut Ui, + params: &mut Value, + _data: &RowsData, + _host: RowsHost, + sampler: Option, +) -> RowsOutput { + let mut out = RowsOutput::default(); + let mode = text(params, "mode", "blackAndWhite"); + for spec in [ + slider("paths", tl!("Paths"), 0.0..=100.0, Some("%")), + slider("corners", tl!("Corners"), 0.0..=100.0, Some("%")), + slider("noise", tl!("Noise"), 1.0..=100.0, Some("px")), + ] { + slider_row(ui, params, spec, true, &mut out); + } + // Flat Logo always paints biggest shapes first with a hair of overlap, so there is no choice. + if mode != "logo" { + let methods = [Entry::new("abutting".to_string(), tl!("Abutting")), Entry::new("overlapping".to_string(), tl!("Overlapping"))]; + let method = text(params, "method", ""); + let picked = Field::new(tl!("Method:")) + .show(ui, |ui, _| Segmented::new(tl!("Method:"), Bind::given(method.clone()), &methods).show(ui).events.committed().cloned()) + .inner + .flatten(); + if let Some(m) = picked.filter(|m| *m != method) { + params["method"] = json!(m); + out.picked(); + } + // Create: Fills and/or Strokes (one of them stays on), and the widest line stroked. + let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills"); + let (fills, strokes) = (create(params, "fills"), create(params, "strokes")); + let mut flipped = None; + Field::new(tl!("Create:")).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + let mut hit = None; + for (key, on, other, label) in [("fills", fills, strokes, tl!("Fills")), ("strokes", strokes, fills, tl!("Strokes"))] { + if check(ui, label, on, !on || other) { + hit = Some(key); + } + } + flipped = hit; + }); + }); + if let Some(key) = flipped { + params[key] = json!(!create(params, key)); + out.picked(); + } + slider_row(ui, params, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out); + } + // (Black and White has one colour and Flat Logo flat ones: no gradients to find.) + let gradients = mode == "grayscale" || mode == "color"; + for (key, label, enabled) in [ + ("snapCurvesToLines", tl!("Snap Curves To Lines"), true), + ("shapes", tl!("Shapes"), true), + ("autoGrouping", tl!("Auto Grouping"), true), + ("gradients", tl!("Gradients"), gradients), + ] { + let on = params[key].as_bool().unwrap_or(false); + if check(ui, label, on, enabled) { + params[key] = json!(!on); + out.picked(); + } + } + // Ignore Color: white, unless another colour is picked. + let on = params["ignoreWhite"].as_bool().unwrap_or(false); + let (mut flipped, mut opened, mut toggled, mut color) = (false, false, false, None); + Row::new().show(ui, |ui, _| { + flipped = check(ui, tl!("Ignore Color"), on, true); + (opened, toggled, color) = (false, false, None); + if !on { + return; + } + let [r, g, b] = ignore_color(params).map(|c| f32::from(c) / 255.0); + let well = ColorPopover::new(tl!("Color"), Bind::given(PickedColor::rgb(Srgba::rgb(r, g, b)))).show(ui); + opened = well.response.clicked(); + color = well.events.value().map(|p| (hex(p.color), well.events.committed().is_some())); + if let Some(s) = sampler { + let mut armed = s.armed; + ToggleButton::new(sample_tip(), Bind::bound(&mut armed)) + .icon(IconId::new("pipette")) + .icon_only() + .tooltip(sample_tip()) + .enabled(s.enabled) + .show(ui); + toggled = armed != s.armed; + } + }); + if flipped { + params["ignoreWhite"] = json!(!on); + out.picked(); + } + if let Some((color, settled)) = color { + params["ignoreColor"] = json!(color); + out.changed = true; + out.committed |= settled; + } + out.color_opened = opened; + out.sampler_toggled = toggled; + out +}