dialogs-w7: net change of 2 commits

- dialogs-w7: written by an agent
- dialogs-w7: review fixes (review-1)
This commit is contained in:
aiongg
2026-11-15 04:46:08 +00:00
parent 74322a79a9
commit 57b00a9a72
11 changed files with 454 additions and 112 deletions
+36 -4
View File
@@ -48,16 +48,48 @@ impl LayerStyleDraft {
LayerStyleDraft { style, page, blend_if_channel: 0, preview: true, shadow_drag: None, gradient_drag: None }
}
/// Whether a Gradient Overlay offset drag is in progress.
/// Whether a drag on the image moves the selected effect's gradient offset now: a Gradient
/// Overlay page is selected.
pub fn drags_gradient(&self) -> bool {
self.gradient_drag.is_some()
self.selected_kind() == Some(EffectKind::GradientOverlay)
}
/// A drag on the image moves the selected Gradient Overlay's hidden `offset` by the pointer's travel over the layer
/// size. `start` is the press; `total` the movement since it. Whether the offset changed.
///
/// The drag starts from the offset the page shows (the stored one clamped, else the spec
/// default) on the press, and again when another instance became the selected one mid-press,
/// counting the travel so far as its zero. A press that moved nothing writes nothing. Only
/// the pass's own `total` is read, so a second pass in the same frame repeats the write.
pub fn drag_gradient(&mut self, start: bool, total: [f64; 2], layer_size: [f64; 2]) -> bool {
let _ = (start, total, layer_size);
todo!("dl.K52")
let LayerStylePage::Effect(id) = self.page else {
return false;
};
if !self.drags_gradient() {
return false;
}
let default = match EffectSpec::photoshop(EffectKind::GradientOverlay).defaults.get("offset") {
Some(StyleValue::Point(p)) => *p,
_ => [0.0, 0.0],
};
let stored = self.style.effect(id).and_then(|e| e.params.get("offset"));
let shown = GradientOffsetDrag::shown(stored, default);
let drag = match self.gradient_drag {
Some(drag) if !start && drag.instance() == id => drag,
_ => GradientOffsetDrag::begin(id, shown, total),
};
self.gradient_drag = Some(drag);
let moved = drag.moved(total, layer_size);
let value = StyleValue::Point(moved);
// A press that moved nothing leaves the stored value (or its absence) alone.
if moved == drag.origin() && shown == drag.origin() {
return false;
}
if stored == Some(&value) {
return false;
}
self.set_param(id, "offset", value);
true
}
/// The host's release: clears the shadow and gradient drags.
+33 -10
View File
@@ -1,6 +1,6 @@
//! The drags on the image: moving a Drop Shadow or Inner Shadow (#5701), and a Gradient Overlay's offset.
use super::model::EffectId;
use super::model::{EffectId, StyleValue};
/// A shadow drag in progress: the shadow's angle and distance when the press came. The offset of
/// a shadow is (−cos angle, sin angle) × distance (the light sits opposite the shadow; y down).
@@ -35,8 +35,11 @@ impl ShadowDrag {
}
}
/// A Gradient Overlay offset drag in progress: the effect instance, the pointer's origin and the
/// offset it started from.
/// The largest offset a Gradient Overlay drag writes, in layer sizes, either way.
const OFFSET_LIMIT: f64 = 4.0;
/// A Gradient Overlay offset drag in progress: the effect instance, the offset it started from
/// and the pointer's travel when it started.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GradientOffsetDrag {
instance: EffectId,
@@ -45,17 +48,37 @@ pub struct GradientOffsetDrag {
}
impl GradientOffsetDrag {
/// A drag on `instance` that starts at `origin` from the hidden `offset` `base`.
/// A drag on `instance` from the shown offset `origin`, begun when the pointer's travel since
/// the press was `base` (zero at the press; the travel so far when the drag moves to another
/// instance mid-press, so the offset does not jump).
pub fn begin(instance: EffectId, origin: [f64; 2], base: [f64; 2]) -> Self {
let _ = (instance, origin, base);
todo!("dl.K52")
GradientOffsetDrag { instance, origin, base }
}
/// The offset after the pointer travelled `total` over a layer of `layer_size`, clamped to
/// plus or minus 4 and rounded to 0.001.
/// The offset after the pointer travelled `total` over a layer of `layer_size`: the origin plus
/// the travel since `base`, in layer sizes (a size under 1 counts as 1), clamped to plus or
/// minus 4 and rounded to 0.001. A result that is not finite is the origin.
pub fn moved(&self, total: [f64; 2], layer_size: [f64; 2]) -> [f64; 2] {
let _ = (total, layer_size);
todo!("dl.K52")
// The result is not an `Option`, so a non-finite result falls back to the origin.
let axis = |i: usize| {
let v = self.origin[i] + (total[i] - self.base[i]) / layer_size[i].max(1.0);
if v.is_finite() { (v.clamp(-OFFSET_LIMIT, OFFSET_LIMIT) * 1000.0).round() / 1000.0 } else { self.origin[i] }
};
[axis(0), axis(1)]
}
/// The offset a page shows for the stored `value`: its parts clamped to plus or minus 4, or
/// `default` when it is no point or a part is not finite.
pub(super) fn shown(value: Option<&StyleValue>, default: [f64; 2]) -> [f64; 2] {
match value {
Some(StyleValue::Point(p)) if p.iter().all(|x| x.is_finite()) => p.map(|x| x.clamp(-OFFSET_LIMIT, OFFSET_LIMIT)),
_ => default,
}
}
/// The offset the drag started from.
pub(super) fn origin(&self) -> [f64; 2] {
self.origin
}
/// The effect instance the drag moves.
+1 -1
View File
@@ -2,7 +2,7 @@
//! ten effect tables ([`EffectSpec::photoshop`]) with their defaults, the Blending Options
//! ([`Blending`], [`BlendIf`]), contours ([`Contour`]), and the dialog's draft logic
//! ([`LayerStyleDraft`]: the page, adding and removing instances, the shared light angle, the
//! shadow drag).
//! shadow drag and the Gradient Overlay offset drag).
//!
//! Everything here is plain data and pure functions, testable without a window. The dialog that
//! edits a draft is `craft_imaging::ui::layer_style` (the `ui` feature); the engine that renders
+12 -6
View File
@@ -134,10 +134,11 @@ impl EffectSpec {
/// Center); blend; opacity 0..100 %; overprint Overprint; color. Defaults: 1, inside,
/// Normal, 100, false, #000000.
/// - Color Overlay: blend; color; opacity 0..100 %. Defaults: Normal, #ff0000, 100.
/// - Gradient Overlay: blend; opacity; from From (Color); to To (Color); reverse Reverse; style
/// - Gradient Overlay: blend; opacity; stops Gradient (Gradient); reverse Reverse; style
/// Style (linear Linear, radial Radial, angle Angle, reflected Reflected, diamond Diamond);
/// angle; scale Scale 10..150 %; method Method (GradientMethod). Defaults: Normal, 100,
/// #000000, #ffffff, false, linear, 90, 100, custom.
/// black to white, false, linear, 90, 100, custom, and `offset` (0, 0), a point with no
/// field that the drag on the image moves.
/// - Pattern Overlay: blend; opacity; pattern Pattern; angle; scale Scale 1..1000 %; link Link
/// with Layer. Defaults: Normal, 100, "", 0, 100, true.
/// - Bevel & Emboss: style Style (inner Inner Bevel, outer Outer Bevel, emboss Emboss, pillow
@@ -311,8 +312,7 @@ impl EffectSpec {
vec![
field("blend", "Blend Mode", FieldKind::Blend),
field("opacity", "Opacity", percent()),
field("from", "From", FieldKind::Color),
field("to", "To", FieldKind::Color),
field("stops", "Gradient", FieldKind::Gradient),
field("reverse", "Reverse", FieldKind::Check),
field(
"style",
@@ -326,8 +326,8 @@ impl EffectSpec {
vec![
("blend", text("Normal")),
("opacity", num(100.0)),
("from", hex("#000000")),
("to", hex("#ffffff")),
("stops", black_to_white()),
("offset", StyleValue::Point([0.0, 0.0])),
("reverse", StyleValue::Bool(false)),
("style", text("linear")),
("angle", num(90.0)),
@@ -465,6 +465,12 @@ fn hex(s: &str) -> StyleValue {
StyleValue::Color(Srgba::from_hex(s).unwrap_or(Srgba::BLACK))
}
fn black_to_white() -> StyleValue {
use craft_color::gradient::{ColorStop, GradientStops};
let color = |s: &str| Srgba::from_hex(s).unwrap_or(Srgba::BLACK);
StyleValue::Gradient(GradientStops::new(vec![ColorStop::new(0.0, color("#000000")), ColorStop::new(1.0, color("#ffffff"))]))
}
fn linear() -> StyleValue {
StyleValue::Contour(Contour::linear())
}
+57 -3
View File
@@ -9,6 +9,12 @@ fn style_with(kinds: &[(u32, EffectKind)]) -> LayerStyle {
LayerStyle { effects, ..LayerStyle::default() }
}
fn set_offset(draft: &mut LayerStyleDraft, n: u32, offset: [f64; 2]) {
if let Some(e) = draft.style.effect_mut(EffectId(n)) {
e.params.set("offset", StyleValue::Point(offset));
}
}
// Per effect, the field keys in order with their kinds and ranges match the table in
// `EffectSpec::photoshop`'s doc (Outer Glow: Technique before Spread, Range after Contour).
@@ -76,10 +82,58 @@ fn shadow_drag_uses_whole_degrees_and_pixels_and_moves_the_global_angle() {
// The blend defaults of a spec become the host's keys; unknown names stay. Bevel & Emboss has two
// Blend fields: only the one defaulting to Multiply is renamed.
// `BlendIfRange::ordered` raises each value to at least the one before it.
// A press writes nothing; a drag moves the offset by travel over the layer size from the shown
// offset; an out-of-range or non-finite stored offset starts from the clamp or the default;
// selecting the other instance mid-press rebases on the travel so far; the result is clamped to
// ±4 and rounded to 0.001; `end_drag` clears the drag.
#[trial]
fn blend_if_ranges_read_ordered() {
assert_eq!(BlendIfRange::ordered([10, 5, 200, 100]), BlendIfRange([10, 10, 200, 200]));
fn a_gradient_offset_drag_starts_from_the_shown_offset_and_rebases_on_another_instance() {
let offset = |draft: &LayerStyleDraft, n: u32| draft.style.effect(EffectId(n)).and_then(|e| e.params.get("offset").cloned());
let size = [200.0, 100.0];
let mut draft = LayerStyleDraft::new(style_with(&[(1, EffectKind::GradientOverlay), (2, EffectKind::GradientOverlay)]));
draft.page = LayerStylePage::Effect(EffectId(1));
assert!(draft.drags_gradient());
// A press writes nothing; the default offset is shown.
assert!(!draft.drag_gradient(true, [0.0, 0.0], size));
assert!(draft.gradient_drag.is_some());
assert_eq!(offset(&draft, 1), Some(StyleValue::Point([0.0, 0.0])));
// 50 px over 200 and 10 px over 100.
assert!(draft.drag_gradient(false, [50.0, 10.0], size));
assert_eq!(offset(&draft, 1), Some(StyleValue::Point([0.25, 0.1])));
// Another instance, selected mid-press, starts from its own shown offset at the travel so far.
set_offset(&mut draft, 2, [1.0, -1.0]);
draft.page = LayerStylePage::Effect(EffectId(2));
assert!(!draft.drag_gradient(false, [50.0, 10.0], size));
assert_eq!(draft.gradient_drag.map(|d| d.instance()), Some(EffectId(2)));
assert!(draft.drag_gradient(false, [70.0, 10.0], size));
assert_eq!(offset(&draft, 2), Some(StyleValue::Point([1.1, -1.0])));
assert_eq!(offset(&draft, 1), Some(StyleValue::Point([0.25, 0.1])));
// Clamped to ±4 and rounded to 0.001.
assert!(draft.drag_gradient(false, [100_000.0, -1.0 / 3.0 * 100.0 + 10.0], size));
assert_eq!(offset(&draft, 2), Some(StyleValue::Point([4.0, -1.333])));
draft.end_drag();
assert!(draft.gradient_drag.is_none());
// A stored offset beyond ±4 starts from the clamp; one that is not finite from the default.
set_offset(&mut draft, 2, [9.0, 0.0]);
assert!(!draft.drag_gradient(true, [0.0, 0.0], size));
assert!(draft.drag_gradient(false, [-20.0, 0.0], size));
assert_eq!(offset(&draft, 2), Some(StyleValue::Point([3.9, 0.0])));
draft.end_drag();
set_offset(&mut draft, 2, [f64::NAN, 0.0]);
assert!(!draft.drag_gradient(true, [0.0, 0.0], size));
assert!(matches!(offset(&draft, 2), Some(StyleValue::Point([x, _])) if x.is_nan()));
assert!(draft.drag_gradient(false, [20.0, 0.0], size));
assert_eq!(offset(&draft, 2), Some(StyleValue::Point([0.1, 0.0])));
// Other pages are not dragged.
draft.page = LayerStylePage::Blending;
assert!(!draft.drag_gradient(true, [10.0, 10.0], size));
}
// A `StyleValue::Other` key no field shows survives `set_param`, `toggle` and
+35 -24
View File
@@ -3,10 +3,10 @@
use std::borrow::Cow;
use std::collections::HashMap;
use craft_color::gradient::GradientStops;
use craft_theme::{Srgba, TypeRole};
use craft_ui::contract::{CommandSet as _, Entry, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::{Divider, Text};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::{Env, Label};
@@ -48,9 +48,6 @@ pub struct LayerStyleOutput {
/// A style preset was picked on the Styles page (its key): the host looks it up and calls
/// [`LayerStyleDraft::apply_preset`].
pub apply_style: Option<String>,
/// New Style… was pressed: the host asks for a name and saves the enabled instances and the blend mode and
/// opacities as a preset.
pub new_style: bool,
/// Make Default on an effect page: the kind and the page's shown values, to keep as the user's default for new
/// instances of the kind.
pub make_default: Option<(EffectKind, StyleParams)>,
@@ -103,8 +100,8 @@ impl LayerStyleOutput {
/// - A page change is reported in [`LayerStyleOutput::page`] and drawn once the host has applied it. The page drawn in
/// the pass of a click is the one the click left, so its fields see their focus loss and commit what was typed
/// before the page changes.
/// - The page title is the effect's name, plain (the Styles page's title carries New Style…). The Preview check box
/// is the host's, in the button column under OK and Cancel (Photoshop's place), over [`LayerStyleDraft::preview`].
/// - The page title is the effect's name, plain. New Style… and the Preview check box are the host's, in the button
/// column under OK and Cancel (Photoshop's place), the check over [`LayerStyleDraft::preview`].
/// - The Styles page ([`StylePresets`]), the Blending Options page, or an effect page drawn from the kind's
/// [`EffectSpec`].
/// - Use Global Light: on an effect that uses it, the Angle edits the shared light angle of every such effect
@@ -130,7 +127,7 @@ pub struct LayerStyleDialog<'a> {
user_contours: &'a [Contour],
sampler: Option<SharedSampler>,
style_presets: Option<StylePresets<'a>>,
gradient_presets: &'a [(String, craft_color::gradient::GradientStops)],
gradient_presets: &'a [(String, GradientStops)],
}
impl<'a> LayerStyleDialog<'a> {
@@ -152,8 +149,8 @@ impl<'a> LayerStyleDialog<'a> {
}
}
/// The gradient presets a Gradient field's select offers, by name.
pub fn gradient_presets(mut self, presets: &'a [(String, craft_color::gradient::GradientStops)]) -> Self {
/// The gradient presets a Gradient field's select offers, by name. Without presets the field shows only the editor.
pub fn gradient_presets(mut self, presets: &'a [(String, GradientStops)]) -> Self {
self.gradient_presets = presets;
self
}
@@ -204,7 +201,7 @@ impl<'a> LayerStyleDialog<'a> {
self
}
/// The Styles page's presets; without them the page shows only New Style….
/// The Styles page's presets; without them the page shows only its title.
pub fn style_presets(mut self, presets: StylePresets<'a>) -> Self {
self.style_presets = Some(presets);
self
@@ -224,8 +221,8 @@ impl<'a> LayerStyleDialog<'a> {
user_contours,
sampler,
style_presets,
gradient_presets: _,
} = self; // P3(dialogs-w7): dl.K53
gradient_presets,
} = self;
let env = Env::of(ui);
let words = env.words::<LayerStyleWords>();
let contour_words = env.words::<ContourWords>();
@@ -259,6 +256,7 @@ impl<'a> LayerStyleDialog<'a> {
patterns,
user_contours,
sampler: sampler.as_ref(),
gradient_presets,
channel_names,
words: &words,
contour_words: &contour_words,
@@ -275,7 +273,6 @@ impl<'a> LayerStyleDialog<'a> {
blend_if_channel: (next.blend_if_channel != draft.blend_if_channel).then_some(next.blend_if_channel),
pick_color: extras.pick_color,
apply_style: extras.apply_style,
new_style: extras.new_style,
make_default: extras.make_default,
reset_to_default: extras.reset_to_default,
contour_action: extras.contour_action,
@@ -287,8 +284,30 @@ impl<'a> LayerStyleDialog<'a> {
/// Answers a [`ColorRequest`] the dialog made: sets the colour parameter its key names (`"fx2/color"`; the instance
/// id, a slash, the parameter key) to `color`. Returns false, changing nothing, for a key that names no instance of
/// `draft`.
///
/// A key `"fx2/stops/1"` names colour stop 1 of the gradient `stops` of instance `fx2`: the stop takes the
/// colour's red, green and blue and keeps its alpha, location, midpoint and tag. The instance's shown gradient is
/// its own `stops`, else the spec default. A bad index changes nothing and returns false.
pub fn set_color(draft: &mut LayerStyleDraft, key: &str, color: Srgba) -> bool {
Self::set_param_by_key(draft, key, StyleValue::Color(color))
match key.split_once('/').and_then(|(id, field)| Some((id, field.strip_prefix("stops/")?))) {
Some((id, index)) => Self::set_stop_color(draft, id, index, color),
None => Self::set_param_by_key(draft, key, StyleValue::Color(color)),
}
}
fn set_stop_color(draft: &mut LayerStyleDraft, id: &str, index: &str, color: Srgba) -> bool {
let Some(id) = EffectId::from_key(id) else { return false };
let Some(instance) = draft.style.effect(id) else { return false };
let Ok(index) = index.parse::<usize>() else { return false };
let shown = instance.params.over(&EffectSpec::photoshop(instance.kind).defaults);
let Some(StyleValue::Gradient(stops)) = shown.get("stops") else { return false };
let mut stops = stops.clone();
let Some(stop) = stops.color.get_mut(index) else { return false };
stop.color.r = color.r;
stop.color.g = color.g;
stop.color.b = color.b;
draft.set_param(id, "stops", StyleValue::Gradient(stops));
true
}
/// Answers a [`ContourRequest`] the dialog made: sets the contour parameter its key names to `contour` (the editor's
@@ -317,6 +336,7 @@ struct PageEnv<'a> {
patterns: &'a [PresetRow<String>],
user_contours: &'a [Contour],
sampler: Option<&'a SharedSampler>,
gradient_presets: &'a [(String, GradientStops)],
channel_names: &'a [String],
words: &'a LayerStyleWords,
contour_words: &'a ContourWords,
@@ -328,7 +348,6 @@ struct PageEnv<'a> {
struct Extras {
pick_color: Option<ColorRequest>,
apply_style: Option<String>,
new_style: bool,
make_default: Option<(EffectKind, StyleParams)>,
reset_to_default: Option<EffectId>,
contour_action: Option<ContourAction>,
@@ -402,6 +421,7 @@ impl Work {
patterns: env.patterns,
user_contours: env.user_contours,
sampler: env.sampler,
gradient_presets: env.gradient_presets,
words,
contour_words: env.contour_words,
units: env.units,
@@ -419,7 +439,6 @@ impl Work {
(LayerStylePage::Styles, _) => {
let out = styles_page(ui, presets, words);
self.extras.apply_style = out.apply_style;
self.extras.new_style = out.new_style;
}
}
}
@@ -436,11 +455,3 @@ fn page_title(page: LayerStylePage, draft: &LayerStyleDraft, words: &LayerStyleW
LayerStylePage::Styles => words.styles.clone(),
}
}
/// A page title in the title role with `end` at the row's end.
pub(super) fn title_row(ui: &mut Ui, title: Label, mut end: impl FnMut(&mut Ui)) {
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
Text::new(title.clone()).role(TypeRole::Title).show(ui);
end(ui);
});
}
+194 -34
View File
@@ -1,21 +1,29 @@
//! [`HostedLayerStyle`]: the Layer Style dialog on the dialog host, framed with its buttons and Preview box.
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
use craft_behavior::{Metrics, Sense};
use craft_color::gradient::GradientStops;
use craft_theme::Srgba;
use craft_ui::contract::{Bind, Entry};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::choice::SwatchMetrics;
use craft_ui::contract::{Bind, CanvasGesture, Common, Component, Cx, DisabledLook, Entry, MeasureCx, PaintUi, Props as _, Role, Sampler as _, Show as _};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::patterns::form_dialogs::FormDialog;
use craft_ui::patterns::presets::{PresetRow, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::requests::ColorRequest;
use egui::{Context, Rect, Ui};
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::style::{ComponentStyle, StyleCx};
use egui::{Context, Rect, Response, Ui, Vec2};
use super::contour::SharedSampler;
use super::labels::LayerStyleWords;
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput, StylePresets};
use crate::layer_style::{Contour, EffectId, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, StyleParams};
use crate::layer_style::{
Contour, EffectId, EffectKind, EffectSpec, FieldKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue,
};
/// What the open Layer Style dialog asks of the app in a pass; [`HostedLayerStyle::take_asks`] hands them over in the
/// order they came.
@@ -42,11 +50,10 @@ pub enum LayerStyleAsk {
impl LayerStyleOutput {
/// The asks of this pass, in the order [`LayerStyleAsk`] lists them.
fn asks(self) -> impl Iterator<Item = LayerStyleAsk> {
let LayerStyleOutput { pick_color, apply_style, new_style, make_default, reset_to_default, contour_action, edit_contour, .. } = self;
let LayerStyleOutput { pick_color, apply_style, make_default, reset_to_default, contour_action, edit_contour, .. } = self;
[
pick_color.map(LayerStyleAsk::PickColor),
apply_style.map(LayerStyleAsk::ApplyStyle),
new_style.then_some(LayerStyleAsk::NewStyle),
make_default.map(|(kind, params)| LayerStyleAsk::MakeDefault(kind, params)),
reset_to_default.map(LayerStyleAsk::ResetToDefault),
contour_action.map(LayerStyleAsk::Contour),
@@ -60,6 +67,75 @@ impl LayerStyleOutput {
/// Paints a style preset's thumbnail.
type Thumb = dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send;
/// Paints the preview swatch beside the footer buttons from the draft.
type PreviewPaint = dyn Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync;
/// The style of the preview swatch: a square as tall as a colour swatch.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct PreviewSwatchStyle {
#[style(metrics)]
metrics: Metrics,
/// The side of the square.
side: f32,
}
/// The preview swatch: the host's painting of the draft's style, in a square. It shows a picture and takes no input.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(content_painter, sample = PreviewSwatch::sample)]
struct PreviewSwatch<'a> {
#[common]
common: Common,
paint: &'a PreviewPaint,
draft: &'a LayerStyleDraft,
}
impl<'a> PreviewSwatch<'a> {
/// A swatch named `label` that `paint` fills from `draft`.
fn new(label: impl Into<Label>, paint: &'a PreviewPaint, draft: &'a LayerStyleDraft) -> Self {
PreviewSwatch { common: Common::new(), paint, draft }.label(label)
}
}
impl PreviewSwatch<'static> {
/// A swatch of the default style, for the suite.
fn sample() -> Self {
static DRAFT: LazyLock<LayerStyleDraft> = LazyLock::new(LayerStyleDraft::default);
static PAINT: LazyLock<Box<PreviewPaint>> = LazyLock::new(|| Box::new(|cx, rect, _| cx.checker(rect)));
PreviewSwatch::new("Preview", &**PAINT, &DRAFT)
}
}
impl Component for PreviewSwatch<'_> {
const DISABLED: DisabledLook = DisabledLook::Faded;
const ROLE: Role = Role::IMAGE;
const OVERLAYS: bool = false;
const PARTS: bool = false;
const STOPS: bool = false;
type Style = PreviewSwatchStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: PreviewSwatchStyleKey) -> PreviewSwatchStyle {
PreviewSwatchStyle { metrics: Metrics::new(), side: SwatchMetrics::of(cx).side }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::splat(cx.style.side)
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
(self.paint)(&ui.content_painter(cx), cx.rect, self.draft);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// The Layer Style dialog the [`DialogHost`](craft_ui::dialog::DialogHost) owns: the [`LayerStyleDialog`] body over a
/// draft the host keeps, in a form dialog with OK and Cancel beside the body (Alt turns Cancel into Reset) and the
/// Preview box under them. Style edits and view changes go into the draft; what the page asks of the app waits in
@@ -84,6 +160,9 @@ pub struct HostedLayerStyle {
user_contours: Vec<Contour>,
sampler: Option<SharedSampler>,
styles: Option<(Vec<PresetRow<String>>, Box<Thumb>)>,
gradient_presets: Vec<(String, GradientStops)>,
canvas: Option<egui::Id>,
preview_thumb: Option<Arc<PreviewPaint>>,
asks: Vec<LayerStyleAsk>,
comparing: bool,
#[cfg(feature = "screen-testing")]
@@ -110,6 +189,9 @@ impl HostedLayerStyle {
user_contours: Vec::new(),
sampler: None,
styles: None,
gradient_presets: Vec::new(),
canvas: None,
preview_thumb: None,
asks: Vec::new(),
comparing: false,
#[cfg(feature = "screen-testing")]
@@ -172,24 +254,24 @@ impl HostedLayerStyle {
/// The canvas the dialog's offset drag works on: while the dialog is modal its pointer presses keep their canvas.
#[must_use]
pub fn canvas(self, canvas: egui::Id) -> Self {
let _ = canvas;
todo!("dl.K53")
pub fn canvas(mut self, canvas: egui::Id) -> Self {
self.canvas = Some(canvas);
self
}
/// [`LayerStyleDialog::gradient_presets`].
#[must_use]
pub fn gradient_presets(self, presets: Vec<(String, GradientStops)>) -> Self {
let _ = presets;
todo!("dl.K53")
pub fn gradient_presets(mut self, presets: Vec<(String, GradientStops)>) -> Self {
self.gradient_presets = presets;
self
}
/// The painter of the preview swatch: `paint` draws the draft's style into the swatch rect.
// P3(dialogs-w7): dl.K53 `HostedLayerStyle::preview_thumb`
/// The painter of the preview swatch: `paint` draws the draft's style into the swatch rect. Without one the footer
/// has no swatch.
#[must_use]
pub fn preview_thumb(self, paint: impl Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync + 'static) -> Self {
let _ = (self, paint);
todo!("dl.K53")
pub fn preview_thumb(mut self, paint: impl Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync + 'static) -> Self {
self.preview_thumb = Some(Arc::new(paint));
self
}
/// The draft the dialog shows: the app previews from it.
@@ -248,24 +330,45 @@ impl StackDialog for HostedLayerStyle {
user_contours,
sampler,
styles,
gradient_presets,
canvas,
preview_thumb,
asks,
comparing,
#[cfg(feature = "screen-testing")]
facts,
..
} = self;
let new_style = Env::of(ui).words::<LayerStyleWords>().new_style.clone();
// The footer paints beside the form's `&mut` draft, so it reads a copy taken at the start of the pass.
let snapshot = preview_thumb.as_ref().map(|_| draft.clone());
let swatch_label = label.clone();
// The draft holds Preview: the box edits a copy, written back only when the box changed it, so a Reset that
// restores the draft keeps the restored Preview.
let previewing = draft.preview;
let mut preview = previewing;
let shown = FormDialog::new(label.clone(), Bind::bound(&mut *draft)).opened(Bind::bound(open)).preview(Some(Bind::bound(&mut preview))).show(
ui,
|ui, _, draft| {
let shown = FormDialog::new(label.clone(), Bind::bound(&mut *draft))
.opened(Bind::bound(open))
.preview(Some(Bind::bound(&mut preview)))
.extra_buttons([FooterButton::new(new_style, DialogRole::Other)])
.footer_extra(|ui| {
if let (Some(paint), Some(draft)) = (preview_thumb.as_deref(), snapshot.as_ref()) {
PreviewSwatch::new(swatch_label.clone(), paint, draft).show(ui);
}
})
.show(ui, |ui, cx, draft| {
if let Some(canvas) = *canvas {
cx.keep_view_open(canvas);
if draft.drags_shadow() || draft.drags_gradient() {
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
}
}
let mut body = LayerStyleDialog::new(label.clone(), draft, channel_names.as_slice())
.blend_modes(blend_modes.as_slice())
.patterns(patterns.as_slice())
.user_contours(user_contours.as_slice())
.shared_sampler(sampler.clone());
.shared_sampler(sampler.clone())
.gradient_presets(gradient_presets.as_slice());
if let Some(specs) = specs.as_deref() {
body = body.specs(specs);
}
@@ -286,8 +389,11 @@ impl StackDialog for HostedLayerStyle {
}
asks.extend(out.asks());
true
},
);
});
// `picked` is this pass's own press: a second pass in the same frame sees none and queues nothing.
if shown.picked == Some(2) {
asks.push(LayerStyleAsk::NewStyle);
}
if preview != previewing {
draft.preview = preview;
}
@@ -300,23 +406,77 @@ impl StackDialog for HostedLayerStyle {
Some(KEY)
}
fn confirm(&mut self, ctx: &Context) -> Option<LayerStyle> {
let _ = ctx;
todo!("dl.K53")
fn confirm(&mut self, _: &Context) -> Option<LayerStyle> {
Some(self.draft.style.clone())
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K53")
let page = match self.draft.page {
LayerStylePage::Styles => "styles".to_owned(),
LayerStylePage::Blending => "blendingOptions".to_owned(),
LayerStylePage::Effect(id) => id.key(),
};
let effects: Vec<_> =
self.draft.style.effects.iter().map(|e| serde_json::json!({ "id": e.id.key(), "kind": e.kind.key(), "on": e.on })).collect();
Some(serde_json::json!({ "page": page, "preview": self.draft.preview, "effects": effects }))
}
fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K53")
fn set_json_field(&mut self, _: &Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let rejected = || Err(FieldRefusal::Rejects(&value).message(field));
match field {
"page" => {
let Some(name) = value.as_str() else { return rejected() };
match name {
"styles" => self.draft.page = LayerStylePage::Styles,
"blendingOptions" => self.draft.page = LayerStylePage::Blending,
_ => {
if let Some(id) = EffectId::from_key(name).filter(|id| self.draft.style.effect(*id).is_some()) {
self.draft.page = LayerStylePage::Effect(id);
} else if let Some(kind) = EffectKind::from_key(name) {
self.draft.open_on(kind);
} else {
return rejected();
}
}
}
Ok(())
}
"preview" => {
let Some(on) = value.as_bool() else { return rejected() };
self.draft.preview = on;
Ok(())
}
"editContour" => {
let id = value.get("effect").and_then(serde_json::Value::as_str).and_then(EffectId::from_key);
let key = value.get("key").and_then(serde_json::Value::as_str);
let (Some(id), Some(key)) = (id, key) else { return rejected() };
let Some(instance) = self.draft.style.effect(id) else { return rejected() };
let owned;
let spec = match self.specs.as_ref().and_then(|specs| specs.iter().find(|spec| spec.kind == instance.kind)) {
Some(spec) => spec,
None => {
owned = EffectSpec::photoshop(instance.kind);
&owned
}
};
if !spec.field(key).is_some_and(|f| matches!(f.kind, FieldKind::Contour { .. })) {
return rejected();
}
let shown = instance.params.over(&spec.defaults);
let contour = match shown.get(key) {
Some(StyleValue::Contour(contour)) => contour.clone(),
_ => Contour::linear(),
};
self.asks.push(LayerStyleAsk::EditContour(ContourRequest::new(format!("{}/{key}", id.key()), contour)));
Ok(())
}
"effects" => Err(FieldRefusal::ReadOnly.message(field)),
_ => Err(FieldRefusal::Unknown.message(field)),
}
}
fn cancelled(&mut self, ctx: &Context) {
let _ = ctx;
todo!("dl.K53")
fn cancelled(&mut self, _: &Context) {
self.draft.end_drag();
}
#[cfg(feature = "screen-testing")]
+2 -4
View File
@@ -56,8 +56,7 @@ craft_ui::words! {
range: "layerStyle.fieldRange" = "Range";
position: "layerStyle.fieldPosition" = "Position";
overprint: "layerStyle.fieldOverprint" = "Overprint";
from: "layerStyle.fieldFrom" = "From";
to: "layerStyle.fieldTo" = "To";
gradient: "layerStyle.fieldGradient" = "Gradient";
reverse: "layerStyle.fieldReverse" = "Reverse";
style: "layerStyle.fieldStyle" = "Style";
scale: "layerStyle.fieldScale" = "Scale";
@@ -160,8 +159,7 @@ impl LayerStyleWords {
"range" | "contourRange" => &self.range,
"position" => &self.position,
"overprint" => &self.overprint,
"from" => &self.from,
"to" => &self.to,
"stops" => &self.gradient,
"reverse" => &self.reverse,
"style" => &self.style,
"scale" => &self.scale,
+49 -4
View File
@@ -1,6 +1,8 @@
//! The effect page: one field per entry of the effect's [`EffectSpec`], drawn by kind.
use craft_behavior::{EditEvent, EditEvents, Mixed, NumberCodec};
use craft_color::gradient::GradientStops;
use craft_color::ui::gradient::GradientEditor;
use craft_theme::variant::Tone;
use craft_theme::{Srgba, TypeRole};
use craft_ui::buttons::Button;
@@ -9,7 +11,7 @@ use craft_ui::contract::{Bind, EditResponse, Entry, Props as _, Show as _, ShowC
use craft_ui::display::Text;
use craft_ui::form::{Field, FieldGroup, SliderField};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::Row;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::patterns::presets::{PresetPicker, PresetRow, PresetState};
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{Label, UnitKind, Units};
@@ -87,6 +89,7 @@ pub(super) struct PageInput<'a> {
pub patterns: &'a [PresetRow<String>],
pub user_contours: &'a [Contour],
pub sampler: Option<&'a SharedSampler>,
pub gradient_presets: &'a [(String, GradientStops)],
pub words: &'a LayerStyleWords,
pub contour_words: &'a ContourWords,
pub units: &'a Units,
@@ -123,6 +126,9 @@ pub(super) struct PageOutput {
/// - `Color`: a `Swatch`; a click or Space reports `pick_color`.
/// - `Blend`: a `Select` over `blend_modes`; a value missing from the list shows as its key.
/// - `Choice`: a `Select` over the options; a missing value shows the first.
/// - `Gradient`: a `GradientEditor` under a `Select` of the host's gradient presets (none without presets), with Custom
/// first while the stops match no preset; a pick is one edit of the stops, an editor click on a stop's colour reports
/// `pick_color` keyed `"{instance id}/{parameter key}/{stop index}"`.
/// - `GradientMethod`: Smooth, Perceptual, Linear, Classic, with Custom first while the value names none of them.
/// - `Pattern`: a `PresetPicker` over `patterns`; an empty value shows the first pattern and reports it as
/// `fill_default`, not as an edit.
@@ -257,8 +263,47 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
push_edit(&mut out.edit, style_edit(&response, input.style, |v| param(StyleValue::Text(v.clone()))));
}
}
// P3(dialogs-w7): dl.K53 — the preset select over the stop bar.
FieldKind::Gradient => todo!("dl.K53"),
FieldKind::Gradient => {
let stops = match shown.get(key) {
Some(StyleValue::Gradient(stops)) => stops.clone(),
_ => GradientStops::default(),
};
let presets = input.gradient_presets;
let matching = presets.iter().find(|(_, preset)| *preset == stops).map(|(name, _)| name.as_str());
let shown_field = Field::new(label.clone())
.id_salt(key)
.show(ui, |ui, _| {
Stack::new()
.show(ui, |ui, _| {
// The select offers a choice only with presets; "Custom" stands for stops that match none.
let preset = (!presets.is_empty()).then(|| {
let mut entries = Vec::new();
if matching.is_none() {
entries.push(Entry::new(String::new(), words.custom.clone()));
}
entries.extend(presets.iter().map(|(name, _)| Entry::new(name.clone(), Label::from(name.clone()))));
Select::new(label.clone(), Bind::given(matching.unwrap_or_default().to_owned()), &entries).show(ui)
});
let editor = GradientEditor::new(label.clone(), Bind::given(stops.clone())).show(ui);
(preset, editor)
})
.inner
})
.inner
.flatten();
if let Some((preset, editor)) = shown_field {
if let Some(preset) = preset {
let chosen = |name: &String| presets.iter().find(|(n, _)| n == name).map_or_else(|| stops.clone(), |(_, preset)| preset.clone());
push_edit(&mut out.edit, style_edit(&preset, input.style, |name| param(StyleValue::Gradient(chosen(name)))));
}
push_edit(&mut out.edit, style_edit(&editor.edit, input.style, |v| param(StyleValue::Gradient(v.clone()))));
if let Some(stop) = editor.color_requested {
let mut request = stop.request;
request.key = format!("{}/{key}/{}", id.key(), stop.index);
out.pick_color = Some(request.title(words.color_picker_title.clone()));
}
}
}
FieldKind::GradientMethod => {
const METHODS: [&str; 4] = ["smooth", "perceptual", "linear", "classic"];
let stored = text_of(shown.get(key)).unwrap_or("custom");
@@ -345,7 +390,7 @@ fn first_invalid<'s>(spec: &'s EffectSpec, params: &StyleParams) -> Option<&'s E
FieldKind::Slider { .. } | FieldKind::Angle => wrong(&field.key, |v| matches!(v, StyleValue::Number(_))),
FieldKind::Check => wrong(&field.key, |v| matches!(v, StyleValue::Bool(_))),
FieldKind::Color => wrong(&field.key, |v| matches!(v, StyleValue::Color(_))),
FieldKind::Gradient => wrong(&field.key, |v| matches!(v, StyleValue::Gradient(_))), // P3(dialogs-w7): dl.K53
FieldKind::Gradient => wrong(&field.key, |v| matches!(v, StyleValue::Gradient(_))),
FieldKind::Blend | FieldKind::Choice(_) | FieldKind::GradientMethod | FieldKind::Pattern => {
wrong(&field.key, |v| matches!(v, StyleValue::Text(_)))
}
+29 -10
View File
@@ -2,8 +2,11 @@
//! document, one story per effect page and the Styles page. Each opens a [`HostedLayerStyle`] on the story's dialog
//! host from a button.
use craft_color::gradient::{ColorStop, GradientStops};
use craft_theme::Srgba;
use craft_ui::contract::Entry;
use craft_ui::dialog::stories::hosted;
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut, blend_entries};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
@@ -25,7 +28,9 @@ craft_ui::words! {
black: "layerStyleStory.black" = "K";
mode_normal: "layerStyleStory.modeNormal" = "Normal";
mode_dissolve: "layerStyleStory.modeDissolve" = "Dissolve";
mode_darken: "layerStyleStory.modeDarken" = "Darken";
mode_multiply: "layerStyleStory.modeMultiply" = "Multiply";
mode_lighten: "layerStyleStory.modeLighten" = "Lighten";
mode_screen: "layerStyleStory.modeScreen" = "Screen";
mode_overlay: "layerStyleStory.modeOverlay" = "Overlay";
mode_soft_light: "layerStyleStory.modeSoftLight" = "Soft Light";
@@ -35,21 +40,34 @@ craft_ui::words! {
style_group: "layerStyleStory.styleGroup" = "Basics";
style_soft: "layerStyleStory.styleSoft" = "Soft";
style_hard: "layerStyleStory.styleHard" = "Hard";
gradient_sunset: "layerStyleStory.gradientSunset" = "Sunset";
gradient_sky: "layerStyleStory.gradientSky" = "Sky";
}
}
/// The blend modes the story host offers, with a separator between groups.
/// The blend modes the story host offers; the separators between groups come from the modes' positions.
fn blend_modes(words: &LayerStyleStoryWords) -> Vec<Entry<String>> {
let entry = |label: &Label| Entry::new(label.as_str().to_owned(), label.clone());
let modes = [
(&words.mode_normal, BlendShortcut::Normal),
(&words.mode_dissolve, BlendShortcut::Dissolve),
(&words.mode_darken, BlendShortcut::Darken),
(&words.mode_multiply, BlendShortcut::Multiply),
(&words.mode_lighten, BlendShortcut::Lighten),
(&words.mode_screen, BlendShortcut::Screen),
(&words.mode_overlay, BlendShortcut::Overlay),
(&words.mode_soft_light, BlendShortcut::SoftLight),
];
// A mode's key is its shown name, as before.
let keys: Vec<BlendKeyEntry<String>> = modes.iter().map(|(label, shortcut)| BlendKeyEntry::new(label.as_str().to_owned(), *shortcut)).collect();
blend_entries(&keys, |entry| Label::from(entry.key.clone()))
}
/// Two gradient presets for the Gradient Overlay story's select.
fn gradient_presets(words: &LayerStyleStoryWords) -> Vec<(String, GradientStops)> {
let stop = |location: f32, hex: &str| ColorStop::new(location, Srgba::from_hex(hex).unwrap_or(Srgba::BLACK));
vec![
entry(&words.mode_normal),
entry(&words.mode_dissolve),
Entry::separator(),
entry(&words.mode_multiply),
Entry::separator(),
entry(&words.mode_screen),
entry(&words.mode_overlay),
entry(&words.mode_soft_light),
(words.gradient_sunset.as_str().to_owned(), GradientStops::new(vec![stop(0.0, "#ff7a18"), stop(1.0, "#af002d")])),
(words.gradient_sky.as_str().to_owned(), GradientStops::new(vec![stop(0.0, "#ffffff"), stop(1.0, "#2a7bde")])),
]
}
@@ -88,6 +106,7 @@ fn host(ui: &mut Ui, data: &mut StoryData, start: impl FnOnce() -> LayerStyleDra
HostedLayerStyle::new("Layer Style", start(), names)
.blend_modes(blend_modes(&words))
.patterns(patterns(&words))
.gradient_presets(gradient_presets(&words))
.style_presets(style_rows(&words), |cx, rect, _| cx.checker(rect))
})
}
+6 -12
View File
@@ -1,12 +1,12 @@
//! The Styles page: the host's style presets in a [`PresetBrowser`] grid.
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Props as _, Show as _, clicked};
use craft_theme::TypeRole;
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::display::Text;
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use egui::{Rect, Ui};
use super::dialog::title_row;
use super::labels::LayerStyleWords;
/// The rows of styles the Styles page shows before the grid scrolls: the user's style library can grow long, and the
@@ -37,18 +37,12 @@ pub(super) struct StylesOutput {
/// [`LayerStyleDraft::apply_preset`](crate::layer_style::LayerStyleDraft::apply_preset); the document is untouched
/// until OK).
pub apply_style: Option<String>,
/// New Style… was pressed.
pub new_style: bool,
}
/// Draws the page: the title with the "New Style…" button at its end, then the browser. Without presets the page
/// shows only the button.
/// Draws the page: the title, then the browser. Without presets the page shows only the title.
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&StylePresets<'_>>, words: &LayerStyleWords) -> StylesOutput {
let mut new_style = false;
title_row(ui, words.styles.clone(), |ui| {
new_style = clicked(&Button::new(words.new_style.clone()).id_salt("new-style").show(ui));
});
let mut out = StylesOutput { apply_style: None, new_style };
Text::new(words.styles.clone()).role(TypeRole::Title).show(ui);
let mut out = StylesOutput { apply_style: None };
if let Some(StylePresets { rows, thumb }) = presets {
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), rows)
.thumb(move |cx, rect, info| thumb(cx, rect, info))