Merge pull request #3140 from aiongg/restore-lost-pc-features

Restore four PhotoCraft features lost in photocraft#15449 (curve grab, ruler snap, Hue/Saturation swatches, Mixer load)
This commit is contained in:
aiongg
2026-11-23 00:45:59 -05:00
committed by GitHub
24 changed files with 983 additions and 118 deletions
+21 -4
View File
@@ -3,7 +3,6 @@
use super::model::{RulerLine, RulerPart};
use super::words::RulerWords;
use craft_behavior::geometry::turn_to_45;
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_behavior::{
Cursor, CursorIcon, CursorPriority, Granularity, HitLevel, HitPriority, HitShape, IconId, Intent, Metrics, NavShape, PaintedCursor, PartKey,
@@ -133,10 +132,28 @@ pub(super) fn translated(line: RulerLine, by: DocVec) -> RulerLine {
RulerLine { start: line.start + by, end: line.end + by, protractor: line.protractor.map(|arm| arm + by) }
}
/// The line with the grabbed `part` moved to `to`, Shift on 45° rays about the fixed point: the end for the start, the
/// start for the end and the protractor.
/// `to` snapped to the nearest 45 degree ray about `from`, keeping the pointer's legs instead of its distance: on a
/// diagonal both legs take the shorter of |dx| and |dy| (signs kept), on a horizontal or vertical ray the dominant leg
/// stays and the other is 0. The ruler never gets longer than the pointer's distance, which `turn_to_45` (used by the
/// pen, the connector and the gradient) does not promise.
fn turn_short(from: Point, to: Point) -> Point {
let (dx, dy) = (to.x - from.x, to.y - from.y);
let step = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() as i64;
let (x, y) = match step.rem_euclid(4) {
0 => (dx, 0.0),
2 => (0.0, dy),
_ => {
let leg = dx.abs().min(dy.abs());
(leg.copysign(dx), leg.copysign(dy))
}
};
Point::new(from.x + x, from.y + y)
}
/// The line with the grabbed `part` moved to `to`, Shift on 45° rays about the fixed point (`turn_short`): the end for
/// the start, the start for the end and the protractor.
pub(super) fn moved(line: RulerLine, part: RulerPart, to: Point, shift: bool) -> RulerLine {
let constrain = |fixed: Point| if shift { turn_to_45(fixed, to) } else { to };
let constrain = |fixed: Point| if shift { turn_short(fixed, to) } else { to };
let mut line = line;
match part {
RulerPart::Start => line.start = constrain(line.end),
+2 -1
View File
@@ -86,7 +86,8 @@ pub use measure::{
MIN_LINE, RulerBar, RulerBarOutput, RulerLine, RulerOverlay, RulerPass, RulerTool, RulerWords, box_distances, ruler_line_form, show_ruler,
};
pub use paint_bar::{
EraserMode, MIXER_COMBINATIONS, MIXER_GROUP_STARTS, MixerValues, PaintBar, PaintBarOutput, PaintBarWords, PaintTool, PaintValues, Smoothing,
EraserMode, MIXER_COMBINATIONS, MIXER_GROUP_STARTS, MixerLoad, MixerValues, PaintBar, PaintBarOutput, PaintBarWords, PaintTool, PaintValues,
Smoothing,
};
pub use paths::{PathKind, PathRow, PathsCommands, PathsEvent, PathsFooterButton, PathsOutput, PathsPanel, PathsWords};
pub use pattern::{PatternColors, PatternFillDialog, PatternFillEditor, PatternFillOptions, PatternFillOutput, PatternSwatch, PatternWords};
+25 -9
View File
@@ -6,7 +6,7 @@ use std::sync::Arc;
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, Value};
use craft_theme::Srgba;
use craft_ui::buttons::{IconButton, ToggleButton};
use craft_ui::choice::{Checkbox, Swatch};
use craft_ui::choice::{Checkbox, Swatch, SwatchFill, SwatchImage};
use craft_ui::contract::{
Bind, BodyCx, Entry, Gap, LabelKind, PopupKind, Props as _, Remember as _, Show as _, ShowContainer as _, SideLabel, Trigger, clicked,
};
@@ -111,8 +111,21 @@ impl Default for Smoothing {
}
}
/// What the Mixer Brush holds: the paint its next stroke starts with.
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum MixerLoad {
/// Nothing: the brush is clean.
#[default]
Clean,
/// One colour.
Color(Srgba),
/// The tip image an Alt-click sampled.
Image(SwatchImage),
}
/// The Mixer Brush's values.
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct MixerValues {
/// Load the brush after each stroke.
@@ -131,8 +144,8 @@ pub struct MixerValues {
pub sample_all_layers: bool,
/// The index into [`MIXER_COMBINATIONS`].
pub combination: usize,
/// The colour the brush is loaded with, if any.
pub load_color: Option<Srgba>,
/// What the brush holds, which the load swatch shows.
pub current_load: MixerLoad,
/// Only solid colours load.
pub solid_colors_only: bool,
}
@@ -149,7 +162,7 @@ impl Default for MixerValues {
flow: 1.0,
sample_all_layers: false,
combination: 0,
load_color: None,
current_load: MixerLoad::Clean,
solid_colors_only: false,
}
}
@@ -442,12 +455,15 @@ impl<M: Value> Pass<'_, M> {
cx.memory::<SmoothingOpen>().0 = open;
}
/// The Mixer Brush's load swatch and its menu.
/// The Mixer Brush's load swatch, showing what the brush holds (a checkerboard when it is clean), and its menu.
fn mixer_load(&mut self, ui: &mut Ui, words: &PaintBarWords) {
let color = self.values.mixer.load_color;
let fill = match &self.values.mixer.current_load {
MixerLoad::Clean => SwatchFill::Empty,
MixerLoad::Color(color) => SwatchFill::Color(Mixed::Same(*color)),
MixerLoad::Image(image) => SwatchFill::Image(image.clone()),
};
let solid = self.values.mixer.solid_colors_only;
// `Swatch` has no empty face, so a brush with no load shows the mixed face.
let swatch = Swatch::new(words.load_swatch.clone(), color.map_or(Mixed::Mixed, Mixed::Same)).show(ui).response;
let swatch = Swatch::with_fill(words.load_swatch.clone(), fill).show(ui).response;
let (mut load, mut clean, mut next_solid) = (false, false, None);
let _ = Menu::new(words.load_swatch.clone()).opened_by(&swatch, Trigger::Click).show(ui, |ui, _| {
load = MenuItem::new(words.load_brush.clone()).show(ui).ran;
+17 -3
View File
@@ -1,14 +1,20 @@
//! Stories of the paint bar, one per tool and Eraser mode.
use super::{EraserMode, PaintBar, PaintTool, PaintValues};
use super::{EraserMode, MixerLoad, PaintBar, PaintTool, PaintValues};
use craft_ui::bars::{Bar, BarKind};
use craft_ui::choice::SwatchImage;
use craft_ui::contract::{Entry, ShowContainer as _};
use craft_ui::testing::pictures::sample_picture;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
/// The bar of `tool` in a bar strip, over values the story keeps.
/// The bar of `tool` in a bar strip, over values the story keeps, starting from `start`.
fn show(ui: &mut Ui, data: &mut StoryData, tool: PaintTool, eraser: EraserMode) -> StoryOutput {
let state = data.value("state", (PaintValues::new(0u32), eraser));
show_from(ui, data, tool, eraser, PaintValues::new(0u32))
}
fn show_from(ui: &mut Ui, data: &mut StoryData, tool: PaintTool, eraser: EraserMode, start: PaintValues<u32>) -> StoryOutput {
let state = data.value("state", (start, eraser));
let (values, eraser_mode) = (&mut state.0, &mut state.1);
let modes = [Entry::new(0u32, "Normal"), Entry::new(1u32, "Multiply"), Entry::new(2u32, "Screen")];
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
@@ -45,3 +51,11 @@ fn eraser_block_mode(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
fn mixer_brush(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, PaintTool::MixerBrush, EraserMode::Brush)
}
/// The Mixer Brush after an Alt-click: the load swatch shows the sampled tip image.
#[story(PaintBar<'static, u32>, covers = [], drive = Drive::Never)]
fn mixer_brush_sampled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut start = PaintValues::new(0u32);
start.mixer.current_load = MixerLoad::Image(SwatchImage::new(sample_picture(11, [64, 64])));
show_from(ui, data, PaintTool::MixerBrush, EraserMode::Brush, start)
}
+48
View File
@@ -330,6 +330,54 @@ fn a_protractors_vertex_moves_the_whole_protractor_and_its_arm_end_moves_alone()
assert!(near(new.start, from) && new.protractor.is_none(), "a press on the arm's line starts a new ruler: {new:?}");
}
/// From upstream PhotoCraft's analysis_ruler_shift_tests (#11985): Shift snaps a ruler end to 45 degree rays and keeps
/// the shorter leg, so a snap never makes the ruler longer; the same for either end moved about the other and for a
/// protractor's arm.
#[trial]
fn shift_snaps_the_ruler_to_45_degrees_without_making_it_longer() {
let shift = egui::Modifiers::SHIFT;
let v = kurbo::Vec2::new;
// (pointer offset from the press, the end's offset after the snap).
for (to, end) in
[(v(82.0, 100.0), v(82.0, 82.0)), (v(122.0, 120.0), v(120.0, 120.0)), (v(300.0, 30.0), v(300.0, 0.0)), (v(-82.0, -100.0), v(-82.0, -82.0))]
{
let mut ruler = shown(None);
let from = ruler.middle();
ruler.drag(from, from + to, shift);
let line = (*ruler.line.borrow()).expect("a line");
assert!(near(line.start, from) && near(line.end, from + end), "to {to:?}: {line:?}");
assert!(line.start.distance(line.end) <= to.hypot() + 1e-6, "never longer than the pointer's distance: {line:?}");
}
// Either end moved about the other.
let mut ruler = shown(None);
let m = ruler.middle();
let line = RulerLine::new(m, m + v(200.0, 150.0));
*ruler.line.borrow_mut() = Some(line);
ruler.drag(line.end, line.start + v(282.0, -90.0), shift);
let after = (*ruler.line.borrow()).expect("a line");
assert!(near(after.start, line.start) && near(after.end, line.start + v(282.0, 0.0)), "the end about the start: {after:?}");
let mut ruler = shown(None);
*ruler.line.borrow_mut() = Some(line);
ruler.drag(line.start, line.end + v(-282.0, -90.0), shift);
let after = (*ruler.line.borrow()).expect("a line");
assert!(near(after.end, line.end) && near(after.start, line.end + v(-282.0, 0.0)), "the start about the end: {after:?}");
// A protractor's arm end keeps the shorter leg about the vertex.
let mut ruler = shown(None);
let line = protractor(ruler.middle());
*ruler.line.borrow_mut() = Some(line);
ruler.drag(line.protractor.unwrap(), line.start + v(122.0, -170.0), shift);
let after = (*ruler.line.borrow()).expect("a line");
assert!(after.protractor.is_some_and(|arm| near(arm, line.start + v(122.0, -122.0))), "{after:?}");
// Without Shift the end follows the pointer.
let mut ruler = shown(None);
let from = ruler.middle();
ruler.drag(from, from + v(82.0, 100.0), egui::Modifiers::NONE);
assert!(near((*ruler.line.borrow()).expect("a line").end, from + v(82.0, 100.0)));
}
/// From upstream PhotoCraft's ruler_tests (#13438): the Ruler's arrow everywhere, the protractor with Alt exactly where
/// an Alt press starts the protractor arm, and the crosshair while the canvas shows precise cursors.
#[trial]
+42 -4
View File
@@ -1,17 +1,19 @@
//! `PaintBar`: which members each tool disables, the smoothing options, the gestures, the combinations list and a
//! click on the load swatch menu.
//! `PaintBar`: which members each tool disables, the smoothing options, the gestures, the combinations list, what the
//! load swatch shows and a click on its menu.
use std::cell::RefCell;
use std::rc::Rc;
use craft_behavior::EditEvent;
use craft_draw::ui::{EraserMode, MIXER_COMBINATIONS, PaintBar, PaintTool, PaintValues};
use craft_draw::ui::{EraserMode, MIXER_COMBINATIONS, MixerLoad, PaintBar, PaintTool, PaintValues};
use craft_theme::Srgba;
use craft_ui::bars::{Bar, BarKind};
use craft_ui::choice::SwatchImage;
use craft_ui::contract::{Entry, ShowContainer as _};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, Room, trial};
use egui::{Key, Modifiers, Pos2};
use egui::{Color32, ColorImage, Key, Modifiers, Pos2, Shape, TextureId};
struct Host {
values: PaintValues<u32>,
@@ -150,3 +152,39 @@ fn a_click_on_the_load_swatch_menus_clean_brush_row_reports_it_once() {
assert_eq!(host.borrow().cleans, 1, "one pass: {one_pass}");
}
}
/// Every shape of the frame, groups opened.
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
}
/// What the load swatch shows: its accessible value and the pictures painted in it (the checkerboard, a sampled image).
fn load_swatch(fixture: &mut Fixture) -> (Option<String>, usize) {
let swatch = fixture.by_label("Current brush load").expect("the bar shows the load swatch");
let value = fixture.tree().value_of(swatch.node).map(str::to_owned);
let well = swatch.rect.expand(0.5);
let mut pictures: Vec<TextureId> = flat(fixture.frame_shapes())
.iter()
.filter(|shape| well.contains_rect(shape.visual_bounding_rect()))
.map(Shape::texture_id)
.filter(|texture| *texture != TextureId::default())
.collect();
pictures.sort_by_key(|texture| format!("{texture:?}"));
pictures.dedup();
(value, pictures.len())
}
/// The load swatch shows what the brush holds: a clean brush the checkerboard alone, a colour that colour, a sampled
/// tip image that picture over the checkerboard.
#[trial]
fn the_load_swatch_shows_each_mixer_load() {
let green = Srgba::rgb(0.0, 1.0, 0.0);
let tip = SwatchImage::new(ColorImage::filled([64, 64], Color32::from_rgb(0, 0, 255)));
let cases =
[(MixerLoad::Clean, Some("Empty".to_owned()), 1), (MixerLoad::Color(green), Some(green.to_hex()), 0), (MixerLoad::Image(tip), None, 2)];
for (load, value, pictures) in cases {
let shown = load.clone();
let (mut fixture, _) = harness(PaintTool::MixerBrush, EraserMode::Brush, move |v| v.mixer.current_load = shown);
assert_eq!(load_swatch(&mut fixture), (value, pictures), "{load:?}");
}
}
+171 -25
View File
@@ -1,20 +1,24 @@
//! [`HueSaturationEditor`]: Master and six colour ranges, Colorize, the two spectrum bars and the four range thumbs
//! that wrap at 360°.
//! [`HueSaturationEditor`]: Master and six colour ranges picked by their swatches, Colorize, the two spectrum bars and
//! the four range thumbs that wrap at 360°.
#[cfg(feature = "suite")]
pub(crate) mod stories;
use craft_behavior::Mixed;
use craft_behavior::{Metrics, Mixed, Sense};
use craft_theme::{Hsb, Srgba};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, EditResponse, Entry, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _};
use craft_ui::choice::{Checkbox, RadioGroup, Swatch, SwatchFill, SwatchMetrics, SwatchShape};
use craft_ui::contract::{
Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, MeasureCx, Outcome, PaintUi, Pattern, Props as _, Remember as _, Role, Show as _,
ShowContainer as _,
};
use craft_ui::display::{Shade, Text};
use craft_ui::form::Field;
use craft_ui::pickers::Select;
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row as LayoutRow, Stack};
use craft_ui::primitives::PaintShape;
use craft_ui::runtime::env::{Env, Label, UnitKind};
use craft_ui::style::{DataColor, TypeRole};
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx, TypeRole};
use craft_ui::value_drag::{Anchor, OffThumbs, SpanInk, Thumb, ThumbRow, ThumbSpan, TrackFace};
use egui::{Color32, Ui};
use egui::{Color32, Response, Ui, Vec2};
use super::sliders::{Run, editor_group, lifted, read, words};
use super::style::tones;
@@ -37,6 +41,10 @@ const TURN: f64 = 360.0;
const MAX_SPAN: f64 = 359.0;
/// The bands under a range's thumbs: the whole range faint, its full-strength part muted.
const RANGE_SPANS: [ThumbSpan; 2] = [ThumbSpan::new(0, 3, SpanInk::Faint), ThumbSpan::new(1, 2, SpanInk::Muted)];
/// The grey Colorize's swatch shows the adjustment of: what Colorize makes of it is the colorize colour.
const MID_GREY: Srgba = Srgba::rgb(0.5, 0.5, 0.5);
/// The edited mark's dot as a share of its slot's height.
const EDITED_DOT: f32 = 1.0;
/// One of Hue/Saturation's six colour ranges (Reds, Yellows, Greens, Cyans, Blues, Magentas).
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -84,6 +92,18 @@ impl HueRangeValue {
out.map(|b| b + shift)
}
/// The middle of the range's fully-on span (its inner two bounds, canonical), in 0..360: 0° for the Reds, 240°
/// for the Blues.
pub fn centre(&self) -> f64 {
let bounds = Self::canonical_bounds(self.bounds);
((bounds[1] + bounds[2]) / 2.0).rem_euclid(TURN)
}
/// Whether the range's own hue, saturation or lightness changes anything.
fn edited(&self) -> bool {
self.hue != 0.0 || self.saturation != 0.0 || self.lightness != 0.0
}
/// `bounds` with thumb `index` (0 range start … 3 range end) dragged to `degrees` (0..=360 on
/// the bar), PhotoCraft's rule: canonicalise first; the start moves by the shortest turn to
/// `degrees`, at most to the second thumb and at least 180° before it; any other thumb moves
@@ -172,6 +192,14 @@ impl HueSaturation {
self
}
/// A value holding only range `r` of `self`: the master unchanged, Colorize off and the other ranges neutral, so
/// an adjustment of it shows what that range alone does.
fn only_range(&self, r: usize) -> HueSaturation {
let mut only = HueSaturation::default();
only.ranges[r] = self.ranges[r];
only
}
/// The four thumbs of range `r` as the thumb row shows them: each bound within one turn.
fn thumbs(&self, r: usize) -> [f64; 4] {
HueRangeValue::canonical_bounds(self.ranges[r].bounds).map(|degrees| degrees.rem_euclid(TURN))
@@ -192,9 +220,14 @@ impl HueSaturation {
}
}
/// A fully saturated, full-brightness hue.
fn hue_srgba(degrees: f64) -> Srgba {
Srgba::from_hsb(Hsb { h: degrees.rem_euclid(TURN) as f32, s: 1.0, b: 1.0 })
}
/// A fully saturated, full-brightness hue as image data.
fn hue_color(degrees: f64) -> DataColor {
DataColor::new(Color32::from(Srgba::from_hsb(Hsb { h: degrees as f32, s: 1.0, b: 1.0 })))
DataColor::new(Color32::from(hue_srgba(degrees)))
}
/// The hue spectrum for a colour track: red, yellow, green, cyan, blue, magenta, red.
@@ -241,19 +274,26 @@ impl std::ops::Deref for HueSaturationOutput {
}
}
/// What a colour of the image becomes under a Hue/Saturation value; see [`HueSaturationEditor::adjusted`].
pub type AdjustedFn<'a> = dyn Fn(&HueSaturation, Srgba) -> Srgba + 'a;
/// Hue/Saturation.
///
/// - **Range select** (Master, Reds … Magentas): view state of the editor, Master at first. Disabled and forced to
/// Master while Colorize is on. The range shown comes back in [`HueSaturationOutput::shown_range`].
/// - **Range swatches** (Master, Reds … Magentas): a radio group of round swatches, view state of the editor, Master
/// (the hue wheel) at first. A range swatch shows the colour at the range's centre; once the range's own Hue,
/// Saturation or Lightness is not zero it shows that colour before and after the range alone (start and end halves,
/// through [`adjusted`](Self::adjusted)) with a dot under it. With a range shown, its centre stands above the Hue row,
/// at the end edge: "240°", or "0° / 30°" once its Hue moves it. While Colorize is on the row is one read-only
/// swatch of what the value makes of a mid grey, and the editor shows Master. The range shown comes back in
/// [`HueSaturationOutput::shown_range`].
/// - **Master**: Hue (−180..180°; 0..360° with Colorize) over the hue spectrum track, Saturation (−100..100 %;
/// 0..100 % with Colorize) over a track from grey to the current hue, Lightness (−100..100 %) over a fixed black,
/// grey, white track. Tracks only while dynamic tracks are on.
/// - **A range**: its Hue, Saturation and Lightness rows, then the range thumbs (below).
/// - **Colorize** (a `Set`): on, Hue wraps into 0..360 and Saturation becomes at least 25; off, a Hue above 180 wraps
/// back by −360.
/// - **Spectrum bars**: the input hues above (37 samples, every 10°), the host's
/// [`adjusted_spectrum`](Self::adjusted_spectrum) below (the same 37 hues after the adjustment; the input bar again
/// without it). Not mirrored in right-to-left layouts: they are scales of the image.
/// - **Spectrum bars**: the input hues above (37 samples, every 10°), the host's [`adjusted`](Self::adjusted) below
/// (the same 37 hues after the adjustment; the input bar again without it). Not mirrored in right-to-left layouts: they are scales of the image.
/// - **Range thumbs** (a range shown): four thumbs under the lower bar as one thumb row that wraps through 0° and keeps
/// its order going round from the first thumb, over a faint band from the first thumb to the last and a muted one
/// between the middle two. A drag on a thumb moves it with [`HueRangeValue::move_bound`], whole degrees; a press
@@ -263,7 +303,7 @@ impl std::ops::Deref for HueSaturationOutput {
pub struct HueSaturationEditor<'a> {
label: Label,
value: Bind<'a, HueSaturation>,
adjusted: Option<&'a dyn Fn(f64) -> Srgba>,
adjusted: Option<&'a AdjustedFn<'a>>,
range: Option<Option<usize>>,
context: AdjustContext,
}
@@ -274,9 +314,10 @@ impl<'a> HueSaturationEditor<'a> {
Self { label: label.into(), value, adjusted: None, range: None, context: AdjustContext::dialog(true) }
}
/// What a fully saturated, full-brightness hue (degrees 0..=360) becomes under the shown value: the host runs its
/// engine. Called 37 times a pass.
pub fn adjusted_spectrum(mut self, adjusted: &'a dyn Fn(f64) -> Srgba) -> Self {
/// What a colour of the image becomes under a value: the host runs its engine. The lower spectrum bar asks for 37
/// full hues under the shown value, each edited range's swatch for its centre colour under a value holding only
/// that range, and Colorize's swatch for a mid grey under the shown value. Without it every colour stays as it is.
pub fn adjusted(mut self, adjusted: &'a AdjustedFn<'a>) -> Self {
self.adjusted = Some(adjusted);
self
}
@@ -308,12 +349,51 @@ impl<'a> HueSaturationEditor<'a> {
let at = if now.colorize { 0 } else { kept.min(6) };
let range = at.checked_sub(1);
let names = [&words.reds, &words.yellows, &words.greens, &words.cyans, &words.blues, &words.magentas];
let mut entries = vec![Entry::new(0usize, words.master.clone())];
entries.extend(names.iter().enumerate().map(|(i, name)| Entry::new(i + 1, (*name).clone())));
let after = |value: &HueSaturation, color: Srgba| adjusted.map_or(color, |adjusted| adjusted(value, color));
let mut picked = None;
Field::new(words.range.clone()).id_salt("range").show(ui, |ui, _| {
picked = Select::new(words.range.clone(), Bind::given(at), &entries).enabled(!now.colorize).show(ui).value().copied();
});
if now.colorize {
Swatch::new(words.colorize_color.clone(), after(&now, MID_GREY)).shape(SwatchShape::Round).read_only(true).show(ui);
} else {
picked = RadioGroup::new(words.range.clone(), Bind::given(at))
.show(ui, |ui, _| {
LayoutRow::new().show(ui, |ui, _| {
for shown in 0..=names.len() {
let (label, fill, edited) = match shown.checked_sub(1) {
None => (words.master.clone(), SwatchFill::Spectrum, false),
Some(r) => {
let range = now.ranges[r];
let before = hue_srgba(range.centre());
let fill = if range.edited() {
SwatchFill::Split(before, after(&now.only_range(r), before))
} else {
SwatchFill::Color(Mixed::Same(before))
};
(names[r].clone(), fill, range.edited())
}
};
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Swatch::with_fill(label.clone(), fill.clone()).shape(SwatchShape::Round).member(shown).show(ui);
EditedMark::new(edited).show(ui);
});
}
});
})
.value()
.copied();
}
if let Some(r) = at.checked_sub(1) {
let range = now.ranges[r];
let degrees = |at: f64| units.text(UnitKind::Degrees, at.round().rem_euclid(TURN) + 0.0, 0..=0);
let centre = range.centre();
let text = if range.hue.round() == 0.0 {
degrees(centre)
} else {
words.range_centre_moved.fill(&[("from", &degrees(centre)), ("to", &degrees(centre + range.hue))])
};
LayoutRow::new().fill_width().align(RowAlign::End).show(ui, |ui, _| {
Text::new(text.clone()).shade(Shade::Faint).show(ui);
});
}
let mut run = Run::start(&mut value, context, now, memory.began);
let hue_track = AdjustTrack::Colors(hue_stops());
let degrees =
@@ -362,7 +442,7 @@ impl<'a> HueSaturationEditor<'a> {
let input: Vec<DataColor> = (0..SAMPLES).map(|i| hue_color(i as f64 * SAMPLE_STEP)).collect();
let after: Vec<DataColor> = match adjusted {
Some(adjusted) => (0..SAMPLES).map(|i| DataColor::new(Color32::from(adjusted(i as f64 * SAMPLE_STEP)))).collect(),
Some(adjusted) => (0..SAMPLES).map(|i| DataColor::new(Color32::from(adjusted(&now, hue_srgba(i as f64 * SAMPLE_STEP))))).collect(),
None => input.clone(),
};
ToneRamp::new(&input).label(words.spectrum_before.clone()).show(ui);
@@ -404,3 +484,69 @@ impl<'a> HueSaturationEditor<'a> {
HueSaturationOutput { edit: lifted(edit, shown.output), shown_range }
}
}
/// The style of the edited mark: its slot and the dot's colour.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct EditedMarkStyle {
#[style(metrics)]
metrics: Metrics,
/// The slot: a swatch wide, `space.gap.tight` tall.
slot: Vec2,
/// The dot.
dot: StyleColor,
}
/// The mark under a range swatch: a dot while the range is edited. Its slot is always there, so the row keeps its
/// height when a range is first edited.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(sample = EditedMark::sample)]
struct EditedMark {
#[common]
common: Common,
edited: bool,
}
impl EditedMark {
fn new(edited: bool) -> Self {
EditedMark { common: Common::new(), edited }
}
fn sample() -> Self {
EditedMark::new(true)
}
}
impl Component for EditedMark {
const DISABLED: DisabledLook = DisabledLook::Faded;
const ROLE: Role = Role::None;
const OVERLAYS: bool = false;
const PARTS: bool = false;
const STOPS: bool = false;
type Style = EditedMarkStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: EditedMarkStyleKey) -> EditedMarkStyle {
let slot = Vec2::new(SwatchMetrics::of(cx).side, cx.tokens.space.gap.tight);
EditedMarkStyle { metrics: Metrics::new(), slot, dot: cx.color(cx.tokens.color.text.muted) }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
cx.style.slot
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if self.edited {
let radius = cx.rect.height() * EDITED_DOT / 2.0;
ui.draw().fill(&PaintShape::Circle(cx.rect.center(), radius), cx.style.dot);
}
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
@@ -1,42 +1,61 @@
//! Stories of Hue/Saturation: Master, a colour range with its thumbs, and Colorize.
//! Stories of Hue/Saturation: Master, a colour range with its thumbs, Colorize, and edited ranges on their swatches.
use super::{HueRangeValue, HueSaturation, HueSaturationEditor};
use craft_theme::Srgba;
use craft_theme::{Hsb, Srgba};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
/// What a hue becomes when the image is shifted 40° towards yellow: a stand-in for the host's engine.
fn shifted(degrees: f64) -> Srgba {
let turn = (degrees + 40.0).rem_euclid(360.0) / 60.0;
let (r, g, b) = match turn as u8 {
0 => (1.0, turn.fract(), 0.0),
1 => (1.0 - turn.fract(), 1.0, 0.0),
2 => (0.0, 1.0, turn.fract()),
3 => (0.0, 1.0 - turn.fract(), 1.0),
4 => (turn.fract(), 0.0, 1.0),
_ => (1.0, 0.0, 1.0 - turn.fract()),
};
Srgba::rgb(r as f32, g as f32, b as f32)
/// What `color` becomes under `value`: a stand-in for the host's engine. Colorize tints the colour with the master hue
/// and saturation; otherwise the master and the ranges whose full span holds the colour's hue shift that hue, scale
/// its saturation and move its brightness.
fn adjusted(value: &HueSaturation, color: Srgba) -> Srgba {
let Hsb { h, s, b } = color.to_hsb();
if value.colorize {
let b = (f64::from(b) * (1.0 + value.lightness / 100.0)).clamp(0.0, 1.0);
return Srgba::from_hsb(Hsb { h: value.hue.rem_euclid(360.0) as f32, s: (value.saturation / 100.0) as f32, b: b as f32 });
}
let (mut hue, mut saturation, mut lightness) = (value.hue, value.saturation, value.lightness);
for range in &value.ranges {
let bounds = HueRangeValue::canonical_bounds(range.bounds);
let inside = (f64::from(h) - bounds[1]).rem_euclid(360.0) <= bounds[2] - bounds[1];
if inside {
(hue, saturation, lightness) = (hue + range.hue, saturation + range.saturation, lightness + range.lightness);
}
}
let s = (f64::from(s) * (1.0 + saturation / 100.0)).clamp(0.0, 1.0);
let b = (f64::from(b) * (1.0 + lightness / 100.0)).clamp(0.0, 1.0);
Srgba::from_hsb(Hsb { h: (f64::from(h) + hue).rem_euclid(360.0) as f32, s: s as f32, b: b as f32 })
}
#[story(HueSaturationEditor<'static>, covers = [Default], drive = Drive::Never)]
fn hue_saturation_master(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let (value, value_at) = data.value_at("master", HueSaturation { hue: 40.0, saturation: 20.0, ..HueSaturation::default() });
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted_spectrum(&shifted).show(ui).into()
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted(&adjusted).show(ui).into()
}
/// The Reds range with its four thumbs and the readout.
/// The Reds range with its four thumbs and the readout, its Hue moved: the split swatch, its dot and "0° / 15°".
#[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)]
fn hue_saturation_range(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut start = HueSaturation::default();
start.ranges[0] = HueRangeValue { hue: 15.0, ..HueRangeValue::neutral(0) };
let (value, value_at) = data.value_at("range", start);
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).range(Some(0)).adjusted_spectrum(&shifted).show(ui).into()
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).range(Some(0)).adjusted(&adjusted).show(ui).into()
}
/// Colorize on: the range select is off and the Hue runs 0 to 360.
/// Colorize on: one read-only swatch of the colorize colour, and the Hue runs 0 to 360.
#[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)]
fn hue_saturation_colorize(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let (value, value_at) = data.value_at("colorize", HueSaturation { hue: 210.0, saturation: 40.0, colorize: true, ..HueSaturation::default() });
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).show(ui).into()
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted(&adjusted).show(ui).into()
}
/// Master shown with the Reds' Hue at +30 and the Blues' Saturation at −80: their swatches split before and after,
/// each with its dot.
#[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)]
fn hue_saturation_edited_ranges(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut start = HueSaturation::default();
start.ranges[0] = HueRangeValue { hue: 30.0, ..HueRangeValue::neutral(0) };
start.ranges[4] = HueRangeValue { saturation: -80.0, ..HueRangeValue::neutral(4) };
let (value, value_at) = data.value_at("edited", start);
HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted(&adjusted).show(ui).into()
}
+4
View File
@@ -96,6 +96,10 @@ craft_ui::words! {
/// The degrees readout under the spectrum bars: the range's outer start, inner start, inner
/// end and outer end, "{a} / {b} · {c} \\ {d}".
range_readout: template "adjust.rangeReadout" = "{a} / {b} · {c} \\ {d}";
/// The centre of the range shown, where its Hue moves it: "0° / 30°".
range_centre_moved: template "adjust.rangeCentreMoved" = "{from} / {to}";
/// The one swatch Colorize shows: what it makes of a mid grey.
colorize_color: "adjust.colorizeColor" = "Colorize Color";
// Black & White.
/// The Black & White editor's group name (AccessKit).
+1 -1
View File
@@ -38,7 +38,7 @@ pub use basic::{
pub use context::{AdjustContext, ToneChannel, ToneChannelCommands, ToneChannels, ToneSpace};
pub use curves_panel::{CurvesMode, CurvesPanel, CurvesPanelOutput, ToneCurves};
pub use hosted::{AdjustDialogCx, EditPhase, HostedAdjustDialog};
pub use hue_saturation::{HueRangeValue, HueSaturation, HueSaturationEditor, HueSaturationOutput};
pub use hue_saturation::{AdjustedFn, HueRangeValue, HueSaturation, HueSaturationEditor, HueSaturationOutput};
pub use kinds::AdjustmentKind;
pub use labels::AdjustWords;
pub use levels_editor::{Levels, LevelsClip, LevelsEditor, LevelsEditorOutput, LevelsWords};
+25 -7
View File
@@ -4,7 +4,7 @@ use super::model::{Curve, CurveRules, follow_corners};
use super::ramp::ToneRamp;
use super::words::CurveWords;
use crate::ui::histogram::{ChannelColor, HistogramData, HistogramInks, HistogramLook, PlotFrame, paint_bins, paint_frame};
use craft_behavior::{HitLevel, HitPriority, Input, Metrics, NavMove, PartKey, PointerButton, PressPhase, Sense};
use craft_behavior::{HitLevel, HitPriority, Input, Metrics, NavMove, PartKey, PointerButton, PressPhase, PressState, Sense};
use craft_keymap::{Chord, Key, Mods};
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, MeasureCx, Outcome, PaintUi, PartsCx,
@@ -23,6 +23,9 @@ use std::rc::Rc;
pub(super) const PLOT: PartKey = PartKey::new("plot");
/// A point: one accessible node each, `POINT.at(i)`.
const POINT: PartKey = PartKey::new("point");
/// A press within this many hit targets of a point grabs it instead of adding a new one; it is the one grab radius of
/// every host of the graph and follows density with `size.hit.target`.
const GRAB_TARGETS: f32 = 2.0;
/// The keys a focused graph keeps from the shortcut dispatcher while it shows points. `+` also arrives as Shift with `=`.
const PLUS: [Chord; 3] = [Chord::plain(Key::Plus), Chord::plain(Key::Equals), Chord::new(Mods::SHIFT, Key::Equals)];
@@ -224,7 +227,7 @@ pub struct CurveGraphStyle {
/// Thickness of the tone bars and the gap between them and the plot.
bar: f32,
bar_gap: f32,
/// Radius around a point that takes a press.
/// Radius around a point that takes a press: `GRAB_TARGETS` hit targets.
hit: f32,
/// How far outside the plot a dragged interior point is removed.
drag_off: f32,
@@ -443,6 +446,17 @@ impl<'a> CurveGraph<'a> {
}
}
/// The press this pass: the plot's, else the one on a point part. A press on a point's area outside the plot is
/// delivered to the point, and both go through the same code, which picks the nearest point within the radius.
fn press_of(cx: &Cx<'_, CurveGraph<'_>>, points: usize) -> PressState {
let plot = cx.part(PLOT).press;
let active = |press: &PressState| !matches!(press.phase, PressPhase::Idle | PressPhase::Hover);
if active(&plot) {
return plot;
}
(0..points as u64).map(|i| cx.part(POINT.at(i)).press).find(active).unwrap_or(plot)
}
/// The pointer's effect on the points while a point is dragged: the curve after the pointer moved to `pos`, or `None`
/// when nothing changed.
fn follow(rules: &CurveRules, map: Map, reach: f32, curve: &Curve, drag: &mut Drag, pos: Pos2, selected: &mut Option<usize>) -> Option<Curve> {
@@ -504,7 +518,7 @@ impl Component for CurveGraph<'_> {
most: (tokens.size.plot.width * MOST_IN_PLOTS).max(least),
bar: tokens.size.icon.sm,
bar_gap: tokens.space.gap.inline,
hit: tokens.size.hit.target,
hit: tokens.size.hit.target * GRAB_TARGETS,
drag_off: tokens.size.icon.sm + tokens.space.gap.inline,
handle: tokens.size.handle.md,
point_fill: cx.color(colors.surface.sunken),
@@ -532,8 +546,11 @@ impl Component for CurveGraph<'_> {
let shown = cx.value().cloned();
if let (true, Some(points)) = (self.points_mode(shown.as_ref()), shown.as_ref().and_then(Curve::points)) {
for (i, p) in points.iter().enumerate() {
let reach = Rect::from_center_size(frame.map.screen(*p), Vec2::splat(cx.style.hit));
cx.part(POINT.at(i as u64), reach).sense(Sense::empty()).priority(HitPriority::new(HitLevel::Body, 0));
let reach = Rect::from_center_size(frame.map.screen(*p), Vec2::splat(2.0 * cx.style.hit));
cx.part(POINT.at(i as u64), reach)
.sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS)
.priority(HitPriority::new(HitLevel::Body, 0))
.pointer_only("the plot's point keys select and move the points");
}
}
}
@@ -560,8 +577,9 @@ impl Component for CurveGraph<'_> {
};
selected = selected.filter(|&i| i < count);
let rules = self.rules();
let reach = cx.style.look.pad + cx.style.drag_off;
let press = cx.part(PLOT).press;
// Never less than the grab radius: a press that grabs a point is never also dragged off.
let reach = (cx.style.look.pad + cx.style.drag_off).max(cx.style.hit);
let press = press_of(cx, count);
let running = cx.gesture().is_some();
let mut held = cx.memory::<Held>().clone();
if let Some(drag) = held.drag
+10 -4
View File
@@ -481,7 +481,13 @@ impl SelectMaskWorkspace {
/// The events of the methods that ran between passes come first. A second pass of a frame reports only what its
/// own input did, since the first pass took the frame's steps and commands. OK closes an open polygon first, so the
/// result carries it.
fn pass(&mut self, ui: &mut Ui, source: &dyn SelectMaskSource, open: Bind<'_, bool>) -> WorkspacePass<SelectMaskEvent, SelectMaskDone> {
fn pass(
&mut self,
ui: &mut Ui,
source: &dyn SelectMaskSource,
revision: u64,
open: Bind<'_, bool>,
) -> WorkspacePass<SelectMaskEvent, SelectMaskDone> {
// pc: crates/ui-egui/src/dialogs/select_mask_ui.rs:1812 `show`, :1375 `keys`, :870
// `enter`, :881 `escape`.
let env = Env::of(ui);
@@ -511,7 +517,7 @@ impl SelectMaskWorkspace {
.sides(|ui, cx| {
let mut guard = this.borrow_mut();
let work: &mut SelectMaskWorkspace = &mut guard;
let status = cx.pending(key.clone(), || source.preview_job(&request)).clone();
let status = cx.pending((revision, key.clone()), || source.preview_job(&request)).clone();
*side_status.borrow_mut() = Some(status.clone());
side_panel_open.set(None);
*side_pick.borrow_mut() = None;
@@ -910,8 +916,8 @@ impl FullWindowWorkspace for SelectMaskWorkspace {
const KEY: &'static str = "select.selectAndMask";
fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass<Self::Event, Self::Result> {
let WorkspaceCx { source, open, .. } = cx;
self.pass(ui, source, open)
let WorkspaceCx { source, revision, open, .. } = cx;
self.pass(ui, source, revision, open)
}
/// The settings, and the bar's `tool`, `mode` (`"add"`, `"subtract"`), `size` (of the current tool), `hardness`,
+133 -2
View File
@@ -2,8 +2,15 @@
//! editor, one gesture per slider drag, the Set of a check box, a preset or a button, and the requests the colour wells
//! file.
use craft_imaging::ui::adjust::{AdjustSession, HueRangeValue};
use craft_ui::testing::trial;
use std::cell::RefCell;
use std::rc::Rc;
use craft_behavior::Mixed;
use craft_imaging::ui::adjust::{AdjustSession, HueRangeValue, HueSaturation, HueSaturationEditor};
use craft_theme::Srgba;
use craft_ui::contract::{Bind, Role};
use craft_ui::testing::{Fixture, trial};
use egui::vec2;
// ---------------------------------------------------------------------------------------------
// Hue/Saturation
@@ -20,6 +27,130 @@ fn range_thumbs_wrap_through_zero() {
assert!(moved.windows(2).all(|pair| pair[0] <= pair[1]));
}
/// What the Hue/Saturation editor's host sees: the value, the range shown and what the editor asked the engine last pass.
struct HueHost {
value: HueSaturation,
shown: Option<usize>,
asked: Vec<(HueSaturation, Srgba)>,
}
/// The Hue/Saturation editor over `start`, with an engine that changes nothing and notes what it was asked.
fn hue_saturation(start: HueSaturation) -> (Fixture, Rc<RefCell<HueHost>>) {
let host = Rc::new(RefCell::new(HueHost { value: start, shown: None, asked: Vec::new() }));
let held = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let mut host = held.borrow_mut();
let HueHost { value, shown, asked } = &mut *host;
let noted = RefCell::new(Vec::new());
let engine = |value: &HueSaturation, color: Srgba| {
noted.borrow_mut().push((*value, color));
color
};
*shown = HueSaturationEditor::new("Hue/Saturation", Bind::bound(value)).adjusted(&engine).show(ui).shown_range;
*asked = noted.into_inner();
});
fixture.room(vec2(400.0, 640.0));
fixture.settle();
(fixture, host)
}
/// The range swatches in order, each with whether it is checked.
fn range_swatches(fixture: &Fixture) -> Vec<(String, bool)> {
let tree = fixture.tree();
fixture
.by_role(Role::RADIO_BUTTON)
.iter()
.map(|swatch| (tree.name_of(swatch.node).unwrap_or_default().to_owned(), tree.toggled_of(swatch.node) == Some(Mixed::Same(true))))
.collect()
}
/// The painted degree texts above the Hue row's title: the centre label, if one shows.
fn centre_labels(fixture: &Fixture) -> Vec<String> {
let texts = fixture.texts();
let hue = texts.iter().find(|text| text.text == "Hue").expect("the Hue row's title").rect;
texts.iter().filter(|text| text.text.contains('°') && text.rect.bottom() <= hue.top() + 0.5).map(|text| text.text.clone()).collect()
}
fn click(fixture: &mut Fixture, label: &str) {
let swatch = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} swatch"));
fixture.click(&swatch).settle();
}
const RANGES: [&str; 7] = ["Master", "Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"];
/// Seven round swatches pick the range, Master selected at first; there is no range dropdown.
#[trial]
fn seven_swatches_replace_the_dropdown_with_master_selected() {
let (fixture, _) = hue_saturation(HueSaturation::default());
let want: Vec<(String, bool)> = RANGES.iter().enumerate().map(|(i, name)| ((*name).to_owned(), i == 0)).collect();
assert_eq!(range_swatches(&fixture), want);
assert!(fixture.by_role(Role::COMBO_BOX).is_empty(), "no range dropdown");
}
/// A click on a swatch shows that range, checks only its swatch and puts the range's centre above the Hue row; Master
/// has no centre.
#[trial]
fn a_click_selects_that_range_and_shows_its_centre() {
let (mut fixture, host) = hue_saturation(HueSaturation::default());
assert!(centre_labels(&fixture).is_empty(), "no centre for Master");
click(&mut fixture, "Blues");
assert_eq!(host.borrow().shown, Some(4));
assert!(range_swatches(&fixture).iter().all(|(name, on)| *on == (name == "Blues")), "{:?}", range_swatches(&fixture));
assert_eq!(centre_labels(&fixture), ["240°"]);
click(&mut fixture, "Reds");
assert_eq!(centre_labels(&fixture), ["0°"]);
click(&mut fixture, "Master");
assert_eq!(host.borrow().shown, None);
assert!(centre_labels(&fixture).is_empty(), "no centre for Master");
}
/// A range's centre is the middle of its fully-on span, within one turn; a Hue shift shows where it moves the centre.
#[trial]
fn centre_labels_name_the_range_centre_and_where_its_hue_moves_it() {
let centres: Vec<f64> = [0, 1, 4, 5].map(|r| HueRangeValue::neutral(r).centre()).to_vec();
assert_eq!(centres, [0.0, 60.0, 240.0, 300.0]);
assert_eq!(HueRangeValue::new(0.0, 0.0, 0.0, [190.0, 220.0, 240.0, 270.0]).centre(), 230.0);
for (shift, shown) in [(30.0, "0° / 30°"), (-30.0, "0° / 330°")] {
let mut start = HueSaturation::default();
start.ranges[0].hue = shift;
let (mut fixture, _) = hue_saturation(start);
click(&mut fixture, "Reds");
assert_eq!(centre_labels(&fixture), [shown]);
}
}
/// Colorize shows one read-only swatch of the colorize colour and no range swatches.
#[trial]
fn colorize_collapses_the_row_into_one_swatch() {
let (fixture, _) = hue_saturation(HueSaturation { hue: 120.0, saturation: 25.0, colorize: true, ..HueSaturation::default() });
assert!(range_swatches(&fixture).is_empty(), "no range swatches");
let tree = fixture.tree();
let wells = fixture.by_role(Role::COLOR_WELL).iter().filter(|well| tree.name_of(well.node) == Some("Colorize Color")).count();
assert_eq!(wells, 1);
}
/// An edited range's swatch shows its centre before and after that range alone: the engine is asked about the centre
/// under a value holding only that range. Back at neutral (what Reset writes) the swatch shows one colour again.
#[trial]
fn an_edited_range_shows_before_and_after() {
let mut start = HueSaturation { hue: 90.0, ..HueSaturation::default() };
start.ranges[0].hue = 30.0;
let (mut fixture, host) = hue_saturation(start);
let mut only_reds = HueSaturation::default();
only_reds.ranges[0].hue = 30.0;
let red = |color: &Srgba| color.r > 0.99 && color.g < 0.01 && color.b < 0.01;
assert!(host.borrow().asked.iter().any(|(value, color)| *value == only_reds && red(color)), "the Reds' centre under the Reds alone");
let reds = fixture.by_label("Reds").expect("the Reds swatch");
assert!(fixture.tree().value_of(reds.node).is_some_and(|value| value.contains(" / ")), "before and after");
host.borrow_mut().value = HueSaturation::default();
fixture.settle();
let shown = host.borrow().value;
assert!(host.borrow().asked.iter().all(|(value, _)| *value == shown), "no range is asked about alone");
let reds = fixture.by_label("Reds").expect("the Reds swatch");
assert!(fixture.tree().value_of(reds.node).is_some_and(|value| !value.contains(" / ")), "one colour");
}
// ---------------------------------------------------------------------------------------------
// The slider table and the session
+59
View File
@@ -86,6 +86,18 @@ impl Rig {
self.fixture.frame(vec![press(pos)]);
}
/// Presses `px` screen pixels from the position of levels `q`.
fn press_near(&mut self, q: [f32; 2], px: Vec2) {
let pos = self.at(q) + px;
self.fixture.frame(vec![moved(pos)]);
self.fixture.frame(vec![press(pos)]);
}
fn release_near(&mut self, q: [f32; 2], px: Vec2) {
self.fixture.frame(vec![release(self.at(q) + px)]);
self.fixture.idle(1);
}
fn move_to(&mut self, q: [f32; 2]) {
self.fixture.frame(vec![moved(self.at(q))]);
}
@@ -136,6 +148,53 @@ fn a_point_dragged_off_the_graph_goes_and_comes_back_within_one_gesture() {
rig.release_at([140.0, 140.0]);
assert_eq!(rig.points(), vec![[0.0, 0.0], [140.0, 140.0], [255.0, 255.0]]);
assert_eq!(rig.kinds().iter().filter(|k| **k == "begin").count(), 1);
// Past the grab radius below the plot it is removed too.
let mut rig = self::rig(&[[0.0, 0.0], [100.0, 0.0], [255.0, 255.0]]);
rig.press_at([100.0, 0.0]);
rig.move_to([100.0, 0.0]);
rig.fixture.frame(vec![moved(rig.at([100.0, 0.0]) + vec2(0.0, 40.0))]);
assert_eq!(rig.points().len(), 2, "removed past the radius");
}
/// A press up to 15 px from a point (straight or diagonal) grabs it; a press 30 px away adds a new one.
#[trial]
fn a_press_near_a_point_grabs_it_and_a_press_far_from_it_adds_one() {
for offset in [vec2(15.0, 0.0), vec2(0.0, -15.0), vec2(10.0, 10.0)] {
let mut rig = rig(&THREE);
rig.press_near([100.0, 100.0], offset);
rig.release_near([100.0, 100.0], offset);
assert_eq!(rig.points().len(), 3, "grabbed at {offset:?}");
assert_eq!(rig.selected.get(), Some(1), "grabbed at {offset:?}");
}
let mut rig = rig(&THREE);
rig.press_near([100.0, 100.0], vec2(30.0, 0.0));
rig.release_near([100.0, 100.0], vec2(30.0, 0.0));
assert_eq!(rig.points().len(), 4, "a press 30 px away adds a point");
}
/// Where two points are closer than the grab radius, a press nearer the second grabs the second.
#[trial]
fn where_grab_areas_overlap_the_nearest_point_is_grabbed() {
let per_px = 1.0 / rig(&THREE).scale.x;
let points = [[0.0, 0.0], [100.0, 100.0], [100.0 + 8.0 * per_px, 100.0], [255.0, 255.0]];
let mut rig = rig(&points);
rig.press_near(points[2], vec2(3.0, 0.0));
rig.release_near(points[2], vec2(3.0, 0.0));
assert_eq!(rig.points().len(), 4);
assert_eq!(rig.selected.get(), Some(2));
}
/// A stationary click that grabs a point outside the plot keeps the point.
#[trial]
fn a_click_that_grabs_a_point_outside_the_plot_keeps_it() {
let points = [[0.0, 0.0], [100.0, 0.0], [255.0, 255.0]];
let mut rig = rig(&points);
let below = vec2(0.0, 15.0);
rig.press_near([100.0, 0.0], below);
rig.release_near([100.0, 0.0], below);
assert_eq!(rig.points().len(), 3);
assert_eq!(rig.selected.get(), Some(1));
}
/// Shown in a panel, the editor's rect holds the whole editor: the Input and Output fields and the hint lie under the
+6 -1
View File
@@ -129,7 +129,7 @@ fn press_label(fixture: &mut Fixture, label: &str) {
#[trial]
fn select_mask_preview_is_asked_for_only_when_it_changes() {
let (mut fixture, _, jobs) = open();
let (mut fixture, app, jobs) = open();
let first = jobs.load(Ordering::SeqCst);
assert_eq!(first, 1, "one preview for the opening state");
fixture.frame(vec![pointer::moved(canvas_point(&fixture, Vec2::ZERO))]);
@@ -137,6 +137,11 @@ fn select_mask_preview_is_asked_for_only_when_it_changes() {
assert_eq!(jobs.load(Ordering::SeqCst), first, "hovering changes nothing");
press_label(&mut fixture, "Invert");
assert_eq!(jobs.load(Ordering::SeqCst), first + 1, "an edit asks for a new preview");
let size = PixelSize::new(DOCUMENT[0], DOCUMENT[1]);
let edited: Arc<dyn SelectMaskSource> = Arc::new(Source { image: Solid { size }, jobs: Arc::clone(&jobs) });
app.borrow_mut().host.get_mut::<HostedWorkspace<SelectMaskWorkspace>>().expect("the workspace is open").set_source(edited);
fixture.settle();
assert_eq!(jobs.load(Ordering::SeqCst), first + 2, "a document edit asks for a new preview of the same request");
}
// The view keys work from inside the workspace with no help from the app: K picks Black & White, X held hides the
@@ -196,6 +196,8 @@ pub struct CxCore<'a> {
pub(crate) fade: Option<crate::contract::steps::Fade>,
/// The focus ring shape each part declared (`focus_shape`), in which step 13 draws the active part's ring.
pub(crate) focus_shapes: Vec<((PartKey, Option<u64>), focus::FocusShape)>,
/// The focus ring shape the component declared for its own ring (`Cx::focus_shape`); its rect when `None`.
pub(crate) focus_shape: Option<focus::FocusShape>,
/// Where the text part reserved the surface in the painter, so the field's surface paints beneath its text.
pub(crate) surface_slot: Option<egui::layers::ShapeIdx>,
/// The editor part as step 8b set it up.
@@ -250,6 +252,13 @@ impl<C: Component> Cx<'_, C> {
self.core.roving_member = true;
}
/// The shape the component's own focus ring takes this pass, as a part's `focus_shape` shapes the part's: the
/// circle inside its rect, or a polygon of points on screen. Called from `update`; a component that does not call
/// it gets the ring round its rect.
pub fn focus_shape(&mut self, shape: focus::FocusShape) {
self.core.focus_shape = Some(shape);
}
/// Runs `command` as this component's own activation would, for a command that is not the component's bound
/// one: resolved against the instances above the component, and not fired when disabled. `source` is where the
/// activation came from (`part_activated` gives it). Returns whether the command was queued.
+1
View File
@@ -417,6 +417,7 @@ fn blank_core<'a>(
node: false,
fade: None,
focus_shapes: Vec::new(),
focus_shape: None,
surface_slot: None,
editor: None,
editor_inputs: Vec::new(),
@@ -111,8 +111,9 @@ pub(crate) fn paint_part_layers(ui: &Ui, env: &Env, core: &CxCore<'_>) {
}
/// Step 13, paint, after `C::paint`: the focus ring of the focused component or its active part, when focus is
/// keyboard-visible. An active part's ring takes the shape the part declared (`focus_shape`), else its rect. Never on
/// `Well` surfaces.
/// keyboard-visible. An active part's ring takes the shape the part declared (`focus_shape`), else its rect; the
/// component's own ring takes the shape it declared (`Cx::focus_shape`), else its rect with its surface's corners. Never
/// on `Well` surfaces.
pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) {
let Some(look) = style.focus() else { return };
let ppp = ui.ctx().pixels_per_point();
@@ -124,7 +125,10 @@ pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) {
let outline = declared.map_or(PaintShape::Rect(rect, egui::CornerRadius::ZERO), |(_, shape)| FocusRing::outline(shape, rect));
ui.painter().extend(FocusRing::shapes(look, FocusKind::Ring, &outline, ppp));
} else if FocusRing::visible(flags) && !well {
let radius = style.surface().map_or(egui::CornerRadius::ZERO, |surface| surface.radius);
ui.painter().extend(FocusRing::shapes(look, FocusKind::Ring, &PaintShape::Rect(core.rect, radius), ppp));
let outline = match &core.focus_shape {
Some(shape) => FocusRing::outline(shape, core.rect),
None => PaintShape::Rect(core.rect, style.surface().map_or(egui::CornerRadius::ZERO, |surface| surface.radius)),
};
ui.painter().extend(FocusRing::shapes(look, FocusKind::Ring, &outline, ppp));
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ pub use segmented::{Segmented, SegmentedStyle};
pub use switch::{Switch, SwitchStyle};
pub use words::ChoiceWords;
pub use swatch::{Swatch, SwatchFace, SwatchMetrics, SwatchOutput, SwatchShape, SwatchStyle};
pub use swatch::{Swatch, SwatchFace, SwatchFill, SwatchImage, SwatchMetrics, SwatchOutput, SwatchShape, SwatchStyle};
pub use swatch_table::{SwatchArrangement, SwatchRows, SwatchTable, SwatchTableOutput, SwatchTableStyle};
/// The well of a check box, radio button or switch track with `radius` corners: the sunken surface, so a bevelled theme
+270 -32
View File
@@ -1,5 +1,6 @@
//! `Swatch`: a colour well. It shows a colour from data, a mixed look for several colours, and reports the activation.
//! It edits nothing: the host opens its picker on a click, or on the `ColorRequest` of a `picker` swatch.
//! `Swatch`: a colour well. It shows a colour from data, a mixed look for several colours, a before and after pair, the
//! hue wheel, a picture or an empty well, and reports the activation. It edits nothing: the host opens its picker on a
//! click, or on the `ColorRequest` of a `picker` swatch.
use super::radio::RadioKind;
use super::words::ChoiceWords;
@@ -7,12 +8,14 @@ use crate::contract::{
Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role,
Sizing, Styled as _, WordSetCx as _,
};
use crate::primitives::{ContentPainterCx, Draw, PaintShape, StrokeWidth};
use crate::primitives::{ContentPainterCx, PaintShape, StrokeWidth, TextureCache};
use crate::runtime::focus::FocusShape;
use crate::runtime::requests::ColorRequest;
use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, UiTokens, resolve_style};
use craft_behavior::{Metrics, Mixed, Sense, Value};
use craft_theme::{Rgba, Srgba, Stateful, States, over};
use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, pos2};
use craft_theme::{Hsb, Rgba, Srgba, Stateful, States, over};
use egui::{Color32, ColorImage, CornerRadius, Mesh, Pos2, Rect, Response, Shape, Vec2, pos2};
use std::sync::Arc;
#[cfg(feature = "suite")]
pub(crate) mod stories;
@@ -20,6 +23,13 @@ pub(crate) mod stories;
/// Opacity of the black or white ring that stands out from a well's colour.
const INNER_EDGE_ALPHA: u8 = 0x80;
/// The points a hue wheel takes along each edge of its well's outline: enough that the colours between them blend
/// into a smooth wheel at any well size.
const SPECTRUM_STEPS: usize = 18;
/// The clear colour: an empty well shows only the checkerboard behind it.
const CLEAR: Srgba = Srgba { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
/// The sizes of a swatch at a control size: what a composition that lays out wells reads.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
@@ -89,8 +99,80 @@ pub enum SwatchShape {
Square,
/// A hexagon well, for a honeycomb of touching cells.
Hexagon,
/// A round well: a circle in the square, a pill when the swatch fills its width. The ranges of Hue/Saturation.
Round,
}
/// What fills a swatch's well.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SwatchFill {
/// A colour over a checkerboard where it is translucent; `Mixed` shows the mixed well with its dash.
Color(Mixed<Srgba>),
/// A colour before and after a change: the first fills the half at the start edge, the second the half at the end
/// edge.
Split(Srgba, Srgba),
/// The hue wheel, red at the top and the hues going clockwise: every colour, as a Master range.
Spectrum,
/// A picture filling the well over the checkerboard, cut to its middle where its aspect differs.
Image(SwatchImage),
/// Nothing: the checkerboard alone, as a clean brush.
Empty,
}
impl From<Srgba> for SwatchFill {
fn from(color: Srgba) -> Self {
SwatchFill::Color(Mixed::Same(color))
}
}
impl From<Mixed<Srgba>> for SwatchFill {
fn from(color: Mixed<Srgba>) -> Self {
SwatchFill::Color(color)
}
}
/// A picture for a swatch's well. [`new`](Self::new) hashes the pixels once into the key the texture cache keeps the
/// picture's texture under, so a well showing the same picture uploads it once and a new picture uploads again.
#[derive(Clone, crate::contract::MemoProps)]
pub struct SwatchImage {
key: u64,
#[memo_props(covered_by = "key", reason = "the key is the hash of the pixels")]
pixels: Arc<ColorImage>,
}
impl SwatchImage {
/// The picture of `pixels`.
pub fn new(pixels: ColorImage) -> Self {
use std::hash::{Hash as _, Hasher as _};
let mut hasher = std::hash::DefaultHasher::new();
pixels.size.hash(&mut hasher);
pixels.pixels.hash(&mut hasher);
SwatchImage { key: hasher.finish(), pixels: Arc::new(pixels) }
}
/// The pixels.
pub fn pixels(&self) -> &ColorImage {
&self.pixels
}
}
impl PartialEq for SwatchImage {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}
impl std::fmt::Debug for SwatchImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SwatchImage").field("key", &self.key).field("size", &self.pixels.size).finish()
}
}
/// The texture cache's key of a swatch picture.
#[derive(Hash)]
struct SwatchImageKey(u64);
/// What a swatch reports.
#[derive(Clone, Debug)]
#[non_exhaustive]
@@ -124,14 +206,17 @@ impl<E> crate::contract::ItemOutput<E> for SwatchOutput {
/// A colour well that shows a colour from data and reports its activation; it edits nothing.
///
/// The colour fills the well over a checkerboard where it has alpha, inside a thin ring that separates it from the
/// panel. A `Mixed` colour shows a neutral well with a dash and has no colour value. A click reports `clicked` and the
/// panel. A `Mixed` colour shows a neutral well with a dash and has no colour value. `with_fill` shows any
/// [`SwatchFill`]: a before and after pair, the hue wheel, a picture or an empty well. A click reports `clicked` and the
/// `activation`. A swatch with a `picker` key also files a `ColorRequest` for that key, opened at the swatch's colour
/// and titled with its label, as `pick_color`; the host opens its colour picker and answers with the picked colour. A
/// `Mixed` swatch files a request with no colour: the host's picker opens empty and the first pick sets the colour.
/// The host writes the pick to every target.
///
/// AccessKit reports a colour well named by the label, whose value is the colour as `#rrggbb` (`#rrggbbaa` when
/// translucent) and whose colour value is the colour; a mixed well has the value "Mixed" and no colour value.
/// translucent) and whose colour value is the colour; a mixed well has the value "Mixed" and no colour value. A split
/// well's value is both colours, "#before / #after", and its colour value the after colour; an empty well's value is
/// "Empty"; the hue wheel and a picture have no value, their label names them.
/// `member` makes the swatch a member of the enclosing `RadioGroup`: a radio button, checked when the group holds its
/// value, whose keys and focus are the group's. `cell` makes it a cell of a table of touching swatches, a list box
/// option. The selected ring is `selected` or a checked radio. `marked` draws a thin edge in the text colour just inside
@@ -141,7 +226,7 @@ impl<E> crate::contract::ItemOutput<E> for SwatchOutput {
pub struct Swatch<T: Value + 'static = ()> {
#[common]
common: Common,
color: Mixed<Srgba>,
fill: SwatchFill,
/// The value this swatch stands for in its `RadioGroup`.
member: Option<T>,
/// A cell of a table of touching swatches: `size.icon.md` square with square corners.
@@ -168,9 +253,14 @@ pub struct Swatch<T: Value + 'static = ()> {
impl Swatch<()> {
/// A swatch of `color` named `label`.
pub fn new(label: impl Into<crate::runtime::env::Label>, color: impl Into<Mixed<Srgba>>) -> Self {
Swatch::with_fill(label, SwatchFill::Color(color.into()))
}
/// A swatch whose well shows `fill`, named `label`.
pub fn with_fill(label: impl Into<crate::runtime::env::Label>, fill: SwatchFill) -> Self {
Swatch {
common: Common::new(),
color: color.into(),
fill,
member: None,
cell: false,
well: false,
@@ -189,7 +279,7 @@ impl<T: Value + 'static> Swatch<T> {
pub fn member<U: Value + 'static>(self, value: U) -> Swatch<U> {
Swatch {
common: self.common,
color: self.color,
fill: self.fill,
member: Some(value),
cell: self.cell,
well: self.well,
@@ -252,6 +342,11 @@ impl<T: Value + 'static> Component for Swatch<T> {
cx.join_roving();
self.checked = group.is(value);
}
match self.shape {
SwatchShape::Square => {}
SwatchShape::Round => cx.focus_shape(FocusShape::Circle),
SwatchShape::Hexagon => cx.focus_shape(FocusShape::Polygon(hexagon(cx.rect))),
}
self.activation = cx.activation().filter(|_| cx.resolved.enabled);
}
@@ -267,46 +362,188 @@ impl<T: Value + 'static> Component for Swatch<T> {
} else if self.cell {
access.role(Role::LIST_BOX_OPTION);
}
match self.color.same() {
Some(color) => {
match &self.fill {
SwatchFill::Color(Mixed::Same(color)) => {
access.value(color.to_hex());
access.color(*color);
}
None => {
SwatchFill::Color(Mixed::Mixed) => {
access.value(cx.words::<ChoiceWords>().swatch_mixed.as_str());
}
SwatchFill::Split(before, after) => {
let (from, to) = (before.to_hex(), after.to_hex());
access.value(cx.words::<ChoiceWords>().swatch_split.fill(&[("before", &from), ("after", &to)]));
access.color(*after);
}
SwatchFill::Empty => {
access.value(cx.words::<ChoiceWords>().swatch_empty.as_str());
}
SwatchFill::Spectrum | SwatchFill::Image(_) => {}
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
paint_face(&ui.draw(), cx.rect, cx.style, cx.state(), self.color, self.marked, self.shape);
let face = Face { style: cx.style, state: cx.state(), fill: &self.fill, marked: self.marked, shape: self.shape, rtl: cx.flow.is_rtl() };
face.paint(&ui.content_painter(cx), cx.rect);
}
fn finish(self, cx: Cx<'_, Self>) -> SwatchOutput {
let pick_color =
self.picker.filter(|_| self.activation.is_some()).map(|key| ColorRequest::new(key, self.color.same().copied()).title(cx.label()));
let color = match &self.fill {
SwatchFill::Color(color) => color.same().copied(),
_ => None,
};
let pick_color = self.picker.filter(|_| self.activation.is_some()).map(|key| ColorRequest::new(key, color).title(cx.label()));
SwatchOutput { response: cx.response.clone(), clicked: self.activation.is_some(), activation: self.activation, pick_color }
}
}
/// The one swatch face painter: the well of `color` in `well` (a checkerboard behind a translucent colour, the dash
/// of a mixed one), then the outline ring, the mark when `marked`, and the selection ring, in `state`.
fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed<Srgba>, marked: bool, shape: SwatchShape) {
let outline = |rect: Rect| match shape {
SwatchShape::Square => PaintShape::Rect(rect, style.radius),
SwatchShape::Hexagon => PaintShape::Polygon(hexagon(rect)),
/// What the one swatch face painter paints: the well of `fill` in `shape`, then the outline ring, the mark when
/// `marked`, and the selection ring, in `state`. A split well's before half is at the start edge, mirrored when `rtl`.
struct Face<'a> {
style: &'a SwatchStyle,
state: &'a StateSet,
fill: &'a SwatchFill,
marked: bool,
shape: SwatchShape,
rtl: bool,
}
impl Face<'_> {
fn paint(&self, painter: &ContentPainterCx<'_>, well: Rect) {
let style = self.style;
let edge = self.outline(well);
self.paint_fill(painter, well);
painter.with_draw(|draw| {
draw.stroke(&edge, StrokeWidth::Thin, self.state.resolve(&style.edge));
if self.marked {
let inside = self.outline(well.shrink(draw.width(StrokeWidth::Thin)));
draw.stroke(&inside, StrokeWidth::Thin, style.mark);
}
draw.stroke(&edge, StrokeWidth::Thick, self.state.resolve(&style.ring));
});
}
/// The corners of a well in `rect`: the style's for a square, half the shorter side for a round one (a circle,
/// or a pill when wider than tall).
fn radius(&self, rect: Rect) -> CornerRadius {
match self.shape {
SwatchShape::Round => UiTokens::corner(rect.width().min(rect.height()) / 2.0),
SwatchShape::Square | SwatchShape::Hexagon => self.style.radius,
}
}
/// The outline of a well in `rect`.
fn outline(&self, rect: Rect) -> PaintShape {
match self.shape {
SwatchShape::Square | SwatchShape::Round => PaintShape::Rect(rect, self.radius(rect)),
SwatchShape::Hexagon => PaintShape::Polygon(hexagon(rect)),
}
}
fn paint_fill(&self, painter: &ContentPainterCx<'_>, well: Rect) {
match self.fill {
SwatchFill::Color(color) => self.color_well(painter, well, color.same().copied()),
SwatchFill::Empty => self.color_well(painter, well, Some(CLEAR)),
SwatchFill::Split(before, after) => {
self.color_well(painter, well, Some(*before));
let middle = well.center().x;
let end = if self.rtl {
Rect::from_x_y_ranges(well.left()..=middle, well.y_range())
} else {
Rect::from_x_y_ranges(middle..=well.right(), well.y_range())
};
painter.clipped(end, |painter| self.color_well(painter, well, Some(*after)));
}
SwatchFill::Spectrum => {
let mesh = spectrum_mesh(well.center(), &self.corners(well));
match self.shape {
SwatchShape::Hexagon => painter.data_shapes([Shape::mesh(mesh)]),
SwatchShape::Square | SwatchShape::Round => painter.mesh_in(well, self.radius(well), mesh),
}
}
SwatchFill::Image(image) => {
self.color_well(painter, well, Some(CLEAR));
let texture = TextureCache::texture(painter.painter.ctx(), SwatchImageKey(image.key), || image.pixels().clone());
let uv = cover_uv(image.pixels().size, well.size());
match self.shape {
SwatchShape::Hexagon => {
let corners = hexagon(well);
let mut mesh = Mesh::with_texture(texture);
for &pos in &corners {
let at = (pos - well.min) / well.size();
mesh.vertices.push(egui::epaint::Vertex { pos, uv: uv.lerp_inside(at), color: Color32::WHITE });
}
for k in 1..corners.len() as u32 - 1 {
mesh.add_triangle(0, k, k + 1);
}
painter.data_shapes([Shape::mesh(mesh)]);
}
SwatchShape::Square | SwatchShape::Round => painter.picture(texture, well, uv, f32::from(self.radius(well).nw)),
}
}
}
}
/// The well of `color` (the checkerboard behind a translucent one, the dash of `None`) over `well`.
fn color_well(&self, painter: &ContentPainterCx<'_>, well: Rect, color: Option<Srgba>) {
painter.with_draw(|draw| match self.shape {
SwatchShape::Hexagon => draw.swatch_polygon_well(&hexagon(well), color),
SwatchShape::Square | SwatchShape::Round => draw.swatch_well(well, self.radius(well), color),
});
}
/// The corners of the polygon a hue wheel is laid over: the hexagon, or the rect, whose rounded corners
/// `mesh_in` pulls the wheel inside.
fn corners(&self, well: Rect) -> Vec<Pos2> {
match self.shape {
SwatchShape::Hexagon => hexagon(well),
SwatchShape::Square | SwatchShape::Round => vec![well.left_top(), well.right_top(), well.right_bottom(), well.left_bottom()],
}
}
}
/// The hue wheel over the convex polygon `corners` round `centre`: full colours, each point along an edge the hue of
/// its direction from the centre, red straight up and the hues going clockwise. Each slice has its own centre vertex
/// in the slice's middle hue, so the hues meet at the centre without a blend towards one colour.
fn spectrum_mesh(centre: Pos2, corners: &[Pos2]) -> Mesh {
let hue = |pos: Pos2| {
let d = pos - centre;
let degrees = d.x.atan2(-d.y).to_degrees().rem_euclid(360.0);
Color32::from(Srgba::from_hsb(Hsb { h: degrees, s: 1.0, b: 1.0 }))
};
let edge = outline(well);
match shape {
SwatchShape::Square => draw.swatch_well(well, style.radius, color.same().copied()),
SwatchShape::Hexagon => draw.swatch_polygon_well(&hexagon(well), color.same().copied()),
let rim: Vec<Pos2> = corners
.iter()
.enumerate()
.flat_map(|(k, &from)| {
let to = corners[(k + 1) % corners.len()];
(0..SPECTRUM_STEPS).map(move |step| from.lerp(to, step as f32 / SPECTRUM_STEPS as f32))
})
.collect();
let mut mesh = Mesh::default();
for (k, &from) in rim.iter().enumerate() {
let to = rim[(k + 1) % rim.len()];
let at = mesh.vertices.len() as u32;
mesh.colored_vertex(centre, hue(from.lerp(to, 0.5)));
mesh.colored_vertex(from, hue(from));
mesh.colored_vertex(to, hue(to));
mesh.add_triangle(at, at + 1, at + 2);
}
draw.stroke(&edge, StrokeWidth::Thin, state.resolve(&style.edge));
if marked {
let inside = outline(well.shrink(draw.width(StrokeWidth::Thin)));
draw.stroke(&inside, StrokeWidth::Thin, style.mark);
mesh
}
/// The part of a picture of `size` pixels that covers a well of `well` points at the picture's aspect: all of it
/// along the side that fits, the middle along the other.
fn cover_uv(size: [usize; 2], well: Vec2) -> Rect {
let (width, height) = (size[0].max(1) as f32, size[1].max(1) as f32);
let picture = width / height;
let room = if well.y > 0.0 { well.x / well.y } else { 1.0 };
if picture > room {
let share = room / picture;
Rect::from_x_y_ranges((0.5 - share / 2.0)..=(0.5 + share / 2.0), 0.0..=1.0)
} else {
let share = picture / room;
Rect::from_x_y_ranges(0.0..=1.0, (0.5 - share / 2.0)..=(0.5 + share / 2.0))
}
draw.stroke(&edge, StrokeWidth::Thick, state.resolve(&style.ring));
}
/// The corners of the pointy-top hexagon inscribed in `rect`: the vertices at the middle of the top and bottom edges,
@@ -353,6 +590,7 @@ impl SwatchFace {
let style = resolve_style(&scope, key, cx.painter.ctx(), Swatch::<()>::style);
let (flags, on) = if self.selected { (Flags::SELECTED, 1.0) } else { (Flags::empty(), 0.0) };
let state = StateSet::new(State::Rest, flags, StateMix::new(0.0, 0.0, on));
cx.with_draw(|draw| paint_face(draw, rect, &style, &state, self.color, false, SwatchShape::Square));
let fill = SwatchFill::Color(self.color);
Face { style: &style, state: &state, fill: &fill, marked: false, shape: SwatchShape::Square, rtl: false }.paint(cx, rect);
}
}
+48 -1
View File
@@ -1,9 +1,10 @@
//! Stories of `Swatch`.
use super::{Swatch, SwatchShape};
use super::{Swatch, SwatchFill, SwatchImage, SwatchShape};
use crate::choice::RadioGroup;
use crate::contract::{Gap, Props as _, Show as _, ShowContainer as _};
use crate::layout_components::{Row, Stack};
use crate::testing::pictures::sample_picture;
use crate::testing::{Drive, StoryData, StoryOutput, show_as_only_item, story};
use craft_behavior::Mixed;
use craft_theme::Srgba;
@@ -81,6 +82,52 @@ fn swatch_hexagon(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Swatch::new("Hexagon", BLUE).shape(SwatchShape::Hexagon).show(ui).into()
}
/// A round well.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_round(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Swatch::new("Round", BLUE).shape(SwatchShape::Round).show(ui).into()
}
/// A colour before and after a change, in a square and a round well: before at the start edge.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_split(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Row::new().show(ui, |ui, _| {
for shape in [SwatchShape::Square, SwatchShape::Round] {
Swatch::with_fill("Reds", SwatchFill::Split(PALETTE[0], PALETTE[2])).shape(shape).show(ui);
}
});
StoryOutput::default()
}
/// The hue wheel in a square and a round well.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_spectrum(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Row::new().show(ui, |ui, _| {
for shape in [SwatchShape::Square, SwatchShape::Round] {
Swatch::with_fill("Master", SwatchFill::Spectrum).shape(shape).show(ui);
}
});
StoryOutput::default()
}
/// A picture in a square and a round well.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_image(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let image = SwatchImage::new(sample_picture(7, [64, 64]));
Row::new().show(ui, |ui, _| {
for shape in [SwatchShape::Square, SwatchShape::Round] {
Swatch::with_fill("Sampled", SwatchFill::Image(image.clone())).shape(shape).show(ui);
}
});
StoryOutput::default()
}
/// An empty well: the checkerboard alone.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_empty(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Swatch::with_fill("Empty", SwatchFill::Empty).show(ui).into()
}
/// A well and a line that counts its clicks.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_clicks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+2
View File
@@ -5,6 +5,8 @@ craft_ui::words! {
pub struct ChoiceWords {
unrated: "choice.ratingUnrated" = "Unrated";
swatch_mixed: "choice.swatchMixed" = "Mixed";
swatch_empty: "choice.swatchEmpty" = "Empty";
swatch_split: template "choice.swatchSplit" = "{before} / {after}";
stars: count "choice.ratingStars" = "{n} star" | "{n} stars";
}
}
@@ -7,5 +7,6 @@ pub(crate) mod select_list;
pub(crate) mod select_measure;
pub(crate) mod select_steps;
pub(crate) mod select_width;
pub(crate) mod swatch;
pub(crate) mod swatch_table;
pub(crate) mod tree_list;
@@ -0,0 +1,41 @@
//! `Swatch`: the focus ring of a shaped well follows its outline.
use craft_theme::Srgba;
use craft_ui::choice::{RadioGroup, Swatch, SwatchShape};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::layout_components::Row;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Shape, vec2};
/// Every shape of the frame, groups opened.
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
}
/// A focused round member swatch draws its ring as a circle round its well, a square one round its rect: the component's
/// declared focus shape (`Cx::focus_shape`) reaches the ring.
#[trial]
fn a_focused_round_swatch_has_a_round_ring() {
for (shape, round) in [(SwatchShape::Round, true), (SwatchShape::Square, false)] {
let mut fixture = Fixture::new(move |ui| {
let _ = RadioGroup::new("Ranges", Bind::given(0u8)).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
for n in 0..3u8 {
Swatch::new(format!("Range {n}"), Srgba::rgb(0.2, 0.4, 0.8)).shape(shape).member(n).show(ui);
}
});
});
});
fixture.room(vec2(300.0, 100.0));
fixture.settle();
fixture.key(Key::Tab, Modifiers::NONE).settle();
let well = fixture.by_label("Range 0").expect("the first swatch").rect;
let rings = flat(fixture.frame_shapes())
.into_iter()
.filter(|shape| {
matches!(shape, Shape::Circle(circle) if circle.stroke.width > 0.0 && circle.center.distance(well.center()) < 0.5 && circle.radius >= well.width() / 2.0)
})
.count();
assert_eq!(rings > 0, round, "{shape:?}: a circle ring round the focused well");
}
}