effects-w6: net change of 1 commits

- effects-w6: written by an agent
This commit is contained in:
bflatastic
2026-11-21 23:32:17 +07:00
parent 59c4dd0cac
commit f2522ea2f2
3 changed files with 439 additions and 200 deletions
+134 -74
View File
@@ -5,21 +5,33 @@
//! Fields: `tones` (the effect's, always [`MAX_TONES`] while the dialog is open, the ones after
//! the first off), `skipSpot`, and `__tone`, the tone whose curve shows.
use craft::theme::Rgba;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Entry, Props as _, RowAlign, Show as _, ShowContainer as _};
use craft::ui::display::Picture;
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind};
use craft::ui::pickers::Select;
use craft::ui::text::HexField;
use egui::{Response, Ui};
use serde_json::{Map, Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_color::Color;
use vectorcraft_effects::addons::duotone::{MAX_TONES, tone_curve_points};
use super::effect::{curve_graph, points_text};
use super::form;
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
use super::effect_adjust::{curve_body, json_value};
// PLAN: assumed `EffectCx` is declared in `effect_params.rs` (ef.C3, effects-w4).
use super::effect_params::EffectCx;
use crate::panels::c32;
/// A curve's text: linear, inverse.
const LINEAR: &str = "0,0 100,100";
const INVERSE: &str = "0,100 100,0";
/// Width of the label column.
const LABEL_W: f32 = 84.0;
/// The dialog-only field that holds the tone whose curve shows.
const TONE: &str = "__tone";
/// A tone's colour (black when it has none that reads).
fn tone_color(tone: &Value) -> Color {
@@ -31,58 +43,92 @@ fn tone_color(tone: &Value) -> Color {
.unwrap_or(Color::BLACK)
}
/// The dialog's fields; returns nothing, the caller compares the values with those previewed.
pub(super) fn fields(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
let mut tones: Vec<Value> = d.fields.get("tones").and_then(Value::as_array).cloned().unwrap_or_default();
/// Fills `params["tones"]` up to [`MAX_TONES`] with tones that are off, once, as the dialog opens:
/// the rows write only what the user edits.
pub(super) fn pad_tones(params: &mut Map<String, Value>) {
let mut tones: Vec<Value> = params.get("tones").and_then(Value::as_array).cloned().unwrap_or_default();
tones.truncate(MAX_TONES);
while tones.len() < MAX_TONES {
tones.push(json!({"color": "#000000", "curve": LINEAR, "active": false}));
}
// The global and spot swatches a tone can be: (name, colour).
let swatches: Vec<(String, Color)> = app
.session
.active()
.map(|st| st.doc.swatches_iter().filter_map(|w| Some((w.name.clone(), st.doc.global_color(&w.name)?))).collect())
.unwrap_or_default();
let labels = [tl!("Tone 1"), tl!("Tone 2"), tl!("Tone 3"), tl!("Tone 4")];
let process = tl!("Process Color");
let names: Vec<&str> = std::iter::once(process).chain(swatches.iter().map(|(n, _)| n.as_str())).collect();
for (i, tone) in tones.iter_mut().enumerate() {
let Some(t) = tone.as_object_mut() else { continue };
ui.horizontal(|ui| {
let on = t.get("active").and_then(Value::as_bool).unwrap_or(true);
if widgets::check(ui, labels.get(i).copied().unwrap_or_default(), on, true) {
t.insert("active".into(), json!(!on));
}
tone_row(ui, (i, labels.get(i).copied().unwrap_or_default()), t, &swatches, &names);
});
}
ui.add_space(6.0);
widgets::subheader(ui, tl!("Curve"));
let picked = (d.f64("__tone", 0.0).max(0.0) as usize).min(MAX_TONES - 1);
ui.horizontal(|ui| {
let current = labels.get(picked).copied().unwrap_or_default();
if let Some(i) = widgets::dropdown_named(ui, "duotone-curve-tone", Some(tl!("Curve")), current, &labels, 120.0) {
d.fields.insert("__tone".into(), json!(i));
}
});
if let Some(t) = tones.get_mut(picked).and_then(Value::as_object_mut) {
curve_fields(ui, t);
}
d.fields.insert("tones".into(), Value::Array(tones));
ui.add_space(4.0);
form::check(ui, d, "skipSpot", tl!("Skip Objects with Spot Colors"));
params.insert("tones".into(), Value::Array(tones));
}
/// Tone `i`'s (named `name`) colour chip, its swatch (or Process Color) and, as a process colour,
/// its hex value.
fn tone_row(ui: &mut egui::Ui, (i, name): (usize, &str), t: &mut Map<String, Value>, swatches: &[(String, Color)], names: &[&str]) {
let color = tone_color(&Value::Object(t.clone()));
let (chip, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover());
widgets::paint_chip(ui, chip, &Paint::solid(color));
let swatch = t.get("swatch").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string);
let current = swatch.as_deref().unwrap_or(names.first().copied().unwrap_or_default());
if let Some(k) = widgets::dropdown_names_named(ui, ("duotone-swatch", i), Some(name), current, names, 130.0) {
/// The names of the tones, in order.
fn tone_labels() -> [&'static str; MAX_TONES] {
[tl!("Tone 1"), tl!("Tone 2"), tl!("Tone 3"), tl!("Tone 4")]
}
/// The tones in `fields`.
fn tones(fields: &DialogFields) -> Vec<Value> {
match json_value(fields, "tones") {
Some(Value::Array(tones)) => tones,
_ => Vec::new(),
}
}
/// The rows of the Duotone dialog: the tones, the curve of one of them and the option.
pub(super) fn params(cx: &EffectCx, _fields: &DialogFields) -> Vec<Param> {
let swatches = cx.swatches.clone();
vec![
Param::custom("tones", tl!("Tones"), move |ui, fields, _| tones_row(ui, fields, &swatches)).full_width(),
Param::section(tl!("Curve")),
Param::custom(TONE, tl!("Curve"), |ui, fields, _| curve_rows(ui, fields)).companions(["tones"]).full_width(),
Param::new("skipSpot", tl!("Skip Objects with Spot Colors"), ParamKind::bool(false)),
]
}
/// A row per tone; an edit writes the tones back.
fn tones_row(ui: &mut Ui, fields: &mut DialogFields, swatches: &[(String, Color)]) -> Response {
let mut tones = tones(fields);
let labels = tone_labels();
// The first entry is a process colour, the rest are the document's swatches.
let mut entries = vec![Entry::new(0usize, tl!("Process Color"))];
entries.extend(swatches.iter().enumerate().map(|(k, (name, _))| Entry::new(k + 1, name.clone())));
let mut changed = false;
let shown = Stack::new().fill_width().show(ui, |ui, _| {
for (i, tone) in tones.iter_mut().enumerate().take(MAX_TONES) {
changed |= tone_row(ui, (i, labels.get(i).copied().unwrap_or_default()), tone, swatches, &entries);
}
});
if changed {
fields.set("tones", FieldValue::Json(Value::Array(tones)));
}
shown.output
}
/// Tone `i`'s (named `name`) switch, colour chip, swatch (or Process Color) and, as a process colour,
/// its hex value. Returns whether it edited `tone`.
fn tone_row(ui: &mut Ui, (i, name): (usize, &'static str), tone: &mut Value, swatches: &[(String, Color)], entries: &[Entry<usize>]) -> bool {
let color = tone_color(tone);
let active = tone.get("active").and_then(Value::as_bool).unwrap_or(true);
let swatch = tone.get("swatch").and_then(Value::as_str).filter(|s| !s.is_empty());
let picked = swatch.and_then(|s| swatches.iter().position(|(n, _)| n == s)).map_or(0, |k| k + 1);
let chip = c32(&color);
let hex = Rgba::from_hex(&format!("#{}", color.to_hex().trim_start_matches('#'))).unwrap_or(Rgba::BLACK);
let (mut set_active, mut set_pick, mut set_hex) = (None, None, None);
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
if let Some(on) = Checkbox::new(Bind::given(active)).label(name).id_salt(("tone-on", i)).show(ui).value() {
set_active = Some(*on);
}
Picture::painter("", ThumbAspect::SQUARE, move |cx, rect| cx.data_shapes([egui::Shape::rect_filled(rect, 0.0, chip)])).show(ui);
if let Some(k) = Select::new(name, Bind::given(picked), entries).id_salt(("tone-swatch", i)).show(ui).value() {
set_pick = Some(*k);
}
if picked == 0 {
Field::new(name).side(HexField::hash_label()).id_salt(("tone-hex", i)).show(ui, |ui, _| {
if let Some(c) = HexField::hex(name, Bind::given(hex)).id_salt(("tone-hex-digits", i)).show(ui).value() {
set_hex = Some(c.to_hex());
}
});
}
});
let changed = set_active.is_some() || set_pick.is_some() || set_hex.is_some();
let Some(t) = tone.as_object_mut() else { return false };
if let Some(on) = set_active {
t.insert("active".into(), json!(on));
}
if let Some(k) = set_pick {
match k.checked_sub(1).and_then(|k| swatches.get(k)) {
Some((name, c)) => {
t.insert("swatch".into(), json!(name));
@@ -93,31 +139,45 @@ fn tone_row(ui: &mut egui::Ui, (i, name): (usize, &str), t: &mut Map<String, Val
}
}
}
if swatch.is_none()
&& let Some(hex) = widgets::hex_field_named(ui, ("duotone-hex", i), Some(name), color.to_hex().trim_start_matches('#'))
&& let Some(c) = Color::from_hex(&format!("#{hex}"))
{
if let Some(c) = set_hex.and_then(|hex| Color::from_hex(&hex)) {
t.insert("color".into(), json!(c.to_hex()));
t.remove("swatch");
}
changed
}
/// The picked tone's curve: the graph, its points as text, and Reset to Linear or to Inverse.
fn curve_fields(ui: &mut egui::Ui, t: &mut Map<String, Value>) {
let mut pts = tone_curve_points(t.get("curve"));
if curve_graph(ui, &mut pts, 100.0) {
t.insert("curve".into(), json!(points_text(&pts, 100.0)));
}
widgets::label_row(ui, tl!("Points"), LABEL_W, |ui| {
let mut text = t.get("curve").and_then(Value::as_str).unwrap_or(LINEAR).to_string();
if ui.add(egui::TextEdit::singleline(&mut text).desired_width(200.0)).changed() {
t.insert("curve".into(), json!(text));
}
});
ui.horizontal(|ui| {
for (label, curve) in [(tl!("Reset to Linear"), LINEAR), (tl!("Reset to Inverse"), INVERSE)] {
if widgets::flat_button(ui, label, 120.0).clicked() {
t.insert("curve".into(), json!(curve));
/// The picked tone's curve: which tone, the graph with its points as text, and Reset to Linear or to
/// Inverse.
fn curve_rows(ui: &mut Ui, fields: &mut DialogFields) -> Response {
let picked = (fields.int(TONE).unwrap_or(0).max(0) as usize).min(MAX_TONES - 1);
let mut tones = tones(fields);
let pts = tone_curve_points(tones.get(picked).and_then(|t| t.get("curve")));
let entries: Vec<Entry<usize>> = tone_labels().into_iter().enumerate().map(|(i, label)| Entry::new(i, label)).collect();
let (mut set_tone, mut set_curve) = (None, None);
let shown = Stack::new().fill_width().show(ui, |ui, _| {
Field::new(tl!("Curve")).show(ui, |ui, _| {
if let Some(i) = Select::new(tl!("Curve"), Bind::given(picked), &entries).id_salt("curve-tone").show(ui).value() {
set_tone = Some(*i);
}
}
});
// PLAN: the sheet has Duotone call `curve_row(100, ..)`; that row reads a top-level key and a tone's curve lives inside `tones`, so the shared graph-and-text body is called.
set_curve = curve_body(ui, 100, &pts).1;
Row::new().show(ui, |ui, _| {
for (label, curve) in [(tl!("Reset to Linear"), LINEAR), (tl!("Reset to Inverse"), INVERSE)] {
if Button::new(label).id_salt(curve).show(ui).clicked() {
set_curve = Some(curve.to_owned());
}
}
});
});
if let Some(i) = set_tone {
fields.set(TONE, i as i64);
}
if let Some(curve) = set_curve
&& let Some(t) = tones.get_mut(picked).and_then(Value::as_object_mut)
{
t.insert("curve".into(), json!(curve));
fields.set("tones", FieldValue::Json(Value::Array(tones)));
}
shown.output
}
+186
View File
@@ -0,0 +1,186 @@
//! The rows of the colour adjustment dialogs (Effect › Color Adjustments) and the curve row Curves
//! and Duotone share: a slider table with colour rails, the channel, Curves' graph with its points
//! as text, the target colour, Levels' gamma and the options.
use craft::imaging::ui::adjust::{AdjustField, AdjustSliders, AdjustTrack};
use craft::imaging::ui::{Curve, CurveEditor};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::form::Field;
use craft::ui::layout_components::Stack;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind};
use craft::ui::runtime::env::Label;
use craft::ui::style::DataColor;
use craft::ui::text::TextField;
use egui::{Color32, Response, Ui};
use serde_json::Value;
use vectorcraft_color::Color;
use vectorcraft_effects::addons::duotone::tone_curve_points;
use vectorcraft_effects::{curve_at, curve_points, default_params};
// PLAN: assumed `EffectCx` is declared in `effect_params.rs` (ef.C3, effects-w4).
use super::effect_params::{EffectCx, own_choices};
use crate::panels::c32;
/// A slider of a colour adjustment dialog: (effect, field, label, range, rail colour at 0..1).
type Slider = (&'static str, &'static str, &'static str, (f64, f64), fn(f32) -> Color32);
/// How many colours sample a rail: enough that the track reads as the rail's gradient.
const RAIL_STOPS: usize = 13;
fn rgb(r: f32, g: f32, b: f32) -> Color32 {
c32(&Color::rgb(r, g, b))
}
fn grey_rail(x: f32) -> Color32 {
rgb(x, x, x)
}
fn hue_rail(x: f32) -> Color32 {
c32(&Color::from_hsb(((x - 0.5) * 360.0).rem_euclid(360.0), 0.8, 0.9))
}
fn saturation_rail(x: f32) -> Color32 {
c32(&Color::from_hsb(0.0, x, 0.9))
}
fn temperature_rail(x: f32) -> Color32 {
rgb(0.35 + 0.65 * x, 0.55 + 0.05 * x, 1.0 - 0.8 * x)
}
fn tint_rail(x: f32) -> Color32 {
rgb(0.3 + 0.6 * x, 0.85 - 0.55 * x, 0.3 + 0.6 * x)
}
const SLIDERS: [Slider; 12] = [
("adjust.brightnessContrast", "brightness", "Brightness", (-100.0, 100.0), grey_rail),
("adjust.brightnessContrast", "contrast", "Contrast", (-100.0, 100.0), grey_rail),
("adjust.hueSaturation", "hue", "Hue", (-180.0, 180.0), hue_rail),
("adjust.hueSaturation", "saturation", "Saturation", (-100.0, 100.0), saturation_rail),
("adjust.hueSaturation", "lightness", "Lightness", (-100.0, 100.0), grey_rail),
("adjust.levels", "inputBlack", "Input Black", (0.0, 255.0), grey_rail),
("adjust.levels", "inputWhite", "Input White", (0.0, 255.0), grey_rail),
("adjust.levels", "outputBlack", "Output Black", (0.0, 255.0), grey_rail),
("adjust.levels", "outputWhite", "Output White", (0.0, 255.0), grey_rail),
("adjust.shiftToColor", "amount", "Amount", (0.0, 100.0), grey_rail),
("adjust.temperatureTint", "temperature", "Temperature", (-100.0, 100.0), temperature_rail),
("adjust.temperatureTint", "tint", "Tint", (-100.0, 100.0), tint_rail),
];
/// The value under `key` as JSON, in whatever form the dialog stored it: the one reader of the rows
/// that keep structured values (tones, corners, curve points).
pub(super) fn json_value(fields: &DialogFields, key: &str) -> Option<Value> {
serde_json::to_value(fields.get(key)?).ok()
}
/// The rows of adjustment `cx.id`: its slider table, then the channel, the curve, the target colour,
/// the gamma and the options, each when the effect's values have the key.
pub(super) fn params(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
let effect = cx.id.as_str();
let defaults = default_params(effect).unwrap_or_default();
let table: Vec<AdjustField> = SLIDERS
.iter()
.filter(|s| s.0 == effect)
.map(|&(_, key, label, (min, max), rail)| {
let stops = (0..RAIL_STOPS).map(|k| DataColor::new(rail(k as f32 / (RAIL_STOPS - 1) as f32))).collect();
AdjustField::new(key, tl!(label), min..=max, defaults.get(key).and_then(Value::as_f64).unwrap_or(min)).track(AdjustTrack::Colors(stops))
})
.collect();
let mut rows = Vec::new();
if !table.is_empty() {
let keys: Vec<&'static str> = table.iter().map(|f| f.key).collect();
rows.push(sliders_row(table).companions(keys));
}
if fields.contains("channel") {
let options = own_choices(effect, "channel", false).unwrap_or_default().into_iter().map(|(label, value)| (value.to_owned(), Label::from(label))).collect();
rows.push(Param::new("channel", tl!("Channel"), ParamKind::choice(options, None)));
}
if fields.contains("points") {
rows.push(curve_row(255, "points"));
}
if fields.contains("color") {
rows.push(Param::new("color", tl!("Color"), ParamKind::color(None)));
}
if fields.contains("gamma") {
rows.push(Param::new("gamma", tl!("Gamma"), ParamKind::number(Some(0.1), Some(10.0), 1.0, 0.01, 2)));
}
for (key, label) in [("colorize", tl!("Colorize")), ("preserveLightness", tl!("Preserve Lightness"))] {
if fields.contains(key) {
rows.push(Param::new(key, label, ParamKind::bool(false)));
}
}
rows
}
/// The slider table as one row over the `table`'s keys, which it reads and writes as numbers.
fn sliders_row(table: Vec<AdjustField>) -> Param {
Param::custom("sliders", tl!("Adjustments"), move |ui, fields, _| {
let values: Vec<f64> = table.iter().map(|f| fields.number(f.key).unwrap_or(f.default)).collect();
let edit = AdjustSliders::new(tl!("Adjustments"), &table, Bind::given(values)).show(ui);
if let Some(now) = edit.value() {
for (field, value) in table.iter().zip(now) {
fields.set(field.key, *value);
}
}
edit.response.clone()
})
.full_width()
}
/// The points of a curve of `levels` levels (0..1 each) from its stored value: the effect's own
/// reader of that scale.
// PLAN: the effects crate exports no reader of a given scale (`curve_points_on` is private to it); the two scales the dialogs use pick their exported reader.
fn curve_points_of(levels: u32, value: Option<&Value>) -> Vec<(f32, f32)> {
if levels == 100 { tone_curve_points(value) } else { curve_points(value) }
}
/// Curve points in level units as the `"x,y x,y …"` text of the effect's `points` and `curve` parameters.
fn points_text(pts: impl IntoIterator<Item = [f32; 2]>) -> String {
pts.into_iter().map(|[x, y]| format!("{},{}", x.round(), y.round())).collect::<Vec<_>>().join(" ")
}
/// A curve row over the points text under `key`, on a scale of 0..`levels`: the graph and the points
/// as text. Curves' (255) and, through [`curve_body`], each Duotone tone's (100).
pub(super) fn curve_row(levels: u32, key: &str) -> Param {
let key = key.to_owned();
let at = key.clone();
Param::custom(key, tl!("Curve"), move |ui, fields, _| {
let pts = curve_points_of(levels, json_value(fields, &at).as_ref());
let (response, text) = curve_body(ui, levels, &pts);
if let Some(text) = text {
fields.set(at.as_str(), FieldValue::Text(text));
}
response
})
.full_width()
}
/// The graph of the curve through `pts` (0..1 each; input across, output up) on a scale of 0..`levels`
/// and its points as text. Returns the body's response and the new points text when the graph or
/// the text was edited. The graph draws the curve the effect applies.
pub(super) fn curve_body(ui: &mut Ui, levels: u32, pts: &[(f32, f32)]) -> (Response, Option<String>) {
let scale = levels.max(1) as f32;
let curve = Curve::smooth(pts.iter().map(|&(x, y)| [(x * scale).round(), (y * scale).round()]).collect());
let text = points_text(pts.iter().map(|&(x, y)| [x * scale, y * scale]));
let mut edited = None;
let shown = Stack::new().fill_width().show(ui, |ui, _| {
// PLAN: the sheet names `CurveSampler::new`; the editor's `sampler` prop takes the closure itself.
let graph = CurveEditor::new(tl!("Curve"), Bind::given(curve.clone()))
.levels(levels)
.bars(false)
.fields(false)
.sampler(move |points: &[[f32; 2]]| {
let unit: Vec<(f32, f32)> = points.iter().map(|&[x, y]| (x / scale, y / scale)).collect();
(0..=levels).map(|k| curve_at(&unit, k as f32 / scale) * scale).collect()
})
.show(ui);
if let Some(points) = graph.value().and_then(Curve::points) {
edited = Some(points_text(points.iter().copied()));
}
Field::new(tl!("Points")).show(ui, |ui, _| {
if let Some(typed) = TextField::new(tl!("Points"), Bind::given(text.clone())).id_salt("points").show(ui).value() {
edited = Some(typed.clone());
}
});
});
(shown.output, edited)
}
+119 -126
View File
@@ -1,15 +1,30 @@
//! Free Distort's dialog body (Effect › Distort & Transform › Free Distort…): a box in the
//! proportions of the first selected object's bounds with a handle on each of its four corners.
//! Dragging a handle moves that corner. A handle focused by a click or Tab moves with the arrow
//! keys, and ten times as far with Shift. Reset puts every corner back on the box. The corners are
//! the effect's `corners` field, which the effect dialog previews and applies.
//! proportions of the first selected object's bounds with a handle on each of its four corners, as
//! the transform box's Distort mode draws them. Dragging a handle moves that corner; the keys of
//! the box move the picked one (an arrow a hundredth of the box side, ten times as far with Shift).
//! Reset puts every corner back on the box. The corners are the effect's `corners` field, which the
//! effect dialog previews and applies.
use egui::{Key, Modifiers, Pos2, Rect, Sense, Stroke, Vec2, vec2};
use craft::behavior::CanvasView;
use craft::behavior::geometry::quad::{BoxRules, BoxState, TransformMode};
use craft::behavior::kurbo::{Point, Rect as DocRect};
use craft::draw::ui::transform::TransformBox;
use craft::ui::buttons::Button;
use craft::ui::canvas::Canvas;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::Picture;
use craft::ui::layout_components::Stack;
use craft::ui::list::ThumbAspect;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param};
use craft::ui::primitives::{ContentPainterCx, PaintShape};
use craft::ui::runtime::env::Env;
use egui::{Response, Sense, vec2};
use serde_json::{Value, json};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::{VectorcraftApp, widgets};
use super::effect_adjust::json_value;
// PLAN: assumed `EffectCx` is declared in `effect_params.rs` (ef.C3, effects-w4).
use super::effect_params::EffectCx;
use crate::VectorcraftApp;
/// The Free Distort effect.
pub(crate) const FREE_DISTORT: &str = "distort.freeDistort";
@@ -18,28 +33,20 @@ pub(crate) const FREE_DISTORT: &str = "distort.freeDistort";
/// coordinates.
pub(super) const IDENTITY: [[f64; 2]; 4] = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
/// The area the handles move in.
const PAD: Vec2 = vec2(260.0, 200.0);
/// The space between the box and the edges of the area.
const MARGIN: f32 = 40.0;
/// The drawn size of a handle.
const HANDLE: f32 = 9.0;
/// The size of the square that takes a press on a handle.
const GRAB: f32 = 16.0;
/// How far an arrow key moves a corner, as a share of the box's side.
const STEP: f64 = 0.01;
/// The box's side in document units: one unit is a hundredth of the side, the step of an arrow key.
const SIDE: f64 = 100.0;
/// The space between the box and the edge of the pad in document units: the share of its side
/// the box always left (40 of 180 points).
const MARGIN: f64 = SIDE * 40.0 / 180.0;
/// How many cells the grid across the distorted box has along each side.
const GRID: u32 = 4;
/// The handles' names for screen readers, in the order of the corners.
fn names() -> [&'static str; 4] {
[tl!("Top Left"), tl!("Top Right"), tl!("Bottom Right"), tl!("Bottom Left")]
}
/// The corners in `d.fields["corners"]`. A missing or malformed corner reads as its place on the
/// The corners in `fields["corners"]`. A missing or malformed corner reads as its place on the
/// box, as the effect reads it.
pub(super) fn corners(d: &Dialog) -> [[f64; 2]; 4] {
pub(super) fn corners(fields: &DialogFields) -> [[f64; 2]; 4] {
let mut c = IDENTITY;
if let Some(list) = d.fields.get("corners").and_then(Value::as_array) {
for (slot, v) in c.iter_mut().zip(list) {
if let Some(Value::Array(list)) = json_value(fields, "corners") {
for (slot, v) in c.iter_mut().zip(&list) {
if let Some(a) = v.as_array()
&& let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64))
&& x.is_finite()
@@ -54,7 +61,7 @@ pub(super) fn corners(d: &Dialog) -> [[f64; 2]; 4] {
/// The width of the first selected object's bounds over their height, limited to 1/8 to 8; 1 when
/// nothing is selected or the bounds are empty.
fn aspect(app: &VectorcraftApp) -> f32 {
pub(super) fn aspect(app: &VectorcraftApp) -> f32 {
let bounds = app.session.active().and_then(|st| st.selection.objects.first().and_then(|id| st.doc.node(*id))).and_then(|n| n.geometric_bounds());
match bounds {
Some(b) if b.width() > 0.0 || b.height() > 0.0 => (b.width().max(1e-9) / b.height().max(1e-9)).clamp(0.125, 8.0) as f32,
@@ -67,106 +74,92 @@ fn round(x: f64) -> f64 {
(x * 1e4).round() / 1e4
}
/// The box, the handles and Reset. Changes go to `d.fields["corners"]`.
pub(super) fn fields(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
let before = corners(d);
let mut c = before;
let (pad, _) = ui.allocate_exact_size(PAD, Sense::hover());
let inner = pad.shrink(MARGIN);
let aspect = aspect(app);
let size = if aspect >= inner.width() / inner.height() {
vec2(inner.width(), inner.width() / aspect)
} else {
vec2(inner.height() * aspect, inner.height())
};
let bx = Rect::from_center_size(inner.center(), size);
let to_screen = |[x, y]: [f64; 2]| Pos2::new(bx.left() + x as f32 * bx.width(), bx.top() + y as f32 * bx.height());
let to_unit = |p: Pos2| [f64::from((p.x - bx.left()) / bx.width()), f64::from((p.y - bx.top()) / bx.height())];
let (lo, hi) = (to_unit(pad.min), to_unit(pad.max));
let names = names();
// Per handle: whether it is held or hovered, and whether it has the keyboard focus.
let mut states = [(false, false); 4];
for (i, corner) in c.iter_mut().enumerate() {
let id = ui.scope_id().with(("free-distort-corner", i));
let at = pad.clamp(to_screen(*corner));
let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(GRAB)), id, Sense::click_and_drag());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), names[i]));
if resp.drag_started() || resp.clicked() {
resp.request_focus();
}
if resp.drag_started()
&& let Some(origin) = ui.input(|i| i.pointer.press_origin())
{
// The offset from the press to the handle's center, kept for the drag.
ui.data_mut(|m| m.insert_temp(id, at - origin));
}
if resp.dragged()
&& let Some(p) = resp.interact_pointer_pos()
{
let grip: Vec2 = ui.data(|m| m.get_temp(id)).unwrap_or_default();
*corner = to_unit(pad.clamp(p + grip)).map(round);
}
if resp.has_focus() {
ui.memory_mut(|m| {
m.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
});
for (key, dx, dy) in [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)] {
// Shift first: a key without modifiers also matches the key with Shift.
for (modifiers, step) in [(Modifiers::SHIFT, STEP * 10.0), (Modifiers::NONE, STEP)] {
if ui.input_mut(|i| i.consume_key(modifiers, key)) {
// A corner stays inside the area, or, when it lies outside, no farther out.
let [x, y] = &mut *corner;
for (v, d, lo, hi) in [(x, dx, lo[0], hi[0]), (y, dy, lo[1], hi[1])] {
*v = round((*v + d * step).clamp(lo.min(*v), hi.max(*v)));
}
}
}
}
}
states[i] = (resp.dragged() || resp.hovered(), resp.has_focus());
if resp.dragged() || resp.hovered() {
ui.ctx().set_cursor_icon(if resp.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
}
}
ui.add_space(4.0);
let reset = ui
.add_enabled_ui(c != IDENTITY, |ui| {
let r = widgets::flat_button(ui, tl!("Reset"), 64.0);
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset")));
r
})
.inner;
if reset.clicked() {
c = IDENTITY;
}
paint(ui, pad, bx, c.map(to_screen), states);
if c != before {
d.fields.insert("corners".into(), json!(c));
}
/// The row of the Free Distort dialog: the box with its handles and Reset.
pub(super) fn params(cx: &EffectCx, _fields: &DialogFields) -> Vec<Param> {
let aspect = cx.aspect;
vec![Param::custom("corners", tl!("Free Distort"), move |ui, fields, _| pad(ui, fields, aspect)).full_width()]
}
/// The pad: the box at rest, the distorted box with a grid across it, and the handles (filled in
/// the accent color while focused).
fn paint(ui: &egui::Ui, pad: Rect, bx: Rect, q: [Pos2; 4], states: [(bool, bool); 4]) {
let t = Tokens::get(ui.ctx());
let painter = ui.painter_at(pad);
painter.rect_filled(pad, 2.0, t.input);
painter.rect_stroke(bx, 0.0, Stroke::new(1.0, t.text_dim.gamma_multiply(0.5)), egui::StrokeKind::Middle);
let at = |u: f32, v: f32| q[0].lerp(q[1], u).lerp(q[3].lerp(q[2], u), v);
let faint = Stroke::new(1.0, t.text_dim.gamma_multiply(0.6));
for k in 1..4 {
let f = k as f32 / 4.0;
painter.line_segment([at(f, 0.0), at(f, 1.0)], faint);
painter.line_segment([at(0.0, f), at(1.0, f)], faint);
}
painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.5, t.text)));
for (p, (active, focused)) in q.into_iter().zip(states) {
let r = Rect::from_center_size(pad.clamp(p), Vec2::splat(HANDLE));
painter.rect_filled(r, 1.0, if focused { t.accent } else { t.panel });
painter.rect_stroke(r, 1.0, Stroke::new(if active { 2.0 } else { 1.0 }, t.text), egui::StrokeKind::Middle);
if focused {
painter.rect_stroke(r.expand(3.0), 2.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Outside);
/// A corner of the unit box as a document point.
fn doc_point([x, y]: [f64; 2]) -> Point {
Point::new(x * SIDE, y * SIDE)
}
/// The corners the box's `now` moves `before` to. A corner the box did not move stays as it was, so
/// a click that moved nothing changes nothing. A moved corner stays inside the document `shown`,
/// or, when it lies outside already, goes no farther out.
fn moved(before: [[f64; 2]; 4], given: [Point; 4], now: [Point; 4], shown: DocRect) -> [[f64; 2]; 4] {
let (lo, hi) = ([shown.x0 / SIDE, shown.y0 / SIDE], [shown.x1 / SIDE, shown.y1 / SIDE]);
let mut c = before;
for (i, corner) in c.iter_mut().enumerate() {
let (Some(&was), Some(&to)) = (given.get(i), now.get(i)) else { continue };
if (to - was).hypot() <= 1e-9 {
continue;
}
let target = [to.x / SIDE, to.y / SIDE];
for (k, v) in corner.iter_mut().enumerate() {
// `max` then `min`, as the bounds may be reversed by a degenerate view.
*v = round(target[k].max(lo[k].min(*v)).min(hi[k].max(*v)));
}
}
painter.rect_stroke(pad, 2.0, Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
c
}
/// The pad: the box at rest, the distorted box with a grid across it and the handles, drawn through
/// `view`.
fn paint(cx: &ContentPainterCx<'_>, view: &CanvasView, quad: [Point; 4]) {
let screen = |p: Point| view.to_screen(p);
let q = quad.map(screen);
let at = |u: f32, v: f32| q[0].lerp(q[1], u).lerp(q[3].lerp(q[2], u), v);
cx.outline(&PaintShape::Polygon(IDENTITY.map(|c| screen(doc_point(c))).to_vec()));
for k in 1..GRID {
let f = k as f32 / GRID as f32;
cx.outline(&PaintShape::Path(vec![at(f, 0.0), at(f, 1.0)]));
cx.outline(&PaintShape::Path(vec![at(0.0, f), at(1.0, f)]));
}
cx.outline(&PaintShape::Polygon(q.to_vec()));
}
/// The box, the handles and Reset. Changes go to `fields["corners"]`.
fn pad(ui: &mut egui::Ui, fields: &mut DialogFields, aspect: f64) -> Response {
let before = corners(fields);
let aspect = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 };
let (least_width, height) = {
let plot = &Env::of(ui).tokens.size.plot;
(plot.width, plot.height)
};
let mut after = before;
let mut reset = false;
let shown = Stack::new().fill_width().show(ui, |ui, _| {
let (room, _) = ui.allocate_exact_size(vec2(ui.available_width().max(least_width), height), Sense::hover());
// The document is the box with a margin round it; its units are `aspect` times as wide as tall.
let extent = SIDE + 2.0 * MARGIN;
let zoom = (f64::from(room.width()) / (extent * aspect)).min(f64::from(room.height()) / extent);
let view = CanvasView::new(room, Point::new(SIDE / 2.0, SIDE / 2.0), zoom).aspect(aspect);
let quad = before.map(doc_point);
let mut state = BoxState::from_rect(DocRect::new(0.0, 0.0, SIDE, SIDE));
state.quad = quad;
let canvas = Canvas::new(tl!("Free Distort")).view(view).show_at(ui, room, |ui, body| {
Picture::painter("", ThumbAspect::SQUARE, move |cx, _| paint(cx, &view, quad)).show_at(ui, body.rect);
TransformBox::new(tl!("Free Distort"), Bind::given(state), DocRect::new(0.0, 0.0, SIDE, SIDE), 0.0)
.rules(BoxRules::in_mode(TransformMode::Distort))
.reference_point(false)
.inside_moves(false)
.session_commit(false)
.show_at(ui, body.rect)
});
if let Some(output) = canvas.inner
&& let Some(edit) = output.edit.value()
{
after = moved(before, quad, edit.quad, view.visible());
}
reset = Button::new(tl!("Reset")).enabled(after != IDENTITY).show(ui).clicked();
});
if reset {
after = IDENTITY;
}
if after != before {
fields.set("corners", FieldValue::Json(json!(after)));
}
shown.output
}