Merge branch 'fw/dlg-a' into fw/mac1

This commit is contained in:
aiongg
2026-11-16 16:47:54 +00:00
24 changed files with 362 additions and 158 deletions
+1
View File
@@ -454,6 +454,7 @@ impl StackDialog for ColorPickerDialog {
let shown = Dialog::new(title.clone())
.opened(Bind::bound(open))
.buttons(buttons)
.side_buttons(true)
.close_on_enter(true)
.initial_focus(Initial::Keep)
.roomy(true)
+1 -1
View File
@@ -410,7 +410,7 @@ fn body(
typed: &mut Option<RangeAlert>,
) -> bool {
let document = values.units.unwrap_or_else(pixels_only);
let entries: Vec<Entry<UnitKind>> = length_units(values).map(|kind| Entry::new(kind, Label::from(numbers.symbol(kind)))).collect();
let entries: Vec<Entry<UnitKind>> = length_units(values).map(|kind| Entry::new(kind, numbers.name(kind))).collect();
let kind = values.kind;
FieldGroup::new(title_of(kind, words)).show(ui, |ui, _| {
let (width, height) = (Label::from(words.width.as_str().to_owned()), Label::from(words.height.as_str().to_owned()));
+24 -23
View File
@@ -1,5 +1,5 @@
//! [`CurvesPanel`]: the Curves adjustment around the [`CurveEditor`]: the Channel select, the mode
//! icons (points, pencil), Smooth, the point pickers, the other channels overlaid on the composite
//! [`CurvesPanel`]: the Curves adjustment around the [`CurveEditor`]: the point pickers, the Channel
//! select, the mode icons (points, pencil), Smooth, the other channels overlaid on the composite
//! and the hint line; and the ⌘/Ctrl-click-on-the-image helper
//! ([`CurvesPanel::add_point_from_sample`]).
@@ -139,15 +139,15 @@ type SamplerFn<'a> = Box<dyn Fn(&[[f32; 2]]) -> Vec<f32> + 'a>;
/// The Curves adjustment: Image › Adjustments › Curves and a Curves layer's Properties panel.
///
/// Top to bottom:
/// 1. The Channel select ([`ToneChannels`]); an isolated channel is the only entry, its name shown exactly as the
/// Top to bottom (PhotoCraft's order):
/// 1. With [`pickers`](Self::pickers), the point picker row.
/// 2. The Channel select ([`ToneChannels`]); an isolated channel is the only entry, its name shown exactly as the
/// host gave it.
/// 2. The mode row: two icon-only toggle buttons ("Edit points to modify the curve", "Draw to modify the curve", the
/// 3. The mode row: two icon-only toggle buttons ("Edit points to modify the curve", "Draw to modify the curve", the
/// current one pressed) and Smooth (enabled in pencil mode only).
/// 3. The [`CurveEditor`] for the shown channel: in its colour, over its histogram, in pencil mode for a drawn curve,
/// 4. The [`CurveEditor`] for the shown channel: in its colour, over its histogram, in pencil mode for a drawn curve,
/// and, on a composite only, the other channels' curves as overlays (Photoshop; none for an isolated channel).
/// 4. The hint line, with the key names from the platform's shortcut words.
/// 5. With [`pickers`](Self::pickers), the point picker row.
/// 5. The hint line, with the key names from the platform's shortcut words.
///
/// - **Smooth** replaces the shown map with its moving average over 7 levels (radius 3, shrunk at the ends so the
/// first and last levels keep their values: PhotoCraft's `smooth_curve_map`), as one `Set`.
@@ -168,7 +168,7 @@ pub struct CurvesPanel<'a> {
/// The host's interpolation of point curves ([`CurveEditor::sampler`]).
#[prop(boxed = "Fn(&[[f32; 2]]) -> Vec<f32> + 'a")]
sampler: Option<SamplerFn<'a>>,
/// The armed point picker; the picker row shows when it is given.
/// The armed point picker; the picker row shows, first, when it is given.
#[prop]
pickers: Option<Bind<'a, Option<TonePicker>>>,
/// The document canvas the ⌘/Ctrl-click and the eyedroppers reach under the dialog.
@@ -313,6 +313,21 @@ impl<'a> CurvesPanel<'a> {
// Alt+2…Alt+6 pick the Channel select's entry in a dialog; Properties has no such keys.
let stack = if context.is_dialog() { stack.command_scope(ToneChannelCommands::SCOPE) } else { stack };
let group = stack.show(ui, |ui, cx| {
if let Some(armed) = pickers.as_mut() {
let mut row = TonePickerRow::new(armed.reborrowed());
if pickers_unavailable {
row = row.unavailable();
}
if let Some(canvas) = canvas {
row = row.canvas(canvas);
}
for each in TonePicker::ALL {
let usable = picker_enabled[each as usize] && !(each == TonePicker::Gray && (channels.is_gray() || context.is_gray()));
row = row.enabled_picker(each, usable);
}
picker = row.show(ui).change;
}
let value = match curves.reborrow().read(cx) {
Some(Mixed::Same(value)) => value,
_ => ToneCurves::identity(&channels),
@@ -406,20 +421,6 @@ impl<'a> CurvesPanel<'a> {
}
edit = events;
if let Some(armed) = pickers.as_mut() {
let mut row = TonePickerRow::new(armed.reborrowed());
if pickers_unavailable {
row = row.unavailable();
}
if let Some(canvas) = canvas {
row = row.canvas(canvas);
}
for each in TonePicker::ALL {
let usable = picker_enabled[each as usize] && !(each == TonePicker::Gray && (channels.is_gray() || context.is_gray()));
row = row.enabled_picker(each, usable);
}
picker = row.show(ui).change;
}
// An edit belongs to the channel it was drawn for; a switch shows from the next pass, with no selection.
shown_channel = if picked == channel || !edit.is_empty() { channel } else { picked };
write_shown(&mut channel_bind, cx, stored, shown_channel);
+2 -2
View File
@@ -87,8 +87,8 @@ type Editor<V, E> = dyn for<'b> Fn(&mut Ui, &mut V, &mut AdjustDialogCx<'b>) ->
type JsonForm<V> = dyn Fn(&V, bool) -> serde_json::Map<String, serde_json::Value> + Send;
/// An Image › Adjustments dialog the [`DialogHost`](craft_ui::dialog::DialogHost) owns: an adjustment editor over a
/// value `V` the host keeps, in a form dialog with OK and Cancel beside the editor (Alt turns Cancel into Reset, which
/// restores the value the dialog opened with) and the Preview box under them. The editor runs in its dialog form
/// value `V` the host keeps, in a form dialog with the Preview box at the start of the footer and OK and Cancel at its
/// end (Alt turns Cancel into Reset, which restores the value the dialog opened with). The editor runs in its dialog form
/// ([`AdjustContext::dialog`]). What the editor asks of the app (Levels' Auto, Black & White's Auto) is an `E` that
/// waits in [`take_asks`](Self::take_asks). It answers with the value at OK.
///
+24 -24
View File
@@ -1,5 +1,5 @@
//! [`LevelsPanel`]: the Levels adjustment around the [`LevelsEditor`]: the Channel select, Auto,
//! the editor over the shown channel's histogram and the point pickers.
//! [`LevelsPanel`]: the Levels adjustment around the [`LevelsEditor`]: the point pickers, the
//! Channel select, Auto and the editor over the shown channel's histogram.
#[cfg(feature = "screen-testing")]
mod stories;
@@ -78,20 +78,19 @@ impl Outcome for LevelsPanelOutput {
/// The Levels adjustment: Image › Adjustments › Levels and a Levels layer's Properties panel
/// (the same call with [`AdjustContext::properties`]).
///
/// Top to bottom (PhotoCraft's and Photoshop's order):
/// 1. The Channel select ([`ToneChannels`]; an isolated channel is the only entry, named as given)
/// Top to bottom (PhotoCraft's order):
/// 1. With [`pickers`](Self::pickers), the [`TonePickerRow`]: Set Black, Neutral Gray, White Point.
/// 2. The Channel select ([`ToneChannels`]; an isolated channel is the only entry, named as given)
/// and Auto. Picking a channel shows that channel's levels and histogram; the choice is the
/// panel's own state, reported as [`LevelsPanelOutput::channel`].
/// 2. The [`LevelsEditor`] for the shown channel, over its histogram drawn in the channel's colour;
/// 3. The [`LevelsEditor`] for the shown channel, over its histogram drawn in the channel's colour;
/// a [`stale`](Self::stale) histogram shows the stale mark.
/// 3. With [`pickers`](Self::pickers), the [`TonePickerRow`] below: Set Black, Neutral Gray, White
/// Point.
///
/// - **Auto** sets the shown channel to [`Levels::auto`] of its histogram as one `Set`; without a
/// histogram it is disabled.
/// - **Edits**: the editor's events pass through for the shown channel, mapped onto the per-channel
/// values.
/// - **Keyboard**: Tab visits the Channel select, Auto, the editor, then the pickers.
/// - **Keyboard**: Tab visits the pickers, the Channel select, Auto, then the editor.
#[must_use = "show the panel with `show`"]
#[derive(Pattern, Props)]
pub struct LevelsPanel<'a> {
@@ -105,7 +104,7 @@ pub struct LevelsPanel<'a> {
/// The histograms are being recounted.
#[prop]
stale: bool,
/// The armed point picker; the picker row shows when it is given.
/// The armed point picker; the picker row shows, first, when it is given.
#[prop]
pickers: Option<Bind<'a, Option<TonePicker>>>,
/// The document canvas the armed picker samples.
@@ -178,6 +177,22 @@ impl<'a> LevelsPanel<'a> {
// Alt+2…Alt+6 pick the Channel select's entry in a dialog; Properties has no such keys.
let stack = if context.is_dialog() { stack.command_scope(ToneChannelCommands::SCOPE) } else { stack };
let group = stack.show(ui, |ui, cx| {
if let Some(armed) = pickers.as_mut() {
let mut row = TonePickerRow::new(armed.reborrowed());
if pickers_unavailable {
row = row.unavailable();
}
if let Some(canvas) = canvas {
row = row.canvas(canvas);
}
for each in TonePicker::ALL {
// A grey document has no Neutral Gray point.
let usable = picker_enabled[each as usize] && !(each == TonePicker::Gray && (channels.is_gray() || context.is_gray()));
row = row.enabled_picker(each, usable);
}
picker = row.show(ui).change;
}
let all: Vec<Levels> = match levels.reborrow().read(cx) {
Some(Mixed::Same(all)) => all,
_ => Vec::new(),
@@ -232,21 +247,6 @@ impl<'a> LevelsPanel<'a> {
}
edit = events;
if let Some(armed) = pickers.as_mut() {
let mut row = TonePickerRow::new(armed.reborrowed());
if pickers_unavailable {
row = row.unavailable();
}
if let Some(canvas) = canvas {
row = row.canvas(canvas);
}
for each in TonePicker::ALL {
// A grey document has no Neutral Gray point.
let usable = picker_enabled[each as usize] && !(each == TonePicker::Gray && (channels.is_gray() || context.is_gray()));
row = row.enabled_picker(each, usable);
}
picker = row.show(ui).change;
}
// An edit belongs to the channel it was drawn for; a switch shows from the next pass.
shown = if picked == channel || !edit.is_empty() { channel } else { picked };
write_shown(&mut channel_bind, cx, stored, shown);
@@ -5,7 +5,7 @@ use std::cell::RefCell;
use craft_behavior::EditEvents;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft_ui::form::{Field, FieldGroup, SliderField};
use craft_ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use craft_ui::layout_components::Stack;
use craft_ui::pickers::Select;
use craft_ui::runtime::env::UnitKind;
@@ -200,7 +200,12 @@ fn with_current(modes: &[Entry<String>], current: &str) -> Vec<Entry<String>> {
/// A 0..=100 % slider and field, whole percent.
fn percent(ui: &mut Ui, label: &Label, value: f32) -> craft_ui::contract::EditResponse<f64> {
SliderField::new(label.clone(), Bind::given(f64::from(value)), 0.0..=100.0).step(1.0).unit_kind(UnitKind::Percent).show(ui).edit
SliderField::new(label.clone(), Bind::given(f64::from(value)), 0.0..=100.0)
.step(1.0)
.unit_kind(UnitKind::Percent)
.layout(SliderFieldLayout::Inline)
.show(ui)
.edit
}
/// The Advanced Blending checks' values, in Photoshop's order.
@@ -363,6 +363,7 @@ impl StackDialog for HostedLayerStyle {
let shown = FormDialog::new(label.clone(), Bind::bound(&mut *draft))
.opened(Bind::bound(open))
.preview(Some(Bind::bound(&mut preview)))
.side_buttons(true)
.extra_buttons([FooterButton::new(new_style, DialogRole::Other)])
.footer_extra(|ui| {
if let (Some(paint), Some(draft)) = (preview_thumb.as_deref(), snapshot.as_ref()) {
+11 -3
View File
@@ -9,7 +9,7 @@ use craft_ui::buttons::Button;
use craft_ui::choice::{Checkbox, Swatch};
use craft_ui::contract::{Bind, EditResponse, Entry, Props as _, Show as _, ShowContainer as _, clicked};
use craft_ui::display::Text;
use craft_ui::form::{Field, FieldGroup, SliderField};
use craft_ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::patterns::presets::{PresetPicker, PresetRow, PresetState};
@@ -201,8 +201,16 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
if let Some(default) = input.spec.defaults.number(key) {
bind = bind.reset(default);
}
let slider = SliderField::new(label.clone(), bind.reborrowed(), *min..=*max).unit_kind(unit_kind(*unit)).step(1.0).id_salt(key).show(ui);
push_edit(&mut out.edit, style_edit(&slider, input.style, |v| param(StyleValue::Number(v.round()))));
let slider = Field::new(label.clone()).id_salt(key).show(ui, |ui, _| {
SliderField::new(label.clone(), bind.reborrowed(), *min..=*max)
.unit_kind(unit_kind(*unit))
.step(1.0)
.layout(SliderFieldLayout::Inline)
.show(ui)
});
if let Some(slider) = slider.inner {
push_edit(&mut out.edit, style_edit(&slider, input.style, |v| param(StyleValue::Number(v.round()))));
}
}
FieldKind::Angle => {
let value = shown.number(key).unwrap_or(0.0);
+11 -6
View File
@@ -16,7 +16,7 @@ use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::runtime::requests::HostAnswer;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::sections::{DialogRole, FooterButton, Section};
use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind};
use egui::load::SizedTexture;
use egui::{Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
@@ -31,6 +31,7 @@ craft_ui::words! {
print: "printDialog.print" = "Print";
done: "printDialog.done" = "Done";
preview: "printDialog.preview" = "Print preview image";
printer_setup: "printDialog.printerSetup" = "Printer Setup";
image_box: "printDialog.imageBox" = "Image box";
}
}
@@ -461,11 +462,15 @@ impl<'a> PrintDialog<'a> {
Text::new(sheet.readout.clone()).show(ui);
});
Stack::new().show(ui, |ui, _| {
let panel = PrintPanel::new(settings.reborrowed(), printers).discovering(discovering).busy(busy).show(ui);
refresh |= panel.refresh;
for section in sections {
let mut rows = ParamRows::new(section.title.clone(), &section.params, Bind::bound(&mut *values)).show(ui);
form.requests().absorb(&mut rows);
Section::fixed(words.printer_setup.clone()).id_salt("printer").show(ui, |ui, _| {
let panel = PrintPanel::new(settings.reborrowed(), printers).discovering(discovering).busy(busy).show(ui);
refresh |= panel.refresh;
});
for (at, section) in sections.iter().enumerate() {
Section::fixed(section.title.clone()).id_salt(("section", at)).show(ui, |ui, _| {
let mut rows = ParamRows::new(section.title.clone(), &section.params, Bind::bound(&mut *values)).show(ui);
form.requests().absorb(&mut rows);
});
}
});
});
+41 -2
View File
@@ -1,7 +1,7 @@
//! `Units`: what typed number input and unit readouts need from the env (core 2.1): the locale's separators and the
//! unit spellings of a number's kind in the user's language, and the file sizes and durations written with them.
use super::EnvValue;
use super::{EnvValue, Label};
use craft_behavior::NumberCodec;
use craft_behavior::quantity::{Reader, is_unit_spelling};
use craft_i18n::{FileSize, Format, WordSet as _, Words};
@@ -10,7 +10,8 @@ use std::ops::RangeInclusive;
use std::sync::{Arc, OnceLock};
craft_ui::words! {
/// The unit words: `{n}` is where the number goes.
/// The unit words: `{n}` is where the number goes. The `_name` words name a unit in a list of units (a unit
/// select), without a number.
pub struct UnitWords {
pixels: unit "units.pixels" = "{n} px";
percent: unit "units.percent" = "{n}%";
@@ -28,6 +29,21 @@ craft_ui::words! {
lines_per_centimetre: unit "units.linesPerCentimetre" = "{n} lpcm";
minutes: unit "units.minutes" = "{n} min";
columns: unit "units.columns" = "{n} col";
pixels_name: "units.pixelsName" = "Pixels";
percent_name: "units.percentName" = "Percent";
degrees_name: "units.degreesName" = "Degrees";
points_name: "units.pointsName" = "Points";
times_name: "units.timesName" = "Times";
inches_name: "units.inchesName" = "Inches";
centimetres_name: "units.centimetresName" = "Centimetres";
millimetres_name: "units.millimetresName" = "Millimetres";
picas_name: "units.picasName" = "Picas";
pixels_per_inch_name: "units.pixelsPerInchName" = "Pixels/Inch";
pixels_per_centimetre_name: "units.pixelsPerCentimetreName" = "Pixels/Centimetre";
minutes_name: "units.minutesName" = "Minutes";
columns_name: "units.columnsName" = "Columns";
lines_per_inch_name: "units.linesPerInchName" = "Lines/Inch";
lines_per_centimetre_name: "units.linesPerCentimetreName" = "Lines/Centimetre";
}
}
@@ -342,6 +358,29 @@ impl Units {
}
}
/// The unit's name in the user's language, as a list of units shows it: Pixels, Pixels/Inch.
pub fn name(&self, kind: UnitKind) -> Label {
let words = &*self.words;
let name = match kind {
UnitKind::Pixels => &words.pixels_name,
UnitKind::Percent => &words.percent_name,
UnitKind::Degrees => &words.degrees_name,
UnitKind::Points => &words.points_name,
UnitKind::Times => &words.times_name,
UnitKind::Inches => &words.inches_name,
UnitKind::Centimetres => &words.centimetres_name,
UnitKind::Millimetres => &words.millimetres_name,
UnitKind::Picas => &words.picas_name,
UnitKind::PixelsPerInch => &words.pixels_per_inch_name,
UnitKind::PixelsPerCentimetre => &words.pixels_per_centimetre_name,
UnitKind::Minutes => &words.minutes_name,
UnitKind::Columns => &words.columns_name,
UnitKind::LinesPerInch => &words.lines_per_inch_name,
UnitKind::LinesPerCentimetre => &words.lines_per_centimetre_name,
};
name.clone()
}
/// The unit's spelling in the user's language without the number: `mm`, `px`.
pub fn symbol(&self, kind: UnitKind) -> String {
self.template(kind).replace("{n}", "").trim().to_owned()
@@ -17,6 +17,7 @@ use crate::contract::{Bind, BodyCx, CanvasGesture, NoValue, Outcome, Remember as
use crate::dialog::{Alert, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, FooterHooks, HeldAnswer, HeldOk, StackDialog, dialog_id};
use crate::display::{Shade, Text};
use crate::form::SliderFieldLayout;
use crate::layout_components::{Row, Stack};
use crate::notices::{Notice, NoticeLayout};
@@ -47,15 +48,37 @@ craft_ui::words! {
}
}
/// Where the preview pane sits.
/// How a parameter dialog arranges its rows, its preview pane and its buttons.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParamLayout {
/// The preview pane to the right of the rows, under the zoom row.
/// The preview pane to the right of the rows, under the zoom row. A dialog that previews has its buttons in a
/// column beside the body, with the Preview check box under them.
#[default]
Beside,
/// The preview pane under the rows.
/// The preview pane under the rows, under the zoom row. A dialog that previews has its buttons in a column beside
/// the body, with the Preview check box under them: Photoshop's filter dialogs.
Below,
/// One column: each slider row stacked (the label and the number field with its unit on one line, a full-width
/// slider under them), then the preview pane with the zoom row under it, and the buttons across the foot with the
/// Preview check box at their start: PhotoCraft's filter dialogs. The other rows keep the form's label and control
/// columns.
Stacked,
}
impl ParamLayout {
/// Whether a dialog that previews stands its buttons in a column beside the body.
fn side_buttons(self) -> bool {
!matches!(self, ParamLayout::Stacked)
}
/// How the range rows arrange their slider and number field.
fn sliders(self) -> SliderFieldLayout {
match self {
ParamLayout::Stacked => SliderFieldLayout::Stacked,
ParamLayout::Beside | ParamLayout::Below => SliderFieldLayout::Inline,
}
}
}
/// What a parameter dialog answers with at OK.
@@ -139,8 +162,8 @@ impl Outcome for ParamDialogOutput {
/// fills the parameters' defaults and, with `remember`, the values saved by [`ParamResult::remember`].
/// - Preview: a dialog that `previews` has the Preview check box; the host renders from the reported values while
/// `preview_on` (on the canvas, or as the picture it hands to `preview`), the unfiltered picture while `comparing`
/// (the Preview check box held down). Drag pans the picture, the zoom buttons scale it. A dialog that previews has
/// its buttons in a column beside the body, with the Preview check box and the footer note under them.
/// (the Preview check box held down). Drag pans the picture, the zoom buttons scale it. The
/// [`layout`](ParamDialog::layout) places the pane and the buttons.
/// - Footer: [`extra_buttons`](ParamDialog::extra_buttons) keep the dialog open and come back as
/// `ParamDialogOutput::footer_action`; [`footer_note`](ParamDialog::footer_note) is a muted line at the start edge.
/// - A command form is a dialog with no preview and no remember key.
@@ -191,7 +214,7 @@ pub struct ParamDialog<'a> {
/// keys added since the open go.
#[prop]
reset_to: Option<DialogFields>,
/// Where the preview pane sits.
/// How the rows, the preview pane and the buttons are arranged.
#[prop]
layout: ParamLayout,
/// Whether the title row has a close action.
@@ -459,7 +482,7 @@ impl<'a> ParamDialog<'a> {
form = form.opened(open);
}
if previews {
form = form.preview(preview_on);
form = form.preview(preview_on).side_buttons(layout.side_buttons());
}
// The pane shows only in a dialog that previews.
let preview = preview.filter(|_| previews);
@@ -523,7 +546,10 @@ impl<'a> ParamDialog<'a> {
live.view = live.view.centred_on(point, texture.size);
}
let mut show_rows = |ui: &mut Ui, values: &mut DialogFields| {
let mut shown = ParamRows::new(title.clone(), &params, Bind::bound(values)).patterns(&patterns).preview_colors(&preview_colors);
let mut shown = ParamRows::new(title.clone(), &params, Bind::bound(values))
.patterns(&patterns)
.preview_colors(&preview_colors)
.sliders(layout.sliders());
if let Some(canvas) = canvas {
shown = shown.canvas(canvas);
}
@@ -533,13 +559,15 @@ impl<'a> ParamDialog<'a> {
(Some(texture), ParamLayout::Beside) => {
Row::new().show(ui, |ui, _| {
show_rows(ui, values);
Stack::new().show(ui, |ui, _| shown_preview = show_preview(ui, &preview_label, texture, click_centres, &mut live));
Stack::new()
.show(ui, |ui, _| shown_preview = show_preview(ui, &preview_label, texture, click_centres, ZoomRow::Above, &mut live));
});
}
(Some(texture), ParamLayout::Below) => {
(Some(texture), layout) => {
let zoom = if layout == ParamLayout::Stacked { ZoomRow::Below } else { ZoomRow::Above };
Stack::new().show(ui, |ui, _| {
show_rows(ui, values);
shown_preview = show_preview(ui, &preview_label, texture, click_centres, &mut live);
shown_preview = show_preview(ui, &preview_label, texture, click_centres, zoom, &mut live);
});
}
(None, _) => show_rows(ui, values),
@@ -722,12 +750,20 @@ struct ShownPreview {
centre: Option<Pos2>,
}
/// Where the zoom row stands: over the preview pane or under it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ZoomRow {
Above,
Below,
}
/// The zoom row and the pane.
fn show_preview(ui: &mut Ui, label: &Label, texture: &SizedTexture, click_centres: bool, live: &mut Live) -> ShownPreview {
let zoom = PreviewZoom::new(&live.view).show(ui);
fn show_preview(ui: &mut Ui, label: &Label, texture: &SizedTexture, click_centres: bool, zoom_row: ZoomRow, live: &mut Live) -> ShownPreview {
let above = (zoom_row == ZoomRow::Above).then(|| PreviewZoom::new(&live.view).show(ui));
let pane = PreviewPane::new(label.clone(), *texture, &live.view).click_centres(click_centres).show(ui);
let below = (zoom_row == ZoomRow::Below).then(|| PreviewZoom::new(&live.view).show(ui));
let centre = pane.shown.centre(texture.size);
live.view = zoom.view.or(pane.view).unwrap_or(pane.shown);
live.view = above.or(below).and_then(|zoom| zoom.view).or(pane.view).unwrap_or(pane.shown);
ShownPreview { clicked: pane.clicked, centre: Some(centre) }
}
@@ -27,15 +27,15 @@ fn picture(ui: &Ui, unfiltered: bool) -> SizedTexture {
SizedTexture::new(id, Vec2::new(PICTURE[0] as f32, PICTURE[1] as f32))
}
const LAYOUTS: [(&str, ParamLayout); 2] = [("Beside", ParamLayout::Beside), ("Below", ParamLayout::Below)];
const LAYOUTS: [(&str, ParamLayout); 3] = [("Beside", ParamLayout::Beside), ("Below", ParamLayout::Below), ("Stacked", ParamLayout::Stacked)];
/// A blur dialog with the `preview` and `layout` values of the story.
fn blur_story(ui: &mut Ui, data: &mut StoryData, preview: bool, layout: ParamLayout) -> StoryOutput {
let preview = *data.value("preview", preview);
let layout = *data.choice("layout", layout, &LAYOUTS);
let comparing = *data.value("comparing", false);
let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true))).history(true);
let dialog = if preview { dialog.previews(true).preview(picture(ui, comparing)).layout(layout) } else { dialog };
let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true))).history(true).layout(layout);
let dialog = if preview { dialog.previews(true).preview(picture(ui, comparing)) } else { dialog };
let shown = dialog.show(ui);
*data.value("comparing", false) = shown.comparing;
shown.into()
@@ -56,6 +56,12 @@ fn param_dialog_with_preview_below(ui: &mut Ui, data: &mut StoryData) -> StoryOu
blur_story(ui, data, true, ParamLayout::Below)
}
/// PhotoCraft's filter dialogs: stacked slider rows, the pane with the zoom row under it, the buttons across the foot.
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
fn param_dialog_stacked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
blur_story(ui, data, true, ParamLayout::Stacked)
}
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
fn param_dialog_close_without_reset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC))
@@ -32,6 +32,7 @@ craft_ui::words! {
pub struct ExportWords {
title: "export.title" = "Export As";
export: "export.export" = "Export…";
file_settings: "export.fileSettings" = "File Settings";
format: "export.format" = "Format";
quality: "export.quality" = "Quality";
lossless: "export.lossless" = "Lossless";
@@ -32,7 +32,7 @@ use crate::pickers::Select;
use crate::runtime::env::{Env, Label, UnitKind, Units};
use crate::runtime::overlay::CloseReason;
use crate::sections::{HeaderStrength, Section};
use crate::sections::Section;
use crate::style::TypeRole;
use crate::text::NumberField;
@@ -650,6 +650,26 @@ struct Pass<'p> {
impl Pass<'_> {
fn settings(&self, ui: &mut Ui, options: &mut ExportOptions, held: &mut Held) {
let words = self.words;
let mut format = None;
Section::fixed(words.file_settings.clone()).id_salt("file").show(ui, |ui, _| format = self.file_settings(ui, options));
let Some(format) = format else { return };
Section::fixed(words.color_space.clone()).id_salt("color-space").show(ui, |ui, _| {
let mut srgb = options.profile == ExportProfile::Srgb;
check(ui, &words.convert_srgb, "profile", &mut srgb);
options.profile = if srgb { ExportProfile::Srgb } else { ExportProfile::Document };
check(ui, &words.embed_profile, "embed", &mut options.embed_profile);
});
Section::fixed(words.image_size.clone()).id_salt("size").show(ui, |ui, _| self.size(ui, options, held, format));
Section::fixed(words.scale_all.clone()).id_salt("scale-all").show(ui, |ui, _| self.scale_all(ui, options));
if let Some(library) = self.library {
self.preset_row(ui, options, held, library);
}
}
/// File Settings: the format, its options and the metadata; the format shown, `None` when the list has none.
fn file_settings(&self, ui: &mut Ui, options: &mut ExportOptions) -> Option<&ExportFormat> {
let words = self.words;
let chosen = self.formats.iter().position(|format| format.id == options.format).unwrap_or(0);
let entries: Vec<Entry<usize>> = self.formats.iter().enumerate().map(|(at, format)| Entry::new(at, format.name)).collect();
@@ -658,7 +678,7 @@ impl Pass<'_> {
if now != chosen {
self.switch(options, now);
}
let Some(format) = self.formats.get(now) else { return };
let format = self.formats.get(now)?;
if format.lossless {
check(ui, &words.lossless, "lossless", &mut options.lossless);
@@ -689,21 +709,7 @@ impl Pass<'_> {
Entry::new(ExportMetadata::All, words.metadata_all.clone()),
];
choose(ui, &words.metadata, "metadata", &metadata, &mut options.metadata);
Section::fixed(words.color_space.clone()).strength(HeaderStrength::Caption).id_salt("color-space").show(ui, |ui, _| {
let mut srgb = options.profile == ExportProfile::Srgb;
check(ui, &words.convert_srgb, "profile", &mut srgb);
options.profile = if srgb { ExportProfile::Srgb } else { ExportProfile::Document };
check(ui, &words.embed_profile, "embed", &mut options.embed_profile);
});
Section::fixed(words.image_size.clone())
.strength(HeaderStrength::Caption)
.id_salt("size")
.show(ui, |ui, _| self.size(ui, options, held, format));
Section::fixed(words.scale_all.clone()).strength(HeaderStrength::Caption).id_salt("scale-all").show(ui, |ui, _| self.scale_all(ui, options));
if let Some(library) = self.library {
self.preset_row(ui, options, held, library);
}
Some(format)
}
/// The preset row under Image Size: a pick applies the preset's options, and each new, renamed or deleted preset
@@ -158,8 +158,9 @@ type ResetWithFn<'a, V> = Box<dyn Fn(&V, &V) -> V + 'a>;
/// - The body returns whether the value can be accepted; OK is enabled while it can and `ok_enabled` is true.
/// - With [`history`](FormDialog::history), Cmd/Ctrl+Z and Shift+Cmd/Ctrl+Z step the dialog's own value; a drag or a
/// typing run is one step.
/// - With [`preview`](FormDialog::preview), the buttons stand in a column beside the body, with the Preview check box
/// and the footer controls under them.
/// - The footer goes across the foot, the Preview check box and the footer controls at its start edge; with
/// [`side_buttons`](FormDialog::side_buttons) the buttons stand in a column beside the body, with the Preview check
/// box and the footer controls under them.
#[must_use = "show the dialog with `show`"]
#[derive(crate::contract::Pattern)]
#[pattern(probe(FormDialog<'static, bool>))]
@@ -179,6 +180,7 @@ pub struct FormDialog<'a, V: Value + Default> {
closable: bool,
accept_stays_open: bool,
enter_confirms: bool,
side_buttons: bool,
footer_extra: Option<FooterExtraFn<'a>>,
/// The Preview check box when shown, over its owner's bind or (`None`) the footer's memory.
preview: Option<Option<Bind<'a, bool>>>,
@@ -210,6 +212,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
closable: true,
accept_stays_open: false,
enter_confirms: true,
side_buttons: false,
footer_extra: None,
preview: None,
extra_buttons: Vec::new(),
@@ -308,15 +311,21 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
self
}
/// The Preview check box, first under the buttons, which stand beside the body: the host previews the value while
/// it is on, and the unfiltered picture while it is held ([`FormOutput::comparing`]). With `on`, the box reads and
/// writes that bind (a kept bind starts on). Without it, every open starts with the box on, and the dialog keeps
/// it off while it stays open.
/// The Preview check box, first in the footer: the host previews the value while it is on, and the unfiltered
/// picture while it is held ([`FormOutput::comparing`]). With `on`, the box reads and writes that bind (a kept
/// bind starts on). Without it, every open starts with the box on, and the dialog keeps it off while it stays open.
pub fn preview(mut self, on: Option<Bind<'a, bool>>) -> Self {
self.preview = Some(on);
self
}
/// Whether the buttons stand in a column beside the body, with the Preview check box and the footer controls under
/// them (`Dialog::side_buttons`), instead of across the foot: Photoshop's button-column dialogs.
pub fn side_buttons(mut self, on: bool) -> Self {
self.side_buttons = on;
self
}
/// Footer buttons after OK and Cancel, which keep the dialog open: the caller acts on
/// [`FormOutput::picked`].
pub fn extra_buttons(mut self, buttons: impl IntoIterator<Item = FooterButton>) -> Self {
@@ -375,6 +384,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
closable,
accept_stays_open,
enter_confirms,
side_buttons,
footer_extra,
preview,
extra_buttons,
@@ -413,7 +423,11 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
}
}
};
let mut dialog = Dialog::new(title).closable(closable).close_on_enter(ok_enabled && enter_confirms).outer_gesture(outer_gesture);
let mut dialog = Dialog::new(title)
.closable(closable)
.close_on_enter(ok_enabled && enter_confirms)
.outer_gesture(outer_gesture)
.side_buttons(side_buttons);
dialog = reset.install(dialog, accept, restore);
if let Some(open) = open {
dialog = dialog.opened(open);
@@ -423,9 +437,6 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
}
let changed = RefCell::new(None::<V>);
let (preview_on, comparing) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
if preview.is_some() {
dialog = dialog.side_buttons(true);
}
if footer_extra.is_some() || preview.is_some() {
let (on, held, label) = (Rc::clone(&preview_on), Rc::clone(&comparing), env.words::<FormDialogWords>().preview.clone());
let (mut extra, mut preview) = (footer_extra, preview);
@@ -331,7 +331,7 @@ impl<'a> GuideLayoutDialog<'a> {
let env = Env::of(ui);
let words = env.words::<GuideDialogWords>();
let number_units = env.units();
let mut dialog = FormDialog::new(words.layout_title.clone(), values).outer_gesture(true).answers(answers).preview(preview);
let mut dialog = FormDialog::new(words.layout_title.clone(), values).outer_gesture(true).answers(answers).preview(preview).side_buttons(true);
if let Some(open) = open {
dialog = dialog.opened(open);
}
@@ -80,9 +80,9 @@ fn apply_number(session: &mut Session, events: &EditEvents<Option<f64>>, set: im
}
}
/// The entries of a unit list, named by the units' symbols.
/// The entries of a unit list, named by the units' names.
fn unit_entries(read: &Read<'_>, kinds: &[UnitKind]) -> Vec<Entry<UnitKind>> {
kinds.iter().map(|kind| Entry::new(*kind, read.units.symbol(*kind))).collect()
kinds.iter().map(|kind| Entry::new(*kind, read.units.name(*kind))).collect()
}
/// Shows the column.
@@ -90,7 +90,9 @@ impl Outcome for ParamRowsOutput {
/// - **Values.** They live in the caller's [`DialogFields`] binding; a missing key shows its parameter's default,
/// which the pass writes. The host keeps its own history of the values and its own Reset.
/// - **Rows.** A row is shown while its `visible_when` holds and takes input while its `enabled_when` holds. A
/// [`Param::section`] opens a section whose body is the rows up to the next section.
/// [`Param::section`] opens a section, a bold title under a rule, whose body is the rows up to the next section.
/// A range row is a slider and its number field beside the row's label, or stacked under the label
/// ([`sliders`](ParamRows::sliders)).
/// - **Requests.** A colour press, a Browse press and the eyedropper toggle come back in [`ParamRowsOutput`].
/// - **Random.** The Random button of an int row draws from a sequence seeded by `seed`'s binding; without one the
/// sequence starts the same in every run.
@@ -107,12 +109,31 @@ pub struct ParamRows<'a> {
canvas: Option<Id>,
patterns: &'a [PresetRow<String>],
preview_colors: &'a [(String, Srgba)],
sliders: SliderFieldLayout,
}
impl<'a> ParamRows<'a> {
/// Rows for `params` over `fields`, the group named `label`.
pub fn new(label: impl Into<Label>, params: &'a [Param], fields: Bind<'a, DialogFields>) -> Self {
ParamRows { label: label.into(), params, fields, seed: None, read_only: false, canvas: None, patterns: &[], preview_colors: &[] }
ParamRows {
label: label.into(),
params,
fields,
seed: None,
read_only: false,
canvas: None,
patterns: &[],
preview_colors: &[],
sliders: SliderFieldLayout::Inline,
}
}
/// How the range rows arrange their slider and number field: `Inline` (the default) puts them on one line beside
/// the row's label; `Stacked` puts the label and the number field on one line and the slider across the width
/// under them.
pub fn sliders(mut self, layout: SliderFieldLayout) -> Self {
self.sliders = layout;
self
}
/// The colours child pickers preview, by colour row key: each such row draws its colour for the pass in place of
@@ -150,13 +171,14 @@ impl<'a> ParamRows<'a> {
/// Shows the rows across the width offered.
pub fn show(self, ui: &mut Ui) -> ParamRowsOutput {
let ParamRows { label, params, mut fields, mut seed, read_only, canvas, patterns, preview_colors } = self;
let ParamRows { label, params, mut fields, mut seed, read_only, canvas, patterns, preview_colors, sliders } = self;
let env = Env::of(ui);
let words = env.words::<ParamWords>();
let units = env.units();
let name: Arc<str> = label.as_str().into();
let mut pass = Pass::new(&words, &units, patterns, canvas);
pass.previews = preview_colors;
pass.sliders = sliders;
let mut changed = false;
let mut values = None;
let mut group = |ui: &mut Ui| {
@@ -239,6 +261,8 @@ struct Pass<'p> {
canvas: Option<Id>,
/// The colours shown in colour rows in place of their values (`ParamRows::preview_colors`).
previews: &'p [(String, Srgba)],
/// How range rows arrange their slider and number field (`ParamRows::sliders`).
sliders: SliderFieldLayout,
}
/// A parameter as the pass shows it: its key, its label without the colon, and whether it takes input.
@@ -287,6 +311,7 @@ impl<'p> Pass<'p> {
patterns,
canvas,
previews: &[],
sliders: SliderFieldLayout::Inline,
}
}
@@ -351,7 +376,7 @@ impl<'p> Pass<'p> {
let end = tail.iter().position(is_section).unwrap_or(tail.len());
let (body, after) = tail.split_at(end);
if head.visible(&self.work) {
group(plain(&head.label)).id_salt(head.key.as_str()).show(ui, |ui, _| {
Section::fixed(plain(&head.label)).id_salt(head.key.as_str()).show(ui, |ui, _| {
for param in body {
self.row(ui, param);
}
@@ -405,24 +430,36 @@ impl<'p> Pass<'p> {
}
}
/// A range row: inline beside its label in the row's field, or stacked under its own caption across the form.
fn range(&mut self, ui: &mut Ui, line: &Line<'_>, range: RangeInclusive<f64>, scale: SliderScale) {
let value = self.work.number(line.key).unwrap_or(*range.start());
let places = line.param.option().range_places();
line.show(ui, |ui| {
let mut slider = SliderField::new(line.name.clone(), Bind::given(value), range.clone()).scale(scale).layout(SliderFieldLayout::Inline);
let layout = self.sliders;
let mut show = |ui: &mut Ui| {
let mut slider = SliderField::new(line.name.clone(), Bind::given(value), range.clone()).scale(scale).layout(layout);
if let Some(places) = places {
slider = slider.step(10f64.powi(-(places as i32)));
}
if let Some(kind) = line.param.unit {
slider = slider.unit_kind(kind);
}
if layout == SliderFieldLayout::Stacked {
slider = slider.id_salt(line.key).enabled(line.enabled);
if let Some(tip) = line.param.tooltip_text() {
slider = slider.tooltip(tip.clone());
}
}
let shown = slider.show(ui);
let value = shown.value().cloned();
self.alert(shown.out_of_range);
if let Some(v) = value {
self.work.set(line.key, rounded(v, places));
}
});
};
match layout {
SliderFieldLayout::Stacked => show(ui),
_ => line.show(ui, show),
}
}
fn number(&mut self, ui: &mut Ui, line: &Line<'_>, range: Option<RangeInclusive<f64>>, step: f64, decimals: u32) {
@@ -635,7 +672,7 @@ impl<'p> Pass<'p> {
/// A radio row is its own section: the title shows the row's name once, and the group it names follows.
fn radio_options(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)]) {
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
group(line.name.clone()).id_salt(line.key).show(ui, |ui, _| {
Section::fixed(line.name.clone()).strength(HeaderStrength::Caption).id_salt(line.key).show(ui, |ui, _| {
let mut group = RadioGroup::new(line.name.clone(), Bind::given(value.clone())).enabled(line.enabled);
if let Some(tip) = line.param.tooltip_text() {
group = group.tooltip(tip.clone());
@@ -915,11 +952,6 @@ fn text_of(value: FieldValue) -> Option<String> {
}
}
/// The heading of a group of rows (a section, or a row of radio buttons): a quiet caption, with no rule.
fn group<'a>(title: impl Into<Label>) -> Section<'a> {
Section::fixed(title).strength(HeaderStrength::Caption)
}
/// A row's label without a trailing colon: the form puts its own beside the control.
fn plain(label: &Label) -> Label {
match label {
@@ -18,7 +18,7 @@ use crate::pickers::{Select, UnitSelect};
use crate::runtime::env::{Label, UnitKind, Units};
use crate::sections::{HeaderStrength, Section};
use crate::sections::Section;
use crate::text::{HexField, NumberField};
use craft_behavior::{NumberCodec, Selection};
@@ -245,7 +245,7 @@ fn palette_section(
(Label::from(format!("{index} #{r:02x}{g:02x}{b:02x}")), Srgba::from(Rgba([r, g, b, OPAQUE])))
})
.collect();
Section::fixed(words.color_table.clone()).strength(HeaderStrength::Caption).id_salt("palette").show(ui, |ui, _| {
Section::fixed(words.color_table.clone()).id_salt("palette").show(ui, |ui, _| {
let shown = SwatchTable::new(words.color_table.clone(), &entries).per_row(16).tips(true).selection(Bind::bound(&mut *table)).show_all(ui);
if let Some(index) = shown.open
&& let (Some((_, color)), Ok(at)) = (entries.get(index), u16::try_from(index))
@@ -333,10 +333,10 @@ fn metadata_row(ui: &mut Ui, words: &SaveForWebWords, options: &mut SaveForWebOp
/// Image Size: Width and Height in pixels or percent, the Percent row and the Resample method.
fn size_section(ui: &mut Ui, words: &SaveForWebWords, sizing: &SizingWords, units: &Units, link: &mut LinkedSize, resample: &mut Resample) {
let kinds = [
Entry::new(UnitKind::Pixels, Label::from(units.symbol(UnitKind::Pixels))),
Entry::new(UnitKind::Percent, Label::from(units.symbol(UnitKind::Percent))),
Entry::new(UnitKind::Pixels, units.name(UnitKind::Pixels)),
Entry::new(UnitKind::Percent, units.name(UnitKind::Percent)),
];
Section::fixed(words.image_size.clone()).strength(HeaderStrength::Caption).id_salt("size").show(ui, |ui, _| {
Section::fixed(words.image_size.clone()).id_salt("size").show(ui, |ui, _| {
row(ui, &words.width, "width", |ui| {
let range = link.width_range();
let field = UnitSelect::new(words.width.clone(), Bind::given(Some(link.width())), Bind::given(link.unit()), &kinds)
@@ -39,8 +39,6 @@ craft_ui::words! {
/// `{width}` and `{height}` are the sides with their unit.
dimensions_value: template "sizing.dimensionsValue" = "{width} × {height}";
current_size: "sizing.currentSize" = "Current Size";
current_width: "sizing.currentWidth" = "Current width";
current_height: "sizing.currentHeight" = "Current height";
new_size: "sizing.newSize" = "New Size";
width: "sizing.width" = "Width";
height: "sizing.height" = "Height";
@@ -336,7 +334,7 @@ impl Kit {
let env = Env::of(ui);
let units = env.units();
let entries =
|kinds: &[UnitKind]| -> Vec<Entry<UnitKind>> { kinds.iter().map(|kind| Entry::new(*kind, Label::from(units.symbol(*kind)))).collect() };
|kinds: &[UnitKind]| -> Vec<Entry<UnitKind>> { kinds.iter().map(|kind| Entry::new(*kind, units.name(*kind))).collect() };
let lengths = entries(&LENGTH_UNITS);
let mut widths = lengths.clone();
widths.extend(entries(&[UnitKind::Columns]));
@@ -6,7 +6,10 @@ use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use crate::form::Field;
use crate::pickers::{Anchor9, ReferencePoint, Select};
use crate::runtime::env::{ColumnSize, UnitKind};
use crate::display::Text;
use crate::runtime::env::{ColumnSize, Label, UnitKind};
use crate::sections::Section;
use craft_theme::variant::Tone;
use craft_behavior::PixelSize;
use egui::Ui;
use serde_json::json;
@@ -184,24 +187,26 @@ impl<'a> CanvasSize<'a> {
let size = state.size.original();
let has_background = state.has_background;
state.extension = state.fill();
kit.readout(ui, &words.current_size, kit.file_size(size, bytes_per_pixel), None);
kit.readout(ui, &words.current_width, kit.pixels(size.width), None);
kit.readout(ui, &words.current_height, kit.pixels(size.height), None);
sized_section(ui, "current", &words.current_size, kit.file_size(size, bytes_per_pixel), None, |ui| {
kit.readout(ui, &words.width, kit.pixels(size.width), None);
kit.readout(ui, &words.height, kit.pixels(size.height), None);
});
let now = state.size.pixels();
kit.readout(ui, &words.new_size, kit.file_size(now, bytes_per_pixel), kit.tone_of(now));
kit.refusal(ui, now);
kit.sides(ui, &mut state.size);
let check = Checkbox::new(Bind::given(state.size.is_relative())).label(words.relative.clone()).id_salt("relative").show(ui);
if let Some(on) = check.value().copied() {
state.size.relative(on);
}
let growth = (f64::from(now.width) - f64::from(size.width), f64::from(now.height) - f64::from(size.height));
Field::new(words.anchor.clone()).id_salt("anchor").show(ui, |ui, _| {
let picked = ReferencePoint::new(words.anchor.clone(), Bind::given(state.anchor)).growth(growth).show(ui);
if let Some(anchor) = picked.value().copied() {
state.anchor = anchor;
sized_section(ui, "new", &words.new_size, kit.file_size(now, bytes_per_pixel), kit.tone_of(now), |ui| {
kit.refusal(ui, now);
kit.sides(ui, &mut state.size);
let check =
Checkbox::new(Bind::given(state.size.is_relative())).label(words.relative.clone()).id_salt("relative").show(ui);
if let Some(on) = check.value().copied() {
state.size.relative(on);
}
let growth = (f64::from(now.width) - f64::from(size.width), f64::from(now.height) - f64::from(size.height));
Field::new(words.anchor.clone()).id_salt("anchor").show(ui, |ui, _| {
let picked = ReferencePoint::new(words.anchor.clone(), Bind::given(state.anchor)).growth(growth).show(ui);
if let Some(anchor) = picked.value().copied() {
state.anchor = anchor;
}
});
});
Field::new(words.extension.clone()).id_salt("extension").enabled(has_background).show(ui, |ui, _| {
let entries = CanvasExtension::entries(words, &state.extension, has_background);
@@ -216,6 +221,20 @@ impl<'a> CanvasSize<'a> {
}
}
/// A section titled `title` with the file size `size` at the end of its header, in `tone` when given.
fn sized_section(ui: &mut Ui, salt: &str, title: &Label, size: String, tone: Option<Tone>, mut body: impl FnMut(&mut Ui)) {
Section::fixed(title.clone())
.id_salt(salt)
.controls(move |ui, _| {
let text = Text::new(size.clone());
match tone {
Some(tone) => text.tone(tone).show(ui),
None => text.show(ui),
};
})
.show(ui, |ui, _| body(ui));
}
/// Builds the dialog over the host-owned values of a [`HostedCanvasSize`] for one pass.
type Build = dyn for<'b> Fn(Bind<'b, CanvasSizeValues>) -> CanvasSize<'b> + Send;
@@ -5,10 +5,11 @@
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Outcome as _, Role, SaveKey, Show as _, clicked};
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::testing::relations::{above, left_of};
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
use egui::{Key, Modifiers, TextureId, Vec2, vec2};
@@ -74,6 +75,38 @@ fn holding_the_preview_box_compares_and_the_release_toggles_it() {
assert_eq!(seen.get(), (false, false), "the release turns the preview off");
}
/// The rects of the radius slider, its number field, the Preview box and OK in a previewing blur dialog laid out as
/// `layout`.
fn laid_out(layout: ParamLayout) -> [egui::Rect; 4] {
let mut fixture = Fixture::new(move |ui| {
let picture = SizedTexture::new(TextureId::default(), vec2(64.0, 48.0));
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).previews(true).preview(picture).layout(layout).show(ui);
});
fixture.settle();
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the radius row has a slider");
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().next().expect("the radius row has a number field");
let preview = fixture
.by_role(Role::CHECK_BOX)
.into_iter()
.find(|target| fixture.tree().name_of(target.node) == Some("Preview"))
.expect("the footer has the Preview box");
let ok = fixture.by_label("OK").expect("the footer has OK");
[slider.rect, field.rect, preview.rect, ok.rect]
}
// Stacked puts each slider under its number field and the buttons across the foot, the Preview box before them;
// Below stands the buttons beside the body.
#[trial]
fn the_stacked_layout_stacks_sliders_and_puts_the_buttons_across_the_foot() {
let [slider, field, preview, ok] = laid_out(ParamLayout::Stacked);
assert!(above(field, slider), "the number field stands over the slider");
assert!(above(slider, ok) && above(slider, preview), "the footer is under the rows");
assert!(left_of(preview, ok), "the Preview box comes before OK on the footer line");
let [slider, _, preview, ok] = laid_out(ParamLayout::Below);
assert!(left_of(slider, ok), "the buttons stand beside the body");
assert!(above(ok, preview), "the Preview box is under the buttons");
}
/// 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()));
+10 -8
View File
@@ -4,10 +4,10 @@ use super::select::Select;
use crate::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, MeasureCx, Outcome, PaintUi, Props as _, Role, WordSetCx as _,
};
use crate::runtime::env::{Label, UnitKind};
use crate::runtime::env::{Label, UnitKind, Units};
use crate::style::{ComponentStyle, StyleCx};
use crate::text::{NumberField, RangeAlert};
use craft_behavior::{EditEvents, Flow, Metrics, Mixed, Proposal, Sense};
use craft_behavior::{EditEvents, Flow, Metrics, Mixed, NumberCodec, Proposal, Sense};
use egui::{Rect, Response, Vec2, pos2};
use std::ops::{Deref, RangeInclusive};
@@ -59,9 +59,10 @@ impl Outcome for UnitSelectOutput {
}
}
/// A number field with a select of units after it. The select picks the unit kind the field reads typed text in and
/// shows its number with, and the kind sets the digits and the step of the number; the number itself is the field's value, and the unit goes to its own binding, so the app
/// converts the number when the unit changes.
/// A number field with a select of units after it. The select picks the unit kind the field reads typed text in
/// (its spellings: "12 mm") and shows its number with, and the kind sets the digits and the step of the number; the
/// select names the unit, so the field shows the number alone. The number itself is the field's value, and the unit
/// goes to its own binding, so the app converts the number when the unit changes.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component]
pub struct UnitSelect<'a> {
@@ -102,7 +103,7 @@ impl<'a> UnitSelect<'a> {
.label(label)
}
fn number(&self, name: Label, value: Mixed<Option<f64>>, kind: Option<UnitKind>) -> NumberField<'static> {
fn number(&self, name: Label, value: Mixed<Option<f64>>, kind: Option<(UnitKind, &Units)>) -> NumberField<'static> {
let field = NumberField::new(name, Bind::given(value));
let field = match self.number_enabled {
Some(on) => field.enabled(on),
@@ -113,7 +114,7 @@ impl<'a> UnitSelect<'a> {
None => field,
};
match kind {
Some(kind) => field.unit_kind(kind).step(kind.step()),
Some((kind, units)) => field.codec(NumberCodec::new(units.reader(Some(kind)), *kind.decimals().end())).step(kind.step()),
None => field,
}
}
@@ -172,7 +173,8 @@ impl Component for UnitSelect<'_> {
};
let shown = shown_of(cx.value());
let start = cx.value().and_then(|value| *value);
let number = ui.child("number", place(number_rect), self.number(group.clone(), shown, kind));
let units = cx.env.units();
let number = ui.child("number", place(number_rect), self.number(group.clone(), shown, kind.map(|kind| (kind, &units))));
cx.adopt(&number, &start, |value, mine| *mine = *value);
self.out_of_range = number.out_of_range;
let select = Select::new(self.select_name(&group), self.unit.reborrowed(), self.units);
@@ -8,7 +8,7 @@ use craft_behavior::Mixed;
use egui::Ui;
fn units() -> [Entry<UnitKind>; 3] {
[Entry::new(UnitKind::Millimetres, "mm"), Entry::new(UnitKind::Inches, "in"), Entry::new(UnitKind::Points, "pt")]
[Entry::new(UnitKind::Millimetres, "Millimetres"), Entry::new(UnitKind::Inches, "Inches"), Entry::new(UnitKind::Points, "Points")]
}
#[story(UnitSelect<'static>, covers = [Default], drive = Drive::Type("42"))]