mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
widgets-w4: net change of 1 commits
- widgets-w4: written from its sheet
This commit is contained in:
+102
-21
@@ -4,15 +4,15 @@ use super::channels::{QUANTIZE_CELLS, channel_range, channel_step, quantized, se
|
||||
use super::ramp::Gamut;
|
||||
use crate::AreaMode;
|
||||
use craft_behavior::{Metrics, Mixed, Proposal, Sense};
|
||||
use craft_theme::ModelValues;
|
||||
use craft_theme::{ModelValues, Srgba};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, Sizing, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use craft_ui::style::{ComponentStyle, MarkerLook, StyleColor, StyleCx};
|
||||
use craft_ui::value_drag::{PointMark, PointPicker};
|
||||
use egui::{Mesh, Pos2, Rect, Vec2, pos2};
|
||||
use egui::{Color32, Mesh, Painter, Pos2, Rect, Stroke, Vec2, pos2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
@@ -20,12 +20,21 @@ mod stories;
|
||||
/// Vertices along each side of the area's colour mesh (PhotoCraft's 32).
|
||||
const MESH: usize = 32;
|
||||
|
||||
/// Cells along each side of the gamut shading grid.
|
||||
const GRID: usize = 16;
|
||||
|
||||
/// The style of a colour area: the field is a point picker, which brings its own look.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorAreaStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The fill of a cell the gamut moves (`surface.scrim`).
|
||||
#[style(skip)]
|
||||
scrim: StyleColor,
|
||||
/// The marker look: its halo is the dark edge line and its ring the light one.
|
||||
#[style(skip)]
|
||||
marker: MarkerLook,
|
||||
}
|
||||
|
||||
/// The 2D field of a colour picker: two components of the colour across and down, the others fixed, as an
|
||||
@@ -98,7 +107,7 @@ impl<'a> ColorArea<'a> {
|
||||
/// quantise steps. `ColorHud` drives it with the host's pointer.
|
||||
pub(crate) fn value_at(&self, rect: Rect, values: &ModelValues, at: Pos2) -> ModelValues {
|
||||
let mut mine = *values;
|
||||
if let Some(point) = self.picker(Some(values), false).value_at(rect, at) {
|
||||
if let Some(point) = self.picker(Some(values), false, None).value_at(rect, at) {
|
||||
self.settle_into(&mut mine, point.map(Some));
|
||||
}
|
||||
mine
|
||||
@@ -107,7 +116,7 @@ impl<'a> ColorArea<'a> {
|
||||
/// Where `values` stands in `rect`: the picker's own value-to-point mapping.
|
||||
pub(crate) fn point_in(&self, rect: Rect, values: &ModelValues) -> Pos2 {
|
||||
let [across, down] = self.channels();
|
||||
let picker = self.picker(Some(values), false);
|
||||
let picker = self.picker(Some(values), false, None);
|
||||
picker.position([values.values[across], values.values[down]].map(f64::from), picker.plot(rect))
|
||||
}
|
||||
|
||||
@@ -125,11 +134,36 @@ impl<'a> ColorArea<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker over `shown`, whose backdrop paints the field of `base`.
|
||||
fn picker<'c>(&self, shown: Option<&ModelValues>, field: bool) -> PointPicker<'c> {
|
||||
/// The values the field is painted around: `shown`, or the model's defaults.
|
||||
fn base(&self, shown: Option<&ModelValues>) -> ModelValues {
|
||||
shown.copied().unwrap_or_else(|| ModelValues::new(self.mode.model().id(), &[]))
|
||||
}
|
||||
|
||||
/// The shading of the cells the gamut moves, `None` without a gamut. The flags are computed here, in the pass, so the
|
||||
/// backdrop closure owns plain data: `Gamut` is not `Clone`.
|
||||
fn shading(&self, base: &ModelValues, style: &ColorAreaStyle) -> Option<Shading> {
|
||||
let gamut = self.gamut.as_ref()?;
|
||||
let at = field_at(self.mode, *base);
|
||||
let mut flags = [false; GRID * GRID];
|
||||
for (index, flag) in flags.iter_mut().enumerate() {
|
||||
let (col, row) = (index % GRID, index / GRID);
|
||||
let centre = |at: usize| (at as f32 + 0.5) / GRID as f32;
|
||||
*flag = gamut.nearest(at(centre(col), centre(row))).is_some();
|
||||
}
|
||||
let (dark, light) = (style.marker.halo, style.marker.ring);
|
||||
Some(Shading {
|
||||
flags,
|
||||
scrim: style.scrim.egui(),
|
||||
dark: Stroke::new(style.marker.ring_width, dark.egui()),
|
||||
light: Stroke::new(style.marker.halo_width, light.egui()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The picker over `shown`; with `field` its backdrop paints the colours of the field (`shading` over them).
|
||||
fn picker<'c>(&self, shown: Option<&ModelValues>, field: bool, shading: Option<Shading>) -> PointPicker<'c> {
|
||||
let model = self.mode.model();
|
||||
let [across, down] = self.channels();
|
||||
let base = shown.copied().unwrap_or_else(|| ModelValues::new(model.id(), &[]));
|
||||
let base = self.base(shown);
|
||||
let point = match shown {
|
||||
Some(values) => Mixed::each([values.values[across], values.values[down]].map(f64::from)),
|
||||
None => [Mixed::Mixed; 2],
|
||||
@@ -148,7 +182,7 @@ impl<'a> ColorArea<'a> {
|
||||
};
|
||||
picker = picker.same(move |from, to| color(from) == color(to));
|
||||
}
|
||||
if field { picker.backdrop(move |painter: &ContentPainterCx, plot: Rect| paint_field(painter, plot, mode, &base, levels)) } else { picker }
|
||||
if field { picker.backdrop(move |painter: &ContentPainterCx, plot: Rect| paint_field(painter, plot, mode, &base, levels, shading)) } else { picker }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,8 +196,8 @@ impl Component for ColorArea<'_> {
|
||||
type Style = ColorAreaStyle;
|
||||
type Output = EditResponse<ModelValues>;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: ColorAreaStyleKey) -> ColorAreaStyle {
|
||||
ColorAreaStyle { metrics: Metrics::new() }
|
||||
fn style(cx: &StyleCx<'_>, _: ColorAreaStyleKey) -> ColorAreaStyle {
|
||||
ColorAreaStyle { metrics: Metrics::new(), scrim: cx.color(cx.tokens.color.surface.scrim), marker: cx.marker() }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
@@ -204,7 +238,8 @@ impl Component for ColorArea<'_> {
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let picker = self.picker(cx.value(), true).label(cx.label());
|
||||
let shading = self.shading(&self.base(cx.value()), &cx.style);
|
||||
let picker = self.picker(cx.value(), true, shading).label(cx.label());
|
||||
let edit = ui.inner("picker", cx.rect, picker);
|
||||
let start = ModelValues::new(self.mode.model().id(), &[]);
|
||||
cx.adopt(&edit, &start, |point, mine| self.settle_into(mine, [0, 1].map(|axis| point[axis].same().copied())));
|
||||
@@ -215,28 +250,74 @@ impl Component for ColorArea<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the colours of the field in `plot`: a mesh blending between 32 by 32 vertices, or with `levels` flat cells
|
||||
/// of the snapped colours.
|
||||
fn paint_field(painter: &ContentPainterCx, plot: Rect, mode: AreaMode, base: &ModelValues, levels: Option<usize>) {
|
||||
/// The cells of the gamut shading and how they are drawn. `flags[row * GRID + col]` is whether the cell is shaded, row 0
|
||||
/// at the top and col 0 at the left.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Shading {
|
||||
flags: [bool; GRID * GRID],
|
||||
scrim: Color32,
|
||||
dark: Stroke,
|
||||
light: Stroke,
|
||||
}
|
||||
|
||||
/// The colour at (`fx`, `fy`) of the field around `base`: across grows right and down grows from the top.
|
||||
fn field_at(mode: AreaMode, base: ModelValues) -> impl Fn(f32, f32) -> Srgba {
|
||||
let model = mode.model();
|
||||
let [across, down] = mode.area();
|
||||
let (x, y) = (channel_range(model, across), channel_range(model, down));
|
||||
let at = |fx: f32, fy: f32| {
|
||||
let mut values = *base;
|
||||
move |fx, fy| {
|
||||
let mut values = base;
|
||||
values.values[across] = egui::lerp(*x.start() as f32..=*x.end() as f32, fx);
|
||||
values.values[down] = egui::lerp(*y.end() as f32..=*y.start() as f32, fy);
|
||||
model.to_srgb(&values.values)
|
||||
};
|
||||
mode.model().to_srgb(&values.values)
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the colours of the field in `plot`: a mesh blending between 32 by 32 vertices, or with `levels` flat cells
|
||||
/// of the snapped colours; then the gamut `shading`.
|
||||
fn paint_field(painter: &ContentPainterCx, plot: Rect, mode: AreaMode, base: &ModelValues, levels: Option<usize>, shading: Option<Shading>) {
|
||||
let at = field_at(mode, *base);
|
||||
let mut mesh = Mesh::default();
|
||||
match levels {
|
||||
Some(levels) => flat_cells(&mut mesh, plot, &at, levels),
|
||||
None => smooth_mesh(&mut mesh, plot, &at),
|
||||
}
|
||||
painter.painter.add(mesh);
|
||||
if let Some(shading) = shading {
|
||||
paint_shading(&painter.painter, plot, &shading);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills the shaded cells and draws the lines between shaded and unshaded neighbours, the dark one first so the light
|
||||
/// one lies over it.
|
||||
fn paint_shading(painter: &Painter, plot: Rect, shading: &Shading) {
|
||||
let cell = plot.size() / GRID as f32;
|
||||
let point = |col: usize, row: usize| pos2(plot.left() + col as f32 * cell.x, plot.top() + row as f32 * cell.y);
|
||||
let shaded = |col: usize, row: usize| shading.flags[row * GRID + col];
|
||||
let mut edges = Vec::new();
|
||||
for row in 0..GRID {
|
||||
for col in 0..GRID {
|
||||
let here = shaded(col, row);
|
||||
if here {
|
||||
painter.rect_filled(Rect::from_min_size(point(col, row), cell), 0.0, shading.scrim);
|
||||
}
|
||||
if col + 1 < GRID && here != shaded(col + 1, row) {
|
||||
edges.push([point(col + 1, row), point(col + 1, row + 1)]);
|
||||
}
|
||||
if row + 1 < GRID && here != shaded(col, row + 1) {
|
||||
edges.push([point(col, row + 1), point(col + 1, row + 1)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for stroke in [shading.dark, shading.light] {
|
||||
for edge in &edges {
|
||||
painter.line_segment(*edge, stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colours as a mesh of vertices, blending between them.
|
||||
fn smooth_mesh(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> craft_theme::Srgba) {
|
||||
fn smooth_mesh(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> Srgba) {
|
||||
let last = (MESH - 1) as f32;
|
||||
for row in 0..MESH {
|
||||
for col in 0..MESH {
|
||||
@@ -255,7 +336,7 @@ fn smooth_mesh(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> craft_theme
|
||||
}
|
||||
|
||||
/// The colours as `QUANTIZE_CELLS` by `QUANTIZE_CELLS` flat cells, each the snapped colour at its centre.
|
||||
fn flat_cells(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> craft_theme::Srgba, levels: usize) {
|
||||
fn flat_cells(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> Srgba, levels: usize) {
|
||||
let n = QUANTIZE_CELLS;
|
||||
let (w, h) = (plot.width() / n as f32, plot.height() / n as f32);
|
||||
for row in 0..n {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Stories of `ColorArea`: its two shapes, a web-safe area, a refused value and a disabled one.
|
||||
|
||||
use super::{AreaShape, ColorArea};
|
||||
use crate::ui::Gamut;
|
||||
use crate::AreaMode;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, Validity};
|
||||
@@ -43,3 +44,15 @@ fn color_area_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).enabled(false).show(ui).into()
|
||||
}
|
||||
|
||||
/// A gamut that moves the pale colours (the top-left quarter of the hue field) to black: the cells it moves are shaded
|
||||
/// and edged.
|
||||
#[story(ColorArea<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_area_gamut(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
let pale_to_black = Gamut::new(|color: Srgba| {
|
||||
let (high, low) = (color.r.max(color.g).max(color.b), color.r.min(color.g).min(color.b));
|
||||
if high > 0.5 && low > high / 2.0 { Srgba::rgb(0.0, 0.0, 0.0) } else { color }
|
||||
});
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).shape(AreaShape::Square).gamut(pale_to_black).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The colour area's gamut shading: which cells of the 16 × 16 grid are shaded and where the edges run.
|
||||
|
||||
use craft_color_ui::AreaMode;
|
||||
use craft_color_ui::ui::{AreaShape, ColorArea, Gamut};
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial};
|
||||
use egui::{Color32, Pos2, Rect, Shape, Ui, Vec2};
|
||||
|
||||
const GRID: f32 = 16.0;
|
||||
|
||||
fn area(ui: &mut Ui, data: &mut StoryData, gamut: Gamut<'static>) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).shape(AreaShape::Square).gamut(gamut).show(ui).into()
|
||||
}
|
||||
|
||||
/// Moves the pale colours of the top-left quarter (saturation under a half, brightness over a half) to black.
|
||||
fn top_left_quarter(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let to_black = |color: Srgba| {
|
||||
let (high, low) = (color.r.max(color.g).max(color.b), color.r.min(color.g).min(color.b));
|
||||
if high > 0.5 && low > high / 2.0 { Srgba::rgb(0.0, 0.0, 0.0) } else { color }
|
||||
};
|
||||
area(ui, data, Gamut::new(to_black))
|
||||
}
|
||||
|
||||
fn moves_nothing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
area(ui, data, Gamut::new(|color: Srgba| color))
|
||||
}
|
||||
|
||||
/// The fills that make up the shading: the largest group of rectangles of one fill and one size.
|
||||
fn shaded_cells(shapes: &[Shape]) -> Vec<Rect> {
|
||||
let rects: Vec<(Color32, Rect)> = shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::Rect(rect) => Some((rect.fill, rect.rect)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let same = |a: &(Color32, Rect), b: &(Color32, Rect)| a.0 == b.0 && (a.1.size() - b.1.size()).abs().max_elem() < 1e-3;
|
||||
let group = rects.iter().map(|pivot| rects.iter().filter(|other| same(pivot, other)).copied().collect::<Vec<_>>()).max_by_key(Vec::len);
|
||||
group.filter(|group| group.len() > 1).map(|group| group.into_iter().map(|(_, rect)| rect).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn near(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < 1e-2
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_gamut_shades_the_cells_it_moves_and_edges_them() {
|
||||
let mut fixture = Fixture::story(&Story::new("gamut", top_left_quarter));
|
||||
fixture.settle();
|
||||
let shapes = fixture.frame_shapes();
|
||||
let cells = shaded_cells(&shapes);
|
||||
assert_eq!(cells.len(), 64, "the 8 × 8 cells of the top-left quarter are shaded");
|
||||
let min = cells.iter().fold(Pos2::new(f32::MAX, f32::MAX), |min, cell| min.min(cell.min));
|
||||
let size: Vec2 = cells[0].size();
|
||||
for row in 0..8 {
|
||||
for col in 0..8 {
|
||||
let at = min + Vec2::new(col as f32 * size.x, row as f32 * size.y);
|
||||
assert!(cells.iter().any(|shaded| near(shaded.min.x, at.x) && near(shaded.min.y, at.y)), "cell {col},{row} is shaded");
|
||||
}
|
||||
}
|
||||
|
||||
// Edges lie on grid points of the field and only along the right and bottom side of the shaded block.
|
||||
let (right, bottom) = (min.x + 8.0 * size.x, min.y + 8.0 * size.y);
|
||||
let on_grid = |point: Pos2| {
|
||||
let (x, y) = ((point.x - min.x) / size.x, (point.y - min.y) / size.y);
|
||||
near(x, x.round()) && near(y, y.round()) && (0.0..=GRID + 0.01).contains(&x) && (0.0..=GRID + 0.01).contains(&y)
|
||||
};
|
||||
let edges: Vec<[Pos2; 2]> = shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::LineSegment { points, .. } if points.iter().all(|point| on_grid(*point)) => Some(*points),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(edges.len(), 2 * 16, "a dark and a light line along each of the 16 cell sides of the boundary");
|
||||
for [from, to] in edges {
|
||||
let vertical = near(from.x, right) && near(to.x, right) && from.y > min.y - 1e-2 && to.y < bottom + 1e-2;
|
||||
let horizontal = near(from.y, bottom) && near(to.y, bottom) && from.x > min.x - 1e-2 && to.x < right + 1e-2;
|
||||
assert!(vertical || horizontal, "{from:?} to {to:?} lies on the boundary of the shaded block");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_gamut_that_moves_nothing_shades_nothing() {
|
||||
let mut fixture = Fixture::story(&Story::new("in gamut", moves_nothing));
|
||||
fixture.settle();
|
||||
assert!(shaded_cells(&fixture.frame_shapes()).is_empty());
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The screen tests of craft-color-ui, folded into the lib's test target.
|
||||
|
||||
mod area_gamut;
|
||||
mod color_parts;
|
||||
mod gradient_bar;
|
||||
mod paint_list;
|
||||
|
||||
Reference in New Issue
Block a user