object-dialogs-w2: net change of 1 commits

- object-dialogs-w2: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 21:27:46 +07:00
parent ab3994954e
commit 58c6ea737f
8 changed files with 376 additions and 153 deletions
+14 -9
View File
@@ -66,6 +66,11 @@ pub enum TipEllipseGrab {
Roundness,
}
/// The least roundness as a bound `clamp` accepts: a non-finite value falls back to the default.
fn least_bound(least: f64) -> f64 {
if least.is_finite() { least.clamp(0.0, 1.0) } else { ROUND_MIN }
}
/// The two roundness dots, relative to the widget's centre in points (screen y down), for an
/// ellipse of major radius `radius`: `±minor × radius × clamp(roundness, 0, 1)`, where the minor
/// axis is the major turned 90° counter-clockwise, `(−sin a, −cos a)`.
@@ -83,9 +88,9 @@ pub fn ellipse_grab(at: Vec2, angle: TipAngle, radius: f32, reach: f32) -> TipEl
/// The value after a drag to `at` (relative to the centre) holding `grab`. Angle: the direction
/// of `at` in whole degrees, counter-clockwise, `atan2(−y, x)` rounded; unchanged within 1 pt of
/// the centre. Roundness: `|at · minor| / radius` clamped to 0.01 to 1; the angle stays.
/// the centre. Roundness: `|at · minor| / radius` clamped to `least` (a non-finite `least` is 0.01) to 1; the angle
/// stays.
pub fn ellipse_drag(grab: TipEllipseGrab, at: Vec2, angle: TipAngle, radius: f32, least: f64) -> TipAngle {
let _ = least; // P3(object-dialogs-w2): od.OD8
if !(at.x.is_finite() && at.y.is_finite()) {
return angle;
}
@@ -95,7 +100,7 @@ pub fn ellipse_drag(grab: TipEllipseGrab, at: Vec2, angle: TipAngle, radius: f32
TipEllipseGrab::Roundness => {
let (sin, cos) = (angle.degrees as f32).to_radians().sin_cos();
let along = (at.x * -sin + at.y * -cos).abs();
TipAngle { roundness: f64::from(along / radius.max(f32::EPSILON)).clamp(ROUND_MIN, 1.0), ..angle }
TipAngle { roundness: f64::from(along / radius.max(f32::EPSILON)).clamp(least_bound(least), 1.0), ..angle }
}
}
}
@@ -166,8 +171,8 @@ fn major_radius(rect: Rect, style: &TipEllipseStyle) -> f32 {
}
/// The angle after a key: Up and Right turn it counter-clockwise (the widget is not mirrored), Shift by a large
/// turn; Alt changes the roundness instead.
fn key(value: TipAngle, mv: NavMove, mods: MoveMods, rtl: bool) -> Option<TipAngle> {
/// turn; Alt changes the roundness instead, down to `least`.
fn key(value: TipAngle, mv: NavMove, mods: MoveMods, rtl: bool, least: f64) -> Option<TipAngle> {
let raise = match mv {
NavMove::Up => true,
NavMove::Down => false,
@@ -177,7 +182,7 @@ fn key(value: TipAngle, mv: NavMove, mods: MoveMods, rtl: bool) -> Option<TipAng
};
let sign = if raise { 1.0 } else { -1.0 };
if mods.fine {
let roundness = (value.roundness + sign * ROUND_STEP).clamp(ROUND_MIN, 1.0);
let roundness = (value.roundness + sign * ROUND_STEP).clamp(least_bound(least), 1.0);
return Some(TipAngle { roundness: (roundness * 100.0).round() / 100.0, ..value });
}
let by = if mods.extend { COARSE_TURN } else { 1.0 };
@@ -266,7 +271,7 @@ impl Component for TipEllipse<'_> {
for (grab, press) in presses {
let current = cx.value().copied().unwrap_or_default();
let least = self.least_roundness;
let at = |pos: Pos2| ellipse_drag(grab, pos - center, current, radius, least); // P3(object-dialogs-w2): od.OD8
let at = |pos: Pos2| ellipse_drag(grab, pos - center, current, radius, least);
match press.phase {
PressPhase::DragStart { pos, .. } => {
cx.begin();
@@ -289,7 +294,7 @@ impl Component for TipEllipse<'_> {
let mut now = cx.value().copied().unwrap_or_default();
// While a drag runs, keys and screen-reader requests change nothing; they are still taken.
while let Some((mv, mods)) = cx.intents().take_move() {
if let Some(next) = key(now, mv, mods, rtl).filter(|_| !running) {
if let Some(next) = key(now, mv, mods, rtl, self.least_roundness).filter(|_| !running) {
cx.set(next);
now = next;
}
@@ -326,7 +331,7 @@ impl Component for TipEllipse<'_> {
draw.stroke(&PaintShape::Path(vec![center - vec2(0.0, disc), center + vec2(0.0, disc)]), StrokeWidth::Thin, cross);
let (sin, cos) = (value.degrees as f32).to_radians().sin_cos();
let (major, minor) = (vec2(cos, -sin), vec2(-sin, -cos));
let round = (value.roundness as f32).clamp(ROUND_MIN as f32, 1.0);
let round = (value.roundness as f32).clamp(least_bound(self.least_roundness) as f32, 1.0);
let ring: Vec<Pos2> = (0..SEGMENTS)
.map(|i| {
let t = i as f32 / SEGMENTS as f32 * std::f32::consts::TAU;
@@ -245,6 +245,14 @@ fn tip_ellipse(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
StoryOutput::from(shown).readout(note)
}
#[story(TipEllipse<'static>, covers = [], drive = Drive::Never)]
fn tip_ellipse_flat(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let flat = TipAngle::new(0.0, 0.0);
let shown = TipEllipse::new("Tip angle and roundness", Bind::bound(data.value("flat_tip", flat))).least_roundness(0.0).show(ui);
let note = angle_note(*data.value("flat_tip", flat));
StoryOutput::from(shown).readout(note)
}
#[story(TipEllipse<'static>, covers = [Mixed], drive = Drive::Never)]
fn tip_ellipse_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
TipEllipse::new("Tip angle and roundness", Bind::bound_mixed(data.value("mixed", Mixed::<TipAngle>::Mixed))).show(ui).into()
+225 -122
View File
@@ -2,16 +2,17 @@
//! what the fields mean at export is the app's.
use super::SliceWords;
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft_theme::Srgba;
use craft_ui::choice::Swatch;
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::Row;
use craft_ui::patterns::form_dialogs::{FormDialog, HostRequests};
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{Env, LengthUnits, UnitKind};
use craft_ui::runtime::env::{Env, Label, LengthUnits, UnitKind};
use craft_ui::runtime::requests::{ColorRequest, HostAnswer};
use craft_ui::text::{NumberField, TextField};
use egui::Ui;
@@ -74,6 +75,30 @@ pub enum SliceBackground {
Color(Srgba),
}
/// The opaque white and black the Background row names; a colour equal to one shows as that row.
const WHITE: Srgba = Srgba::rgb(1.0, 1.0, 1.0);
const BLACK: Srgba = Srgba::rgb(0.0, 0.0, 0.0);
impl SliceBackground {
/// The backgrounds the Background row names, by the id its `ColorChoice` stores.
const NAMED: [(&'static str, SliceBackground); 4] = [
("none", SliceBackground::None),
("matte", SliceBackground::Matte),
("white", SliceBackground::Color(WHITE)),
("black", SliceBackground::Color(BLACK)),
];
/// The row this background shows as: its named row, else the custom colour.
fn chosen(self) -> ChosenColor {
Self::NAMED.iter().find(|(_, listed)| *listed == self).map_or(ChosenColor::Custom, |(id, _)| ChosenColor::Named((*id).to_owned()))
}
/// The background the named row `id` stands for.
fn named(id: &str) -> Option<Self> {
Self::NAMED.iter().find(|(listed, _)| *listed == id).map(|(_, background)| *background)
}
}
/// A slice's options.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
@@ -92,8 +117,6 @@ pub struct SliceOptions {
pub alt: String,
/// No Image slices only.
pub cell_text: String,
/// Whether the Background row shows (PhotoCraft's; VectorCraft has none).
pub background_row: bool,
/// The cell background.
pub background: SliceBackground,
/// The alignment of a No Image or HTML Text cell; JSON `hAlign` takes `default`, `left`, `center` or `right`.
@@ -112,16 +135,58 @@ fn kind_name(kind: SliceKind) -> &'static str {
}
}
/// The colour a background starts with when None is switched to Colour.
const BACKGROUND_START: Srgba = Srgba::rgb(1.0, 1.0, 1.0);
/// The JSON names of the horizontal alignments.
const H_ALIGNS: [(SliceCellAlign, &str); 4] =
[(SliceCellAlign::Default, "default"), (SliceCellAlign::Left, "left"), (SliceCellAlign::Center, "center"), (SliceCellAlign::Right, "right")];
/// Slice Options for one slice: Slice Type (the [`kinds`](Self::kinds) offered), Name, URL, Target, Message Text, then
/// Alt Tag (Image) or Text (No Image, HTML Text), and the optional Background row (None or a colour, asked for with a
/// [`ColorRequest`]). OK answers the options; Cancel nothing. Enter is OK, Escape Cancel; the Name field has the focus
/// The JSON names of the vertical alignments.
const V_ALIGNS: [(SliceCellVAlign, &str); 5] = [
(SliceCellVAlign::Default, "default"),
(SliceCellVAlign::Top, "top"),
(SliceCellVAlign::Middle, "middle"),
(SliceCellVAlign::Baseline, "baseline"),
(SliceCellVAlign::Bottom, "bottom"),
];
/// The JSON name of `value` in `table`.
fn name_of<T: Copy + PartialEq>(table: &[(T, &'static str)], value: T) -> &'static str {
table.iter().find(|(listed, _)| *listed == value).map_or("default", |(_, name)| *name)
}
/// The value `table` names by the JSON string `value` of `field`.
fn pick<T: Copy>(table: &[(T, &'static str)], field: &str, value: &serde_json::Value) -> Result<T, String> {
let name = value.as_str().ok_or_else(|| format!("field `{field}` takes a string, got {value}"))?;
table.iter().find(|(_, listed)| *listed == name).map(|(listed, _)| *listed).ok_or_else(|| {
let names: Vec<&str> = table.iter().map(|(_, listed)| *listed).collect();
format!("field `{field}` takes one of {}, got `{name}`", names.join(", "))
})
}
/// A labelled text field.
fn text_row(ui: &mut Ui, label: &Label, value: &mut String) {
Field::new(label.clone()).show(ui, |ui, _| {
TextField::new(label.clone(), Bind::bound(value)).show(ui);
});
}
/// A labelled `Select` over `entries`.
fn select_row<T: Copy + Eq + std::hash::Hash + std::fmt::Debug + 'static>(ui: &mut Ui, label: &Label, value: &mut T, entries: &[Entry<T>]) {
Field::new(label.clone()).show(ui, |ui, _| {
if let Some(picked) = Select::new(label.clone(), Bind::given(*value), entries).show(ui).value().copied() {
*value = picked;
}
});
}
/// Slice Options for one slice: Slice Type (the [`kinds`](Self::kinds) offered), then by type: Name, URL, Target,
/// Message Text and Alt Tag for an image; the cell's Text for No Image, a note for HTML Text, and for both the
/// Horizontal and Vertical alignment; then Background (None, Matte, White, Black or a custom colour, asked for with a
/// [`ColorRequest`]). OK answers the options; Cancel nothing. Enter is OK, Escape Cancel; the first field has the focus
/// when the dialog opens.
///
/// The Background swatch asks for a colour: the app takes [`pick_color`](Self::pick_color) after each pass, opens its
/// picker and answers with [`set_color`](Self::set_color).
/// The custom colour asks for a colour: the dialog host takes
/// [`take_color_request`](StackDialog::take_color_request) after each pass, opens its picker and answers with
/// [`answer_color`](StackDialog::answer_color).
#[derive(craft_ui::contract::Pattern)]
pub struct SliceOptionsDialog {
id: DialogId,
@@ -131,9 +196,6 @@ pub struct SliceOptionsDialog {
}
impl SliceOptionsDialog {
/// The key of the [`ColorRequest`] the Background row reports.
pub const BACKGROUND_KEY: &'static str = "slice.options.background";
/// The dialog for `options`, offering Image and No Image (PhotoCraft's choices).
pub fn new(options: SliceOptions) -> Self {
SliceOptionsDialog {
@@ -155,19 +217,6 @@ impl SliceOptionsDialog {
pub fn options(&self) -> &SliceOptions {
&self.options
}
/// The Background swatch was clicked in the pass since the last call: the request for the app's picker, keyed
/// [`BACKGROUND_KEY`](Self::BACKGROUND_KEY). Returned once.
pub fn pick_color(&mut self) -> Option<ColorRequest> {
self.requests.take_color()
}
/// The colour the app's picker returned for `key`; other keys are ignored.
pub fn set_color(&mut self, key: &str, color: Srgba) {
if key == Self::BACKGROUND_KEY {
self.requests.answer_color(key, color);
}
}
}
impl StackDialog for SliceOptionsDialog {
@@ -175,7 +224,12 @@ impl StackDialog for SliceOptionsDialog {
fn json_fields(&self) -> Option<serde_json::Value> {
let options = &self.options;
let mut fields = serde_json::json!({
let background = match options.background {
SliceBackground::None => serde_json::Value::Null,
SliceBackground::Matte => serde_json::json!("matte"),
SliceBackground::Color(color) => serde_json::Value::String(Srgba::rgb(color.r, color.g, color.b).to_hex()),
};
Some(serde_json::json!({
"kind": kind_name(options.kind),
"name": options.name,
"url": options.url,
@@ -183,18 +237,10 @@ impl StackDialog for SliceOptionsDialog {
"message": options.message,
"alt": options.alt,
"cellText": options.cell_text,
});
if options.background_row
&& let Some(map) = fields.as_object_mut()
{
// P3(object-dialogs-w2): od.OD10
let background = match options.background {
SliceBackground::Color(color) => serde_json::Value::String(Srgba::rgb(color.r, color.g, color.b).to_hex()),
SliceBackground::None | SliceBackground::Matte => serde_json::Value::Null,
};
map.insert("background".into(), background);
}
Some(fields)
"background": background,
"hAlign": name_of(&H_ALIGNS, options.h_align),
"vAlign": name_of(&V_ALIGNS, options.v_align),
}))
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
@@ -217,23 +263,23 @@ impl StackDialog for SliceOptionsDialog {
"message" => self.options.message = text(&value)?,
"alt" => self.options.alt = text(&value)?,
"cellText" => self.options.cell_text = text(&value)?,
"hAlign" => self.options.h_align = pick(&H_ALIGNS, field, &value)?,
"vAlign" => self.options.v_align = pick(&V_ALIGNS, field, &value)?,
"background" => {
if !self.options.background_row {
return Err("field `background` is not shown: the dialog has no Background row".into());
}
// P3(object-dialogs-w2): od.OD10
self.options.background = match &value {
serde_json::Value::Null => SliceBackground::None,
serde_json::Value::String(name) if name == "matte" => SliceBackground::Matte,
serde_json::Value::String(hex) => {
let digits = hex.strip_prefix('#').unwrap_or(hex);
if digits.len() != 6 {
return Err(format!("field `background` takes six hex digits or null, got `{hex}`"));
return Err(format!("field `background` takes six hex digits, \"matte\" or null, got `{hex}`"));
}
SliceBackground::Color(
Srgba::from_hex(digits).ok_or_else(|| format!("field `background` takes six hex digits or null, got `{hex}`"))?,
Srgba::from_hex(digits)
.ok_or_else(|| format!("field `background` takes six hex digits, \"matte\" or null, got `{hex}`"))?,
)
}
other => return Err(format!("field `background` takes six hex digits or null, got {other}")),
other => return Err(format!("field `background` takes six hex digits, \"matte\" or null, got {other}")),
};
}
_ => return Err(format!("unknown field `{field}`")),
@@ -246,6 +292,16 @@ impl StackDialog for SliceOptionsDialog {
self.id
}
fn take_color_request(&mut self) -> Option<ColorRequest> {
self.requests.take_color()
}
fn answer_color(&mut self, key: &str, color: Srgba) {
if key == ColorChoice::CUSTOM_KEY {
self.requests.answer_color(key, color);
}
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<SliceOptions>> {
let words = Env::of(ui).words::<SliceWords>();
let kind_label = |kind: SliceKind| match kind {
@@ -254,14 +310,33 @@ impl StackDialog for SliceOptionsDialog {
_ => words.html_text.clone(),
};
let kinds: Vec<Entry<SliceKind>> = self.kinds.iter().map(|&kind| Entry::new(kind, kind_label(kind))).collect();
let backgrounds = [Entry::new(false, words.background_none.clone()), Entry::new(true, words.background_color_choice.clone())];
let h_aligns: Vec<Entry<SliceCellAlign>> = [
(SliceCellAlign::Default, &words.align_default),
(SliceCellAlign::Left, &words.align_left),
(SliceCellAlign::Center, &words.align_center),
(SliceCellAlign::Right, &words.align_right),
]
.into_iter()
.map(|(value, label)| Entry::new(value, label.clone()))
.collect();
let v_aligns: Vec<Entry<SliceCellVAlign>> = [
(SliceCellVAlign::Default, &words.valign_default),
(SliceCellVAlign::Top, &words.valign_top),
(SliceCellVAlign::Middle, &words.valign_middle),
(SliceCellVAlign::Baseline, &words.valign_baseline),
(SliceCellVAlign::Bottom, &words.valign_bottom),
]
.into_iter()
.map(|(value, label)| Entry::new(value, label.clone()))
.collect();
let background_labels = [&words.background_none, &words.background_matte, &words.background_white, &words.background_black];
let answers = self.requests.take_answers();
let shown = FormDialog::new(words.options_title.clone(), Bind::bound(&mut self.options)).answers(answers).show(ui, |ui, form, options| {
for answer in form.take_answers() {
if let HostAnswer::Color { key, color, .. } = answer
&& key == Self::BACKGROUND_KEY
&& key == ColorChoice::CUSTOM_KEY
{
options.background = SliceBackground::Color(color); // P3(object-dialogs-w2): od.OD10
options.background = SliceBackground::Color(color);
}
}
FieldGroup::new(words.options_title.clone()).show(ui, |ui, _| {
@@ -270,42 +345,50 @@ impl StackDialog for SliceOptionsDialog {
options.kind = kind;
}
});
Field::new(words.name.clone()).show(ui, |ui, _| TextField::new(words.name.clone(), Bind::bound(&mut options.name)).show(ui));
for (label, value) in [(&words.url, &mut options.url), (&words.target, &mut options.target), (&words.message, &mut options.message)] {
Field::new(label.clone()).show(ui, |ui, _| {
TextField::new(label.clone(), Bind::bound(value)).show(ui);
});
}
let (label, value) =
if options.kind == SliceKind::Image { (&words.alt, &mut options.alt) } else { (&words.cell_text, &mut options.cell_text) };
Field::new(label.clone()).show(ui, |ui, _| {
TextField::new(label.clone(), Bind::bound(value)).show(ui);
});
if options.background_row {
Field::new(words.background.clone()).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
// P3(object-dialogs-w2): od.OD10
let colour = matches!(options.background, SliceBackground::Color(_));
if let Some(on) = Select::new(words.background_kind.clone(), Bind::given(colour), &backgrounds).show(ui).value().copied()
{
options.background = if on {
SliceBackground::Color(match options.background {
SliceBackground::Color(color) => color,
_ => BACKGROUND_START,
})
} else {
SliceBackground::None
};
}
if let SliceBackground::Color(color) = options.background
&& let Some(request) =
Swatch::new(words.background_color.clone(), color).picker(Self::BACKGROUND_KEY).show(ui).pick_color
{
form.requests().request_color(request);
}
if options.kind == SliceKind::Image {
for (label, value) in [
(&words.name, &mut options.name),
(&words.url, &mut options.url),
(&words.target, &mut options.target),
(&words.message, &mut options.message),
(&words.alt, &mut options.alt),
] {
text_row(ui, label, value);
}
} else {
if options.kind == SliceKind::NoImage {
Field::new(words.cell_text.clone()).show(ui, |ui, _| {
TextField::new(words.cell_text.clone(), Bind::bound(&mut options.cell_text)).lines(4).show(ui);
});
});
} else {
Text::new(words.html_note.clone()).shade(Shade::Muted).show(ui);
}
select_row(ui, &words.h_align, &mut options.h_align, &h_aligns);
select_row(ui, &words.v_align, &mut options.v_align, &v_aligns);
}
let chosen = options.background.chosen();
let custom = match options.background {
SliceBackground::Color(color) if chosen == ChosenColor::Custom => Some(color),
_ => None,
};
let named = SliceBackground::NAMED.iter().zip(background_labels).map(|((id, background), label)| {
let swatch = match background {
SliceBackground::Color(color) => Some(*color),
_ => None,
};
NamedColor::new(*id, label.clone(), swatch)
});
Field::new(words.background.clone()).show(ui, |ui, _| {
let picked = ColorChoice::new(words.background.clone(), &chosen).named(named).custom(custom).show(ui);
if let Some(ChosenColor::Named(id)) = &picked.chosen
&& let Some(background) = SliceBackground::named(id)
{
options.background = background;
}
if let Some(request) = picked.pick_color {
form.requests().request_color(request);
}
});
});
true
});
@@ -363,36 +446,39 @@ impl Default for DivideSlices {
}
}
/// One axis of the dialog: its check box, whether the value is a size, and the value. An axis that is off keeps its
/// value for when it is switched on.
/// One axis of the dialog: its check box, whether the value is a size, and a count and a size. Both values are kept, so
/// a switch between Count and Size, or an axis switched off, loses neither.
#[derive(Clone, Copy, Debug, PartialEq)]
struct AxisState {
on: bool,
by_size: bool,
value: u32,
count: u32,
size: f64,
}
impl AxisState {
/// The most slices one axis divides into (PhotoCraft's clamp).
const MAX_COUNT: u32 = 1000;
/// The largest slice size in pixels.
const MAX_SIZE: u32 = 300_000;
/// The largest slice size, in the dialog's stored unit.
const MAX_SIZE: f64 = 300_000.0;
/// The axis for `divide`; the value `divide` does not give starts at `off_value`.
fn of(divide: Option<DivideBy>, off_value: u32) -> Self {
let off_size = f64::from(off_value);
match divide {
Some(DivideBy::Count(n)) => AxisState { on: true, by_size: false, value: n.clamp(1, Self::MAX_COUNT) },
// P3(object-dialogs-w2): od.OD12
Some(DivideBy::Size(n)) => AxisState { on: true, by_size: true, value: n.round().clamp(1.0, f64::from(Self::MAX_SIZE)) as u32 },
None => AxisState { on: false, by_size: false, value: off_value },
Some(DivideBy::Count(n)) => AxisState { on: true, by_size: false, count: n.clamp(1, Self::MAX_COUNT), size: off_size },
Some(DivideBy::Size(size)) => AxisState { on: true, by_size: true, count: off_value, size: Self::size_of(size, off_size) },
None => AxisState { on: false, by_size: false, count: off_value, size: off_size },
}
}
fn answer(self) -> Option<DivideBy> {
self.on.then_some(if self.by_size { DivideBy::Size(f64::from(self.value)) } else { DivideBy::Count(self.value) })
/// `size` within the size range; `fallback` when it is not a number.
fn size_of(size: f64, fallback: f64) -> f64 {
if size.is_finite() { size.clamp(1.0, Self::MAX_SIZE) } else { fallback }
}
fn max(self) -> u32 {
if self.by_size { Self::MAX_SIZE } else { Self::MAX_COUNT }
fn answer(self) -> Option<DivideBy> {
self.on.then_some(if self.by_size { DivideBy::Size(self.size) } else { DivideBy::Count(self.count) })
}
}
@@ -422,37 +508,43 @@ impl Axes {
}
/// Divide Slice: "Divide Horizontally Into" and "Divide Vertically Into", each a check box with a choice of a count
/// ("slices, evenly spaced") or a size ("pixels per slice"), counts and sizes at least 1. OK answers
/// [`DivideSlices`] and is off while neither axis is on; Cancel answers nothing. Enter is OK, Escape Cancel.
/// ("slices, evenly spaced") or a size ("per slice", a length in the [`lengths`](Self::lengths) units), counts and
/// sizes at least 1. OK answers [`DivideSlices`] and is off while neither axis is on; Cancel answers nothing. Enter
/// is OK, Escape Cancel.
#[derive(craft_ui::contract::Pattern)]
pub struct DivideSlicesDialog {
id: DialogId,
axes: Axes,
lengths: LengthUnits,
}
impl DivideSlicesDialog {
/// The dialog starting from `divide`.
pub fn new(divide: DivideSlices) -> Self {
DivideSlicesDialog { id: dialog_id("slice.divide"), axes: Axes::of(divide) }
DivideSlicesDialog { id: dialog_id("slice.divide"), axes: Axes::of(divide), lengths: LengthUnits::new(UnitKind::Pixels, UnitKind::Pixels, 72.0) }
}
/// The units the size field keeps and shows its length in; pixels in both, at 72 per inch, by default.
#[must_use]
pub fn lengths(self, lengths: LengthUnits) -> Self {
let _ = lengths;
todo!("od.OD12")
pub fn lengths(mut self, lengths: LengthUnits) -> Self {
self.lengths = lengths;
self
}
/// The size an axis that opened on a count switches to, for rows and columns.
/// The size an axis that opened on a count switches to, for rows and columns, in the stored unit.
#[must_use]
pub fn start_sizes(self, rows: f64, columns: f64) -> Self {
let _ = (rows, columns);
todo!("od.OD12")
pub fn start_sizes(mut self, rows: f64, columns: f64) -> Self {
for (axis, size) in [(&mut self.axes.rows, rows), (&mut self.axes.columns, columns)] {
if !axis.by_size {
axis.size = AxisState::size_of(size, axis.size);
}
}
self
}
}
/// One axis: its check box, then (while it is on) what the value counts and the value.
fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &craft_ui::runtime::env::Label, words: &SliceWords) {
fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &Label, words: &SliceWords, lengths: LengthUnits) {
Field::new(caption.clone()).show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut axis.on)).label(caption.clone()).show(ui);
});
@@ -466,15 +558,18 @@ fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &craft_ui::runtime::env
});
});
Field::new(unit).enabled(axis.on).show(ui, |ui, _| {
let max = axis.max();
let field =
NumberField::new(words.divide_value.clone(), Bind::given(Some(f64::from(axis.value)))).range(1.0..=f64::from(max)).commit_decimals(0);
// A count has no unit; a size counts pixels.
let field = if axis.by_size { field.unit_kind(UnitKind::Pixels) } else { field }.show(ui);
if let Some(Some(value)) = field.value().copied() {
axis.value = value.round().clamp(1.0, f64::from(max)) as u32;
if axis.by_size {
let field = NumberField::length(words.divide_value.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
if let Some(Some(size)) = field.value().copied() {
axis.size = AxisState::size_of(size, axis.size);
}
} else {
let max = f64::from(AxisState::MAX_COUNT);
let field = NumberField::new(words.divide_value.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
if let Some(Some(count)) = field.value().copied() {
axis.count = count.round().clamp(1.0, max) as u32;
}
}
axis.value = axis.value.min(max);
});
}
@@ -483,7 +578,11 @@ impl StackDialog for DivideSlicesDialog {
fn json_fields(&self) -> Option<serde_json::Value> {
let Axes { rows, columns } = self.axes;
let axis = |axis: AxisState| if axis.on { serde_json::json!(axis.value) } else { serde_json::Value::Null };
let axis = |axis: AxisState| match (axis.on, axis.by_size) {
(false, _) => serde_json::Value::Null,
(true, true) => serde_json::json!(axis.size),
(true, false) => serde_json::json!(axis.count),
};
let by = |axis: AxisState| if axis.by_size { "size" } else { "count" };
Some(serde_json::json!({ "rows": axis(rows), "rowsBy": by(rows), "columns": axis(columns), "columnsBy": by(columns) }))
}
@@ -500,12 +599,15 @@ impl StackDialog for DivideSlicesDialog {
Some("size") => true,
_ => return Err(format!("field `{field}` takes \"count\" or \"size\", got {value}")),
};
axis.value = axis.value.min(axis.max());
} else if value.is_null() {
axis.on = false;
} else {
let number = value.as_f64().ok_or_else(|| format!("field `{what}` takes a number or null, got {value}"))?;
axis.value = number.round().clamp(1.0, f64::from(axis.max())) as u32;
let number = value.as_f64().filter(|number| number.is_finite()).ok_or_else(|| format!("field `{what}` takes a number or null, got {value}"))?;
if axis.by_size {
axis.size = AxisState::size_of(number, axis.size);
} else {
axis.count = number.round().clamp(1.0, f64::from(AxisState::MAX_COUNT)) as u32;
}
axis.on = true;
}
ctx.request_repaint();
@@ -518,10 +620,11 @@ impl StackDialog for DivideSlicesDialog {
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<DivideSlices>> {
let words = Env::of(ui).words::<SliceWords>();
let lengths = self.lengths;
let shown = FormDialog::new(words.divide_title.clone(), Bind::bound(&mut self.axes)).show(ui, |ui, _, axes| {
FieldGroup::new(words.divide_title.clone()).show(ui, |ui, _| {
axis_rows(ui, &mut axes.rows, &words.horizontally, &words);
axis_rows(ui, &mut axes.columns, &words.vertically, &words);
axis_rows(ui, &mut axes.rows, &words.horizontally, &words, lengths);
axis_rows(ui, &mut axes.columns, &words.vertically, &words, lengths);
});
axes.answer().is_some()
});
+68 -2
View File
@@ -2,15 +2,18 @@
//! each mode.
use super::{
SliceBar, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRules, SliceTool, SliceToolSettings, SliceToolWords,
DivideBy, DivideSlices, DivideSlicesDialog, SliceBackground, SliceBar, SliceCellAlign, SliceCellVAlign, SliceCommand, SliceEvent, SliceItem,
SliceKind, SliceMode, SliceOptions, SliceOptionsDialog, SliceOrigin, SliceOverlay, SliceRules, SliceTool, SliceToolSettings, SliceToolWords,
};
use craft_behavior::geometry::Constraint;
use craft_behavior::kurbo::Rect;
use craft_behavior::{CanvasView, EditEvent, PixelSize};
use craft_ui::bars::{Bar, BarKind};
use craft_ui::buttons::Button;
use craft_ui::dialog::{DialogStack, StackDialog};
use craft_ui::canvas::{Canvas, RasterSource as _};
use craft_ui::contract::{Entry, Show as _, ShowContainer as _};
use craft_ui::runtime::env::{Env, UnitKind};
use craft_ui::runtime::env::{Env, LengthUnits, UnitKind};
use craft_ui::testing::canvas_story::StoryDocument;
use craft_ui::testing::{Drive, EditKind, StoryButton, StoryData, StoryHost, StoryOutput, ToolStory, story, tool_story};
use egui::Ui;
@@ -105,6 +108,69 @@ fn slice_bar_locked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
bar(ui, data, SliceMode::Select, Constraint::Free, true)
}
/// A story button that opens the dialog `make` builds; the dialog is kept until it answers or is cancelled, so its
/// fields keep what was typed while it shows.
fn dialog_story<D: StackDialog + 'static>(ui: &mut Ui, data: &mut StoryData, opener: &'static str, make: impl FnOnce() -> D) -> StoryOutput {
let open = data.note::<Option<D>>("dialog", None);
if Button::new(opener).show(ui).response.clicked() {
*open = Some(make());
}
if let Some(dialog) = open.as_mut() {
let mut stack = DialogStack::default();
stack.push(dialog.id(), None);
let closed = dialog.show(ui, &stack).is_some();
if closed {
*open = None;
}
}
StoryOutput::default()
}
/// Slice Options over `options` and the slice types `kinds`.
fn options_story(ui: &mut Ui, data: &mut StoryData, options: SliceOptions, kinds: &[SliceKind]) -> StoryOutput {
dialog_story(ui, data, "Slice Options…", || SliceOptionsDialog::new(options).kinds(kinds))
}
#[story(SliceOptionsDialog, covers = [Default], drive = Drive::Never)]
fn slice_options_image(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = SliceOptions { name: "hero".into(), url: "https://example.com".into(), alt: "A hero image".into(), ..SliceOptions::default() };
options_story(ui, data, options, &[SliceKind::Image, SliceKind::NoImage])
}
#[story(SliceOptionsDialog, covers = [], drive = Drive::Never)]
fn slice_options_no_image(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = SliceOptions {
kind: SliceKind::NoImage,
cell_text: "Sale ends Friday".into(),
h_align: SliceCellAlign::Center,
v_align: SliceCellVAlign::Middle,
background: SliceBackground::Matte,
..SliceOptions::default()
};
options_story(ui, data, options, &[SliceKind::Image, SliceKind::NoImage])
}
#[story(SliceOptionsDialog, covers = [], drive = Drive::Never)]
fn slice_options_html_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() };
options_story(ui, data, options, &[SliceKind::Image, SliceKind::NoImage, SliceKind::HtmlText])
}
#[story(DivideSlicesDialog, covers = [Default], drive = Drive::Never)]
fn divide_slices(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog_story(ui, data, "Divide…", || DivideSlicesDialog::new(DivideSlices::default()))
}
/// Sizes kept in points and shown in millimetres.
#[story(DivideSlicesDialog, covers = [], drive = Drive::Never)]
fn divide_slices_by_length(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog_story(ui, data, "Divide…", || {
DivideSlicesDialog::new(DivideSlices::new(Some(DivideBy::Size(72.0)), Some(DivideBy::Count(3))))
.lengths(LengthUnits::new(UnitKind::Points, UnitKind::Millimetres, 72.0))
.start_sizes(72.0, 144.0)
})
}
/// The slices of the live story's document: a demo layout of user, auto and layer slices on the story document.
fn sample_slices() -> Vec<SliceItem> {
let page = StoryDocument::STANDARD.size();
+1 -2
View File
@@ -49,8 +49,7 @@ craft_ui::words! {
background: "slice.background" = "Background";
background_none: "slice.backgroundNone" = "None";
background_color: "slice.backgroundColor" = "Slice Background Color";
background_kind: "slice.backgroundKind" = "Background Type";
background_color_choice: "slice.backgroundColorChoice" = "Color";
h_align: "slice.hAlign" = "Horizontal";
v_align: "slice.vAlign" = "Vertical";
align_default: "slice.alignDefault" = "Default";
+1 -1
View File
@@ -33,7 +33,6 @@ mod artboard;
// draw-bars
mod measure;
mod slice;
mod slice_divide;
// draw-stroke
mod stroke_button;
@@ -43,6 +42,7 @@ mod stroke_editor;
mod brush_presets;
mod brush_size;
mod paint_bar;
mod tip_ellipse;
// draw-transform-a
mod transform_box;
-17
View File
@@ -1,17 +0,0 @@
//! The Divide Slices dialog's value field: a size shows its pixel unit, a count none.
use craft_draw::ui::slice::{DivideBy, DivideSlices, DivideSlicesDialog};
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Fixture, trial};
#[trial]
fn a_count_shows_no_unit_and_a_size_shows_pixels() {
// P3(object-dialogs-w2): od.OD12
let mut dialog = DivideSlicesDialog::new(DivideSlices::new(Some(DivideBy::Count(4)), Some(DivideBy::Size(64.0))));
let mut fixture = Fixture::new(move |ui| {
let _ = dialog.show(ui, &DialogStack::default());
});
fixture.idle(4);
let units = fixture.texts().iter().filter(|run| run.text == "px").count();
assert_eq!(units, 1, "only the size field shows a unit");
}
+59
View File
@@ -0,0 +1,59 @@
//! The tip ellipse's least roundness: a dot drag and Alt+arrow steps stop at it.
use craft_draw::ui::brush_settings::{TipAngle, TipEllipse};
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
/// A fixture over a tip of roundness `start`, with the least roundness `least` or the widget's default.
fn shown(start: f64, least: Option<f64>) -> (Fixture, Rc<RefCell<TipAngle>>) {
let angle = Rc::new(RefCell::new(TipAngle::new(0.0, start)));
let value = Rc::clone(&angle);
let mut fixture = Fixture::new(move |ui| {
let mut angle = value.borrow_mut();
let widget = TipEllipse::new("Tip angle and roundness", Bind::bound(&mut *angle));
let _ = match least {
Some(least) => widget.least_roundness(least),
None => widget,
}
.show(ui);
});
fixture.room(Vec2::new(200.0, 200.0)).settle();
(fixture, angle)
}
/// The roundness after a drag of the lower dot (on the short axis of a horizontal tip) to the widget's centre.
fn dragged_to_centre(least: Option<f64>) -> f64 {
let (mut fixture, angle) = shown(0.5, least);
let rect = fixture.by_role(Role::SLIDER).first().copied().expect("the tip widget shows").rect;
let quarter = rect.height() / 4.0;
fixture.drag_at(rect.center() + Vec2::new(0.0, quarter), Vec2::new(0.0, -quarter));
let roundness = angle.borrow().roundness;
roundness
}
/// The roundness after Alt+Down pressed far more often than the start needs to reach any least.
fn stepped_down(least: Option<f64>) -> f64 {
let (mut fixture, angle) = shown(0.04, least);
fixture.key(Key::Tab, Modifiers::NONE);
for _ in 0..12 {
fixture.key(Key::ArrowDown, Modifiers::ALT);
}
let roundness = angle.borrow().roundness;
roundness
}
#[trial]
fn a_dot_drag_and_alt_keys_stop_at_the_least_roundness() {
let (flat_drag, default_drag) = (dragged_to_centre(Some(0.0)), dragged_to_centre(None));
assert!(flat_drag.abs() < 1e-3, "a flat tip's dot reaches the centre, got {flat_drag}");
assert!(default_drag > 0.0, "the default least keeps the dot off the centre, got {default_drag}");
assert!(flat_drag < default_drag, "the flat tip goes below the default least");
let (flat_keys, default_keys) = (stepped_down(Some(0.0)), stepped_down(None));
assert_eq!(flat_keys, 0.0, "Alt+Down reaches a roundness of 0 on a flat tip");
assert!(default_keys > 0.0, "Alt+Down stops above 0 with the default least, got {default_keys}");
assert!(flat_keys < default_keys, "the flat tip's keys go below the default least");
}