Param list additions and the preview click point: Param::multiline, Param::read_only_text, PreviewOutput::clicked through ParamDialog and HostedParamDialog

This commit is contained in:
aiongg
2026-11-13 18:32:12 +00:00
parent df9a3eee36
commit 02e1c47112
12 changed files with 259 additions and 42 deletions
@@ -340,6 +340,10 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
Some(DraftChange::Revert) => state.end = Some(End::Revert),
None => {}
}
// A plain Enter in an editable multi-line field inserts a line, so no default button around the field takes it.
if focused_before && input.options.multiline() && !input.read_only && state.preedit.is_none() {
input.intents.take(Intent::Submit);
}
// A clearing field takes Escape while it shows text, with or without a draft, and passes it on once it is empty.
let takes_escape =
if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { state.draft.is_some() || state.preedit.is_some() };
@@ -26,7 +26,7 @@ use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
use egui::load::SizedTexture;
use egui::{Context, Response, Ui};
use egui::{Context, Pos2, Response, Ui};
use serde_json::Value;
use std::borrow::Cow;
@@ -102,6 +102,9 @@ pub struct ParamDialogOutput {
/// Whether the Preview check box is on and held: the host shows the unfiltered picture in the preview pane while
/// it is.
pub comparing: bool,
/// The point of the preview picture a click landed on this pass (`PreviewOutput::clicked`): an eyedropper on the
/// preview samples there.
pub preview_click: Option<Pos2>,
}
impl Outcome for ParamDialogOutput {
@@ -176,6 +179,10 @@ pub struct ParamDialog<'a> {
/// The picture the preview pane shows; without one the dialog has no preview.
#[prop]
preview: Option<SizedTexture>,
/// Whether a click on the preview centres it on the point clicked (`PreviewPane::click_centres`); a dialog whose
/// preview clicks pick a colour turns it off. The default is true.
#[prop]
click_centres: bool,
/// Controls before the buttons in the footer (Color Table's Load and Save).
#[prop(func = "FnMut(&mut Ui)")]
footer_extra: Option<FooterExtra<'a>>,
@@ -237,6 +244,7 @@ impl<'a> ParamDialog<'a> {
layout: ParamLayout::default(),
closable: true,
preview: None,
click_centres: true,
footer_extra: None,
below: None,
shaped: None,
@@ -326,6 +334,7 @@ impl<'a> ParamDialog<'a> {
layout,
closable,
preview,
click_centres,
footer_extra,
below,
shaped,
@@ -377,6 +386,7 @@ impl<'a> ParamDialog<'a> {
let mut live = Live::default();
let mut rows = None;
let mut preview_click = None;
let shown = form.show(ui, |ui, cx, values| {
if cx.first() && !values_opened {
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<DialogFields>>(key).clone());
@@ -396,13 +406,13 @@ impl<'a> ParamDialog<'a> {
(Some(texture), ParamLayout::Beside) => {
Row::new().show(ui, |ui, _| {
show_rows(ui, values);
Stack::new().show(ui, |ui, _| show_preview(ui, &preview_label, texture, &mut live));
Stack::new().show(ui, |ui, _| preview_click = show_preview(ui, &preview_label, texture, click_centres, &mut live));
});
}
(Some(texture), ParamLayout::Below) => {
Stack::new().show(ui, |ui, _| {
show_rows(ui, values);
show_preview(ui, &preview_label, texture, &mut live);
preview_click = show_preview(ui, &preview_label, texture, click_centres, &mut live);
});
}
(None, _) => show_rows(ui, values),
@@ -423,6 +433,7 @@ impl<'a> ParamDialog<'a> {
values: shown.value,
preview_on: shown.preview_on,
comparing: shown.comparing,
preview_click,
}
}
}
@@ -557,11 +568,12 @@ impl ResetFooter {
}
}
/// The zoom row and the pane.
fn show_preview(ui: &mut Ui, label: &Label, texture: &SizedTexture, live: &mut Live) {
/// The zoom row and the pane; returns the picture point a click landed on.
fn show_preview(ui: &mut Ui, label: &Label, texture: &SizedTexture, click_centres: bool, live: &mut Live) -> Option<Pos2> {
let zoom = PreviewZoom::new(&live.view).show(ui);
let pane = PreviewPane::new(label.clone(), *texture, &live.view).show(ui);
let pane = PreviewPane::new(label.clone(), *texture, &live.view).click_centres(click_centres).show(ui);
live.view = zoom.view.or(pane.view).unwrap_or(pane.shown);
pane.clicked
}
/// Builds the dialog over the host-owned values of a [`HostedParamDialog`] for one pass.
@@ -638,6 +650,11 @@ impl HostedParamDialog {
self.requests.take_path()
}
/// The point of the preview picture the last click landed on (`ParamDialogOutput::preview_click`), once.
pub fn take_preview_click(&mut self) -> Option<Pos2> {
self.requests.take_preview_click()
}
/// Answers the colour request `key`: the dialog writes the colour into its values in its next pass.
pub fn answer_color(&mut self, key: impl Into<String>, color: craft_theme::Srgba) {
self.requests.answer_color(key, color);
@@ -682,7 +699,7 @@ fn read_value(kind: &ParamKind, value: Value) -> Option<FieldValue> {
ParamKind::Color { .. } => FieldValue::Color(serde_json::from_value(value).ok()?),
ParamKind::Point { .. } => FieldValue::Point(serde_json::from_value(value).ok()?),
ParamKind::Grid { .. } => FieldValue::Grid(serde_json::from_value(value).ok()?),
ParamKind::Custom(_) | ParamKind::Section => return None,
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
})
}
@@ -700,6 +717,9 @@ impl StackDialog for HostedParamDialog {
if let Some(mut rows) = shown.rows {
self.requests.absorb(&mut rows);
}
if let Some(point) = shown.preview_click {
self.requests.request_preview_click(point);
}
match (shown.result, shown.closed) {
(Some(result), _) => Some(DialogResult::Ok(result)),
(None, Some(_)) => Some(DialogResult::Cancel),
@@ -4,7 +4,6 @@
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::display::Text;
use crate::form::Field;
use crate::layout_components::{Row, Stack};
use crate::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult};
@@ -438,11 +437,7 @@ fn params(words: &FormatOptionsWords, start: FormatOptions) -> Vec<Param> {
match start {
FormatOptions::Jpeg(options) => jpeg_params(words, options),
FormatOptions::Tiff(options) => vec![
Param::custom("note", words.layers_note.clone(), {
let note = words.layers_note.clone();
move |ui, _, _| Text::new(note.clone()).show(ui)
})
.full_width(),
Param::read_only_text("note", words.layers_note.clone(), words.layers_note.clone()).full_width(),
Param::new(DISCARD, words.discard_layers.clone(), ParamKind::bool(options.discard_layers)),
Param::new(DONT_SHOW, words.dont_show.clone(), ParamKind::bool(options.dont_show_again)),
],
@@ -3,6 +3,7 @@
use super::rows::ParamRowsOutput;
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, PathRequest};
use craft_theme::Srgba;
use egui::Pos2;
use std::path::PathBuf;
/// A request to render a preview of `options`, numbered so the host's answer can be matched to the settings it was
@@ -23,14 +24,15 @@ impl<O> PreviewRequest<O> {
}
}
/// The requests of parameter rows that the host answers: the colour picker, the file dialog and the eyedropper. A
/// hosted dialog embeds one, feeds it each pass's rows with [`absorb`](HostRequests::absorb) and offers the
/// The requests of parameter rows that the host answers: the colour picker, the file dialog and the eyedropper, and
/// the click on a dialog's preview picture (an eyedropper there samples it). A hosted dialog embeds one, feeds it each pass's rows with [`absorb`](HostRequests::absorb) and offers the
/// `take_*` methods to its host. A request stays until it is taken; a newer one of the same kind replaces it.
#[derive(Clone, Debug, Default)]
pub struct HostRequests {
color: Option<ColorRequest>,
path: Option<PathRequest>,
eyedropper: Option<EyedropperRequest>,
preview_click: Option<Pos2>,
answers: Vec<HostAnswer>,
}
@@ -68,6 +70,11 @@ impl HostRequests {
self.eyedropper = Some(request);
}
/// Files a click on the preview picture at `point`, in the picture's units; it replaces one not taken yet.
pub fn request_preview_click(&mut self, point: Pos2) {
self.preview_click = Some(point);
}
/// The colour parameter whose button was pressed, once.
pub fn take_color(&mut self) -> Option<ColorRequest> {
self.color.take()
@@ -83,6 +90,11 @@ impl HostRequests {
self.eyedropper.take()
}
/// The preview picture's point the last click landed on, once.
pub fn take_preview_click(&mut self) -> Option<Pos2> {
self.preview_click.take()
}
/// Answers the colour request `key` with `color`: the dialog writes it into its values in its next pass.
pub fn answer_color(&mut self, key: impl Into<String>, color: Srgba) {
self.color = None;
@@ -107,10 +119,11 @@ impl HostRequests {
/// Moves the requests and answers of `other` in; its requests replace the ones not taken yet.
pub fn extend(&mut self, other: HostRequests) {
let HostRequests { color, path, eyedropper, answers } = other;
let HostRequests { color, path, eyedropper, preview_click, answers } = other;
self.color = color.or(self.color.take());
self.path = path.or(self.path.take());
self.eyedropper = eyedropper.or(self.eyedropper.take());
self.preview_click = preview_click.or(self.preview_click.take());
self.answers.extend(answers);
}
@@ -136,6 +136,12 @@ pub enum ParamKind {
/// The most digits shown after the decimal mark; 0 for an integer.
decimals: u32,
},
/// Read-only text the user can select and copy: see [`Param::read_only_text`]. It has no value.
#[non_exhaustive]
ReadOnlyText {
/// The text shown; line breaks start new lines.
text: Label,
},
/// A row the host draws: see [`Param::custom`]. It has no value of its own.
Custom(CustomRow),
/// A section heading over the rows that follow it: see [`Param::section`]. It has no value.
@@ -239,7 +245,7 @@ impl ParamKind {
ParamKind::Channel { default, .. } => FieldValue::Int(i64::try_from(*default).unwrap_or(0)),
ParamKind::Text { default } => FieldValue::Text(default.clone()),
ParamKind::OptionalNumber { default, .. } => FieldValue::Number((*default)?),
ParamKind::Custom(_) | ParamKind::Section => return None,
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
})
}
@@ -364,6 +370,8 @@ pub(crate) struct RowOptions {
eyedropper_armed: bool,
full_width: bool,
not_remembered: bool,
/// The lines a multi-line text row shows.
lines: Option<usize>,
units: Option<UnitChoices>,
}
@@ -449,6 +457,13 @@ impl Param {
Self::new(key, label, ParamKind::Custom(CustomRow::new(draw)))
}
/// A row of read-only `text` beside the label, wrapped to the form's width: the user can select and copy it, and
/// Tab passes over it. It has no value, so nothing is remembered or in the result. With
/// [`full_width`](Param::full_width) it has no label and spans the form (a note over the rows).
pub fn read_only_text(key: impl Into<String>, label: impl Into<Label>, text: impl Into<Label>) -> Self {
Self::new(key, label, ParamKind::ReadOnlyText { text: text.into() })
}
/// A section heading: the label as the title of a section whose body is the rows that follow, up to the next
/// section. It has no value and no control.
pub fn section(label: impl Into<Label>) -> Self {
@@ -563,13 +578,22 @@ impl Param {
self
}
/// For a [`Param::custom`] row: no label, and the body spans the width of the form; other kinds are unchanged.
/// For a [`Param::custom`] or [`Param::read_only_text`] row: no label, and the body spans the width of the form;
/// other kinds are unchanged.
#[must_use]
pub fn full_width(mut self) -> Self {
self.options.get_or_insert_default().full_width = true;
self
}
/// A [`ParamKind::Text`] row without a Browse button edits multi-line text in a field `lines` lines tall: Enter
/// inserts a line break and the dialog's default button leaves it to the field. Other kinds are unchanged.
#[must_use]
pub fn multiline(mut self, lines: usize) -> Self {
self.options.get_or_insert_default().lines = Some(lines);
self
}
/// Leaves the row out of the remembered values: a choice that refers to something in the document (a depth
/// channel, a menu of open documents) opens from its default every time.
#[must_use]
@@ -671,6 +695,11 @@ impl RowOptions {
self.full_width
}
/// The lines of a multi-line text row; `None` for a single line.
pub(crate) fn lines(&self) -> Option<usize> {
self.lines
}
/// The units of a number row.
pub(crate) fn units(&self) -> Option<&UnitChoices> {
self.units.as_ref()
@@ -16,7 +16,7 @@ use crate::style::{ComponentStyle, FocusLook, StyleCx};
use crate::text::NumberField;
use craft_behavior::{AccessAction, AccessData, CanvasTransform, CursorIcon, CursorPriority, IconId, Metrics, NavMove, PartKey, PressPhase, Sense};
use egui::load::SizedTexture;
use egui::{Rect, Response, Ui, Vec2, pos2};
use egui::{Pos2, Rect, Response, Ui, Vec2, pos2};
use std::ops::RangeInclusive;
#[cfg(feature = "testing")]
@@ -202,6 +202,10 @@ pub struct PreviewOutput {
/// The well took the second press of a double click this pass. The pane returns to fit on it; a caller may
/// also act on it (open the picture larger, say).
pub double_clicked: bool,
/// The point of the picture a single click landed on this pass, in the picture's own units (its pixels when the
/// texture's size is its pixel size) from its top-left corner; `None` when there was no click or it missed the
/// picture. It is reported whether or not the click centres the view: an eyedropper or a locator reads it.
pub clicked: Option<Pos2>,
}
impl Outcome for PreviewOutput {
@@ -219,6 +223,7 @@ impl Outcome for PreviewOutput {
/// wheel pans where the picture overflows the well and Ctrl or Cmd with the wheel zooms about the pointer, so the
/// point under it stays. On an axis where the picture fits the well the wheel does not scroll the pane, so the
/// scroll region around it takes it; zoom is always the pane's.
/// - A click reports the picture point under it in `PreviewOutput::clicked`, centring or not.
/// - While the [`PreviewView`] is `fit` the zoom is the one that shows the whole picture in the well, recomputed when
/// the well changes. A pan or zoom leaves fit and a double click returns to it.
/// - The pane keeps no view: it shows the one given and reports the next in `PreviewOutput::view`. `PreviewZoom`
@@ -243,6 +248,8 @@ pub struct PreviewPane<'a> {
moved: Option<PreviewView>,
/// The well took the second press of a double click this pass.
double_clicked: bool,
/// The picture point a single click landed on this pass.
clicked: Option<Pos2>,
/// The host's drawing over the picture of a `Ready` pane.
#[prop(func = "FnOnce(&ContentPainterCx, CanvasTransform, Rect)")]
overlay: Option<PaneOverlay<'a>>,
@@ -271,6 +278,7 @@ impl PreviewPane<'_> {
aspect: None,
moved: None,
double_clicked: false,
clicked: None,
overlay: None,
overflow: (false, false),
fixed: view.fixed,
@@ -447,8 +455,13 @@ impl Component for PreviewPane<'_> {
refit = true;
self.double_clicked = true;
}
PressPhase::Release { start, pos, click: true, .. } if self.click_centres && start.clicks < 2 => {
next.offset += well.center() - pos;
PressPhase::Release { start, pos, click: true, .. } if start.clicks < 2 => {
let point = (pos - well.center() - shown.offset) / shown.scale + texture.size / 2.0;
let on_picture = (0.0..=texture.size.x).contains(&point.x) && (0.0..=texture.size.y).contains(&point.y);
self.clicked = on_picture.then(|| point.to_pos2());
if self.click_centres {
next.offset += well.center() - pos;
}
}
_ => {}
}
@@ -548,7 +561,7 @@ impl Component for PreviewPane<'_> {
fn finish(self, cx: Cx<'_, Self>) -> PreviewOutput {
let shown = PreviewView { transform: self.shown(cx.rect.size()), ..self.view.clone() };
PreviewOutput { response: cx.response.clone(), view: self.moved, shown, double_clicked: self.double_clicked }
PreviewOutput { response: cx.response.clone(), view: self.moved, shown, double_clicked: self.double_clicked, clicked: self.clicked }
}
}
@@ -10,7 +10,6 @@ use crate::runtime::overlay::CloseReason;
use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
use crate::tabs::{Tab, TabKind, TabStrip};
use crate::text::SelectableText;
use craft_behavior::{DisplayOrder, ItemSource, SelectionChange};
use egui::{Response, Ui};
use std::borrow::Cow;
@@ -77,19 +76,13 @@ impl PropertiesTab {
PropertiesTab { title: title.into(), rows }
}
/// The parameters the rows are: a read-only row draws its text, a heading is a section.
/// The parameters the rows are: a value is a read-only text row, a heading is a section.
fn params(&self, at: usize) -> Vec<Param> {
self.rows
.iter()
.enumerate()
.map(|(row, entry)| match entry {
PropertyRow::Value { label, text } => {
let (name, text) = (label.clone(), text.clone());
Param::custom(format!("properties.{at}.{row}"), label.clone(), move |ui, _, _| {
let shown = Env::of(ui).view().resolve(&text);
SelectableText::new(name.clone(), shown.as_str()).multiline().show(ui)
})
}
PropertyRow::Value { label, text } => Param::read_only_text(format!("properties.{at}.{row}"), label.clone(), text.clone()),
PropertyRow::Field(param) => (**param).clone(),
PropertyRow::Heading(label) => Param::section(label.clone()),
PropertyRow::Space => Param::custom(format!("properties.{at}.{row}"), Label::Empty, |ui, _, _| Text::new(Label::Empty).show(ui)),
@@ -20,7 +20,7 @@ use crate::pickers::{Select, UnitSelect};
use crate::runtime::env::{Env, Label, UnitKind, Units, with_env};
use crate::sections::{HeaderStrength, Section};
use crate::text::{NumberField, TextField};
use crate::text::{NumberField, SelectableText, TextField};
use crate::value_drag::{AngleDial, PointPicker, SliderScale};
@@ -290,6 +290,7 @@ impl<'p> Pass<'p> {
ParamKind::Channel { names, default } => self.channel(ui, &line, names, *default),
ParamKind::Text { default } => self.text(ui, &line, default),
ParamKind::OptionalNumber { min, max, initial, decimals, .. } => self.optional(ui, &line, *min..=*max, *initial, *decimals),
ParamKind::ReadOnlyText { text } => read_only_text(ui, &line, text),
ParamKind::Custom(_) => self.custom(ui, &line),
ParamKind::Section => {}
}
@@ -563,6 +564,9 @@ impl<'p> Pass<'p> {
}
None => {
let mut field = TextField::new(line.name.clone(), Bind::given(value.clone())).id_salt("text");
if let Some(lines) = line.param.option().lines() {
field = field.lines(lines);
}
if let Some(hint) = line.param.hint_text() {
field = field.placeholder(hint.clone());
}
@@ -618,6 +622,19 @@ impl<'p> Pass<'p> {
}
}
/// Read-only text beside the row's label, or across the form for a full-width row.
fn read_only_text(ui: &mut Ui, line: &Line<'_>, text: &Label) {
let shown = Env::of(ui).view().resolve(text);
let body = |ui: &mut Ui| {
SelectableText::new(line.name.clone(), shown.as_str()).multiline().show(ui);
};
if line.param.option().full_width() {
Row::new().id_salt(line.key).enabled(line.enabled).fill().show(ui, |ui, _| body(ui));
} else {
line.show(ui, body);
}
}
/// Shows `body` as one row of controls side by side.
fn beside(ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
Row::new().show(ui, |ui, _| body(ui));
@@ -12,7 +12,8 @@ use egui::Ui;
const SPEC: &str = r#"{"radius":0.1..1000=1,"method":"spin|zoom","smooth":bool,"seed":u32=0,"tint":color=#336699}"#;
/// One row of every kind the rows show, a section, a row that waits for a check box and a row with a unit menu.
/// One row of every kind the rows show, a section, a row that waits for a check box, a row with a unit menu, a
/// multi-line text row and a section of read-only rows.
fn params() -> Vec<Param> {
let mut params = Param::parse_list(SPEC);
params.push(Param::new("angle", "Angle", ParamKind::angle(30.0)));
@@ -35,6 +36,10 @@ fn params() -> Vec<Param> {
params.push(Param::new("kernel", "Kernel", ParamKind::grid(9, 0)));
params.push(Param::new("sharpen", "Sharpen", ParamKind::bool(false)));
params.push(Param::new("amount", "Amount", ParamKind::range(0.0, 100.0, 50.0, Default::default())).enabled_when("sharpen", true));
params.push(Param::new("notes", "Notes", ParamKind::text("")).multiline(3));
params.push(Param::section("Camera Data"));
params.push(Param::read_only_text("make", "Make", "Canon"));
params.push(Param::read_only_text("exposure", "Exposure", "1/250 s at f/8"));
params
}
@@ -1,7 +1,7 @@
//! `ParamDialog`: the dialog's own undo history and the Preview box's hold-to-compare.
//! `ParamDialog`: the dialog's own undo history, the Preview box's hold-to-compare and Enter in a multi-line row.
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog};
use craft_ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind};
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
use egui::{Key, Modifiers, TextureId, vec2};
@@ -63,3 +63,37 @@ fn holding_the_preview_box_compares_and_the_release_toggles_it() {
fixture.release(&preview).settle();
assert_eq!(seen.get(), (false, false), "the release turns the preview off");
}
/// The notes and whether the dialog answered OK after typing "a", Enter, "b" in a Notes row of `lines` lines.
fn enter_in_notes(lines: Option<usize>) -> (String, bool) {
let values = Rc::new(RefCell::new(DialogFields::new()));
let accepted = Rc::new(Cell::new(false));
let (shown, ok) = (values.clone(), accepted.clone());
let mut fixture = Fixture::new(move |ui| {
let notes = Param::new("notes", "Notes", ParamKind::text(""));
let params = vec![lines.map_or(notes.clone(), |lines| notes.multiline(lines))];
let out = ParamDialog::new("info", "Info", params).values(Bind::bound(&mut *shown.borrow_mut())).show(ui);
if out.result.is_some() {
ok.set(true);
}
});
fixture.settle();
let field = fixture.by_label("Notes").expect("the notes row has a field");
fixture.click(&field).settle();
fixture.type_text("a");
fixture.key(Key::Enter, Modifiers::NONE).settle();
if !accepted.get() {
fixture.type_text("b").settle();
}
let notes = values.borrow().text("notes").unwrap_or_default().to_owned();
(notes, accepted.get())
}
// Enter in a multi-line row starts a new line and leaves the dialog open; in a single-line row it is the OK.
#[trial]
fn enter_in_a_multi_line_row_inserts_a_line_and_the_dialog_stays_open() {
let (notes, accepted) = enter_in_notes(Some(3));
assert_eq!((notes.as_str(), accepted), ("a\nb", false));
let (_, accepted) = enter_in_notes(None);
assert!(accepted, "Enter in a single-line row answers OK");
}
@@ -1,8 +1,12 @@
//! The parameter model: the spec-string parser, kinds, defaults and fit rules.
//! The parameter model: the spec-string parser, kinds, defaults and fit rules, and the rows' predicates, read-only
//! text and tooltips.
use craft_ui::patterns::form_dialogs::{FieldValue, Param, ParamKind};
use craft_ui::testing::trial;
use craft_ui::contract::Bind;
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, ParamRows};
use craft_ui::testing::{Fixture, trial};
use craft_ui::value_drag::SliderScale;
use std::cell::RefCell;
use std::rc::Rc;
const SPEC: &str = r#"{"radius":0.1..1000=1,"method":"spin|zoom"="zoom","monochromatic":bool,"seed":u32=0,"cellSize":px=4,"tint":color=#ff8000,"kernel":int[25],"layer":layer id,"curve":json,"note":text} -> {"x":1}"#;
const KERNEL_CELLS: usize = 25;
@@ -30,3 +34,52 @@ fn the_registry_notation_parses_into_params() {
assert!(!params[0].kind.fits(&FieldValue::Number(5000.0)));
assert!(!params[1].kind.fits(&FieldValue::Text("wobble".into())));
}
/// A fixture showing `params` as rows over `values`.
fn rows(params: Vec<Param>, values: &Rc<RefCell<DialogFields>>) -> Fixture {
let shown = values.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = ParamRows::new("Form", &params, Bind::bound(&mut *shown.borrow_mut())).show(ui);
});
fixture.settle();
fixture
}
// A row with `visible_when` is there only while its condition holds, and one with `enabled_when` takes input only
// while its condition holds; a tooltip is the description of its row.
#[trial]
fn rows_follow_their_predicates_and_carry_their_tooltip() {
let source = ParamKind::choice(vec![("file".into(), "File".into()), ("folder".into(), "Folder".into())], None);
let params = vec![
Param::new("source", "Source", source),
Param::new("input", "Input Folder", ParamKind::text("")).visible_when("source", "folder"),
Param::new("custom", "Custom", ParamKind::bool(false)).tooltip("Use your own quality"),
Param::new("quality", "Quality", ParamKind::int(Some(0), Some(12), 8)).enabled_when("custom", true),
];
let values = Rc::new(RefCell::new(DialogFields::new()));
let mut fixture = rows(params, &values);
assert!(fixture.by_label("Input Folder").is_none(), "hidden while the source is a file");
let quality = fixture.by_label("Quality").expect("the quality row");
assert!(fixture.tree().is_disabled_key(quality.node), "disabled until Custom is on");
let custom = fixture.by_label("Custom").expect("the custom row");
assert_eq!(fixture.tree().description_of(custom.node), Some("Use your own quality"));
fixture.click(&custom).settle();
let quality = fixture.by_label("Quality").expect("the quality row");
assert!(!fixture.tree().is_disabled_key(quality.node), "enabled with Custom on");
values.borrow_mut().set("source", FieldValue::Text("folder".into()));
fixture.settle();
assert!(fixture.by_label("Input Folder").is_some(), "shown once the source is a folder");
}
// A read-only row shows its text, selectable, and keeps no value.
#[trial]
fn a_read_only_row_shows_its_text_and_keeps_no_value() {
let params = vec![Param::section("Camera Data"), Param::read_only_text("make", "Make", "Canon")];
let values = Rc::new(RefCell::new(DialogFields::new()));
let fixture = rows(params, &values);
let tree = fixture.tree();
let shown = tree.keys().into_iter().any(|key| tree.value_of(key) == Some("Canon"));
assert!(shown, "the text is the value of a node");
assert!(!values.borrow().contains("make"), "the row keeps no value");
}
@@ -1,10 +1,12 @@
//! The preview's zoom row.
//! The preview's zoom row and the picture point a click reports.
use craft_behavior::CanvasTransform;
use craft_ui::patterns::form_dialogs::{PreviewView, PreviewZoom};
use craft_ui::contract::Show as _;
use craft_ui::patterns::form_dialogs::{PreviewPane, PreviewView, PreviewZoom};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
use std::cell::RefCell;
use egui::load::SizedTexture;
use egui::{Key, Modifiers, Pos2, TextureId, Vec2, pos2, vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// Zooms closer than this are the same zoom.
@@ -39,3 +41,42 @@ fn a_typed_zoom_sets_the_preview_zoom_inside_its_range() {
let end = *view.borrow().range.end();
assert!((view.borrow().transform.scale - end).abs() < SAME, "a zoom past the range stops at its end: {:?}", view.borrow().transform);
}
/// The picture the click trials show.
const PICTURE: Vec2 = vec2(64.0, 48.0);
/// What a pane at `scale`, centring on a click or not, reports for a click at `from_centre` points from the well's
/// centre: the picture point and whether the view moved.
fn click(scale: f32, centres: bool, from_centre: Vec2) -> (Option<Pos2>, bool) {
let seen = Rc::new(Cell::new((None, false)));
let out = seen.clone();
let view = PreviewView::new(CanvasTransform::new(scale, Vec2::ZERO));
let mut fixture = Fixture::new(move |ui| {
let shown = PreviewPane::new("Preview", SizedTexture::new(TextureId::default(), PICTURE), &view).click_centres(centres).show(ui);
if shown.clicked.is_some() || shown.view.is_some() {
out.set((shown.clicked, shown.view.is_some()));
}
});
fixture.settle();
let well = fixture.by_label("Preview").expect("the pane").rect;
fixture.click_at(well.center() + from_centre).settle();
seen.get()
}
// A click reports the picture point under it, centring the view or not; a click beside the picture reports none.
#[trial]
fn a_click_reports_the_picture_point_under_it() {
let near = |a: Option<Pos2>, b: Pos2| a.is_some_and(|a| (a - b).length() < 0.5);
// At half size the picture sits in the middle of the well: a point 8 to the right is 16 picture pixels.
let (point, _) = click(0.5, true, vec2(8.0, -4.0));
assert!(near(point, pos2(PICTURE.x / 2.0 + 16.0, PICTURE.y / 2.0 - 8.0)), "{point:?}");
// The half-size picture's edge is 16 points right of the centre.
let (beside, _) = click(0.5, true, vec2(PICTURE.x / 4.0 + 4.0, 0.0));
assert_eq!(beside, None, "a click in the well beside the picture");
// Zoomed in, the picture overflows the well: a click centres the view unless the pane is told not to.
let (centred, moved) = click(8.0, true, vec2(16.0, 8.0));
assert!(near(centred, pos2(PICTURE.x / 2.0 + 2.0, PICTURE.y / 2.0 + 1.0)) && moved, "{centred:?} {moved}");
let (kept, moved) = click(8.0, false, vec2(16.0, 8.0));
assert!(near(kept, pos2(PICTURE.x / 2.0 + 2.0, PICTURE.y / 2.0 + 1.0)) && !moved, "{kept:?} {moved}");
}