mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 05:37:04 +00:00
Contract stubs: craft-color gradient module, wip
This commit is contained in:
Generated
+1
@@ -1615,6 +1615,7 @@ dependencies = [
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -19,7 +19,7 @@ workspace = true
|
||||
[features]
|
||||
default = []
|
||||
# The colour widgets (`craft_color::ui`).
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-settings", "dep:craft-window", "craft-platform/screen"]
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-settings", "dep:craft-window", "craft-platform/screen", "dep:serde_json"]
|
||||
# Screenshot and input tests of the widgets with egui_kittest (desktop only).
|
||||
screen-testing = ["ui", "craft-ui/testing"]
|
||||
|
||||
@@ -36,6 +36,7 @@ craft-ui = { workspace = true, optional = true }
|
||||
craft-window = { workspace = true, optional = true }
|
||||
egui = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-ui = { workspace = true, features = ["testing"] }
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
//! The gradient stop model and its rules, without egui: [`GradientStops`] and the pure functions of [`stops`].
|
||||
//!
|
||||
//! Colour stops and opacity stops live in two rows ([`StopRows::Split`]) or in one, the opacity being the colour's alpha
|
||||
//! ([`StopRows::Combined`]). The rules are pure functions of the stops, so an on-canvas gradient line and the stop bar
|
||||
//! cannot disagree. A ramp samples through a [`Sampler`]; the default mixes straight lines in encoded sRGB.
|
||||
|
||||
pub mod stops;
|
||||
mod value;
|
||||
|
||||
pub use stops::{Sampler, StopRules, default_sampler};
|
||||
pub use value::{ColorStop, GradientStops, OpacityStop, StopRow, StopRows};
|
||||
@@ -0,0 +1,345 @@
|
||||
//! The stop rules of a gradient bar, as pure functions the bar and an on-canvas gradient line
|
||||
//! share. Every edit returns the new stops and the index of the stop it touched, so a selection
|
||||
//! follows a stop across reorders; `None` when the rules refuse the edit.
|
||||
//!
|
||||
//! Stops keep their own midpoints and tags when they move. Locations are clamped to 0..=1; the
|
||||
//! bar rounds pointer locations with [`round_location`] before it gives them to the rules, so a
|
||||
//! typed location keeps its decimals.
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
|
||||
use super::value::{ColorStop, GradientStops, OpacityStop, StopRow, StopRows};
|
||||
|
||||
/// Gives the colour, with alpha, of a gradient at a location 0..=1. Draws the ramp and colours
|
||||
/// new stops; the default is [`default_sampler`].
|
||||
pub type Sampler = dyn Fn(&GradientStops, f32) -> Srgba;
|
||||
|
||||
/// What a host allows of the stops of one row.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct StopRules {
|
||||
/// The row layout.
|
||||
pub rows: StopRows,
|
||||
/// Fewest stops a row keeps (PhotoCraft 2, EffectCraft 1).
|
||||
pub min: usize,
|
||||
/// Most stops a row holds (PhotoCraft 1024, its Gradient Map 64).
|
||||
pub max: usize,
|
||||
/// The range a midpoint may take (PhotoCraft 0.05..=0.95; InDesign and Illustrator 0.13..=0.87).
|
||||
pub midpoint: RangeInclusive<f32>,
|
||||
}
|
||||
|
||||
impl StopRules {
|
||||
/// The default rules for `rows`.
|
||||
pub fn new(rows: StopRows) -> Self {
|
||||
Self { rows, ..Self::default() }
|
||||
}
|
||||
|
||||
/// The fewest and most stops a row keeps; `max` is at least `min`.
|
||||
#[must_use]
|
||||
pub fn stops(mut self, min: usize, max: usize) -> Self {
|
||||
self.min = min;
|
||||
self.max = max.max(min);
|
||||
self
|
||||
}
|
||||
|
||||
/// The range a midpoint may take.
|
||||
#[must_use]
|
||||
pub fn midpoint_range(mut self, range: RangeInclusive<f32>) -> Self {
|
||||
self.midpoint = range;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for StopRules {
|
||||
fn default() -> Self {
|
||||
Self { rows: StopRows::Split, min: 2, max: 1024, midpoint: 0.05..=0.95 }
|
||||
}
|
||||
}
|
||||
|
||||
/// One Left or Right press moves a stop or midpoint by this share of the bar or line.
|
||||
pub const STOP_STEP: f32 = 0.01;
|
||||
/// One Shift press.
|
||||
pub const STOP_STEP_FAR: f32 = 0.10;
|
||||
|
||||
/// `location` clamped to 0..=1 and rounded to 0.001, as pointer locations are (PhotoCraft's
|
||||
/// Gradient Map).
|
||||
pub fn round_location(location: f32) -> f32 {
|
||||
(clamp_location(location) * 1000.0).round() / 1000.0
|
||||
}
|
||||
|
||||
/// `location` clamped to 0..=1; 0 when it isn't a number.
|
||||
fn clamp_location(location: f32) -> f32 {
|
||||
if location.is_finite() { location.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// What the two stop types have in common for the rules.
|
||||
pub(crate) trait Stop: Clone + PartialEq {
|
||||
fn location(&self) -> f32;
|
||||
fn set_location(&mut self, location: f32);
|
||||
fn midpoint(&self) -> f32;
|
||||
fn set_midpoint(&mut self, midpoint: f32);
|
||||
}
|
||||
|
||||
impl Stop for ColorStop {
|
||||
fn location(&self) -> f32 {
|
||||
self.location
|
||||
}
|
||||
fn set_location(&mut self, location: f32) {
|
||||
self.location = location;
|
||||
}
|
||||
fn midpoint(&self) -> f32 {
|
||||
self.midpoint
|
||||
}
|
||||
fn set_midpoint(&mut self, midpoint: f32) {
|
||||
self.midpoint = midpoint;
|
||||
}
|
||||
}
|
||||
|
||||
impl Stop for OpacityStop {
|
||||
fn location(&self) -> f32 {
|
||||
self.location
|
||||
}
|
||||
fn set_location(&mut self, location: f32) {
|
||||
self.location = location;
|
||||
}
|
||||
fn midpoint(&self) -> f32 {
|
||||
self.midpoint
|
||||
}
|
||||
fn set_midpoint(&mut self, midpoint: f32) {
|
||||
self.midpoint = midpoint;
|
||||
}
|
||||
}
|
||||
|
||||
/// The location of stop `i` of `row`.
|
||||
pub(crate) fn location(stops: &GradientStops, row: StopRow, i: usize) -> f32 {
|
||||
match row {
|
||||
StopRow::Color => stops.color[i].location,
|
||||
StopRow::Opacity => stops.opacity_stops()[i].location,
|
||||
}
|
||||
}
|
||||
|
||||
/// The midpoint after stop `i` of `row`.
|
||||
pub(crate) fn midpoint(stops: &GradientStops, row: StopRow, i: usize) -> f32 {
|
||||
match row {
|
||||
StopRow::Color => stops.color[i].midpoint,
|
||||
StopRow::Opacity => stops.opacity_stops()[i].midpoint,
|
||||
}
|
||||
}
|
||||
|
||||
/// The locations of `row`'s stops as the bar shows them.
|
||||
pub(crate) fn locations(stops: &GradientStops, row: StopRow) -> Vec<f32> {
|
||||
match row {
|
||||
StopRow::Color => stops.color.iter().map(|s| s.location).collect(),
|
||||
StopRow::Opacity => stops.opacity_stops().iter().map(|s| s.location).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the midpoint after stop `i` of `row` is, 0..=1 of the bar.
|
||||
pub(crate) fn midpoint_at(stops: &GradientStops, row: StopRow, i: usize) -> f32 {
|
||||
let at = locations(stops, row);
|
||||
at[i] + (at[i + 1] - at[i]) * midpoint(stops, row, i)
|
||||
}
|
||||
|
||||
/// Inserts `stop` after the stops at its location. Returns its index.
|
||||
fn place<T: Stop>(list: &mut Vec<T>, stop: T) -> usize {
|
||||
let at = list.partition_point(|s| s.location() <= stop.location());
|
||||
list.insert(at, stop);
|
||||
at
|
||||
}
|
||||
|
||||
/// Inserts `stop` and resets the midpoint of the segment it splits.
|
||||
fn insert<T: Stop>(list: &mut Vec<T>, stop: T) -> usize {
|
||||
let at = place(list, stop);
|
||||
if let Some(before) = at.checked_sub(1) {
|
||||
list[before].set_midpoint(0.5);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The stops to edit in `row`: the opacity list is written out when it was empty and an opacity
|
||||
/// stop is edited.
|
||||
fn explicit(stops: &GradientStops, row: StopRow) -> GradientStops {
|
||||
match row {
|
||||
StopRow::Color => stops.clone(),
|
||||
StopRow::Opacity => GradientStops { color: stops.color.clone(), opacity: stops.opacity_stops().into_owned() },
|
||||
}
|
||||
}
|
||||
|
||||
fn has_row(rules: &StopRules, row: StopRow) -> bool {
|
||||
row == StopRow::Color || rules.rows == StopRows::Split
|
||||
}
|
||||
|
||||
/// A new stop at `location` in `row`, taking the gradient's colour or opacity there from
|
||||
/// `sampler`, selected by its index. The segment it splits gets its midpoint reset to 0.5. Under
|
||||
/// [`StopRows::Split`] and [`StopRows::ColorOnly`] a colour stop is opaque.
|
||||
pub fn add(stops: &GradientStops, row: StopRow, location: f32, sampler: &Sampler, rules: &StopRules) -> Option<(GradientStops, usize)> {
|
||||
if !has_row(rules, row) || stops.len(row) >= rules.max {
|
||||
return None;
|
||||
}
|
||||
let location = clamp_location(location);
|
||||
let sampled = sampler(stops, location);
|
||||
let mut out = explicit(stops, row);
|
||||
let at = match row {
|
||||
StopRow::Color => {
|
||||
let color = if rules.rows == StopRows::Combined { sampled } else { Srgba { a: 1.0, ..sampled } };
|
||||
insert(&mut out.color, ColorStop::new(location, color))
|
||||
}
|
||||
StopRow::Opacity => insert(&mut out.opacity, OpacityStop::new(location, sampled.a)),
|
||||
};
|
||||
Some((out, at))
|
||||
}
|
||||
|
||||
/// Moves stop `i` of `row` to `location`. It may pass its neighbours; it keeps its place among
|
||||
/// stops at its new location, on the side it came from, so a stop that doesn't move or only
|
||||
/// reaches a neighbour's location never swaps with it. Returns its new index.
|
||||
pub fn move_to(stops: &GradientStops, row: StopRow, i: usize, location: f32, rules: &StopRules) -> Option<(GradientStops, usize)> {
|
||||
if !has_row(rules, row) || i >= stops.len(row) {
|
||||
return None;
|
||||
}
|
||||
let location = clamp_location(location);
|
||||
let mut out = explicit(stops, row);
|
||||
let at = match row {
|
||||
StopRow::Color => relocate(&mut out.color, i, location),
|
||||
StopRow::Opacity => relocate(&mut out.opacity, i, location),
|
||||
};
|
||||
Some((out, at))
|
||||
}
|
||||
|
||||
fn relocate<T: Stop>(list: &mut Vec<T>, i: usize, location: f32) -> usize {
|
||||
let mut stop = list.remove(i);
|
||||
let from = stop.location();
|
||||
stop.set_location(location);
|
||||
// Moving up it stops before the stops at its new location, moving down after them.
|
||||
let at = match location > from {
|
||||
true => list.partition_point(|s| s.location() < location),
|
||||
false if location == from => i,
|
||||
false => list.partition_point(|s| s.location() <= location),
|
||||
};
|
||||
list.insert(at, stop);
|
||||
at
|
||||
}
|
||||
|
||||
/// Removes stop `i` of `row`, never below `rules.min`. Returns the index of the stop that takes
|
||||
/// its place: the next, or the last when it was the last.
|
||||
pub fn remove(stops: &GradientStops, row: StopRow, i: usize, rules: &StopRules) -> Option<(GradientStops, usize)> {
|
||||
let len = stops.len(row);
|
||||
if !has_row(rules, row) || i >= len || len <= rules.min {
|
||||
return None;
|
||||
}
|
||||
let mut out = explicit(stops, row);
|
||||
match row {
|
||||
StopRow::Color => drop(out.color.remove(i)),
|
||||
StopRow::Opacity => drop(out.opacity.remove(i)),
|
||||
}
|
||||
Some((out, i.min(len - 2)))
|
||||
}
|
||||
|
||||
/// A copy of stop `i` of `row` at `location` (an Alt-drag), with its colour or opacity, midpoint
|
||||
/// and tag. The segment it splits gets its midpoint reset to 0.5. Returns the copy's index.
|
||||
pub fn copy(stops: &GradientStops, row: StopRow, i: usize, location: f32, rules: &StopRules) -> Option<(GradientStops, usize)> {
|
||||
if !has_row(rules, row) || i >= stops.len(row) || stops.len(row) >= rules.max {
|
||||
return None;
|
||||
}
|
||||
let location = clamp_location(location);
|
||||
let mut out = explicit(stops, row);
|
||||
let at = match row {
|
||||
StopRow::Color => insert(&mut out.color, ColorStop { location, ..stops.color[i] }),
|
||||
StopRow::Opacity => {
|
||||
let source = out.opacity[i];
|
||||
insert(&mut out.opacity, OpacityStop { location, ..source })
|
||||
}
|
||||
};
|
||||
Some((out, at))
|
||||
}
|
||||
|
||||
/// Sets the midpoint after stop `i` of `row`, clamped to `rules.midpoint`. The last stop has none.
|
||||
pub fn set_midpoint(stops: &GradientStops, row: StopRow, i: usize, midpoint: f32, rules: &StopRules) -> Option<(GradientStops, usize)> {
|
||||
if !has_row(rules, row) || i + 1 >= stops.len(row) {
|
||||
return None;
|
||||
}
|
||||
let m = if midpoint.is_finite() { midpoint.clamp(*rules.midpoint.start(), *rules.midpoint.end()) } else { 0.5 };
|
||||
let mut out = explicit(stops, row);
|
||||
match row {
|
||||
StopRow::Color => out.color[i].midpoint = m,
|
||||
StopRow::Opacity => out.opacity[i].midpoint = m,
|
||||
}
|
||||
Some((out, i))
|
||||
}
|
||||
|
||||
/// The location halfway between the selected stop of `row` and the next, or the one before for
|
||||
/// the last stop; with nothing selected, across the widest gap between stops. A row with one
|
||||
/// stop is halved towards its farther end of the bar, and an empty row at 0.5.
|
||||
pub fn halfway(stops: &GradientStops, row: StopRow, selected: Option<usize>) -> f32 {
|
||||
let at: Vec<f32> = match row {
|
||||
StopRow::Color => stops.color.iter().map(|s| s.location).collect(),
|
||||
StopRow::Opacity => stops.opacity_stops().iter().map(|s| s.location).collect(),
|
||||
};
|
||||
let middle = |a: f32, b: f32| round_location((a + b) / 2.0);
|
||||
match (at.as_slice(), selected) {
|
||||
([], _) => 0.5,
|
||||
([only], _) => middle(*only, if *only < 0.5 { 1.0 } else { 0.0 }),
|
||||
(at, Some(i)) if i < at.len() => {
|
||||
if i + 1 < at.len() {
|
||||
middle(at[i], at[i + 1])
|
||||
} else {
|
||||
middle(at[i - 1], at[i])
|
||||
}
|
||||
}
|
||||
(at, _) => {
|
||||
let widest = (0..at.len() - 1).fold(0, |best, i| if at[i + 1] - at[i] > at[best + 1] - at[best] { i } else { best });
|
||||
middle(at[widest], at[widest + 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mix factor at `location` between the stops of `list` it lies between, with the segment's
|
||||
/// midpoint bent to half: `(from, to, mix)`.
|
||||
fn segment<T: Stop>(list: &[T], location: f32) -> (usize, usize, f32) {
|
||||
let last = list.len() - 1;
|
||||
if location <= list[0].location() {
|
||||
return (0, 0, 0.0);
|
||||
}
|
||||
for (i, pair) in list.windows(2).enumerate() {
|
||||
let (a, b) = (&pair[0], &pair[1]);
|
||||
if location <= b.location() {
|
||||
let u = (location - a.location()) / (b.location() - a.location()).max(1e-6);
|
||||
let m = a.midpoint().clamp(0.01, 0.99);
|
||||
let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) };
|
||||
return (i, i + 1, v);
|
||||
}
|
||||
}
|
||||
(last, last, 0.0)
|
||||
}
|
||||
|
||||
fn mix(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
/// The gradient at `location` with straight lines in encoded sRGB between stops, each segment
|
||||
/// bent so its midpoint gives the half mix. Under [`StopRows::Split`] the alpha comes from the
|
||||
/// opacity stops (opaque when there are none) and the colours' own alpha is ignored; under
|
||||
/// [`StopRows::Combined`] it is the colours' alpha; under [`StopRows::ColorOnly`] it is 1. No colour stops give opaque black.
|
||||
pub fn sample(stops: &GradientStops, rows: StopRows, location: f32) -> Srgba {
|
||||
if stops.color.is_empty() {
|
||||
return Srgba::BLACK;
|
||||
}
|
||||
let (i, j, t) = segment(&stops.color, location);
|
||||
let (a, b) = (stops.color[i].color, stops.color[j].color);
|
||||
let mut out = Srgba::new(mix(a.r, b.r, t), mix(a.g, b.g, t), mix(a.b, b.b, t), mix(a.a, b.a, t));
|
||||
match rows {
|
||||
StopRows::Split if !stops.opacity.is_empty() => {
|
||||
let (i, j, t) = segment(&stops.opacity, location);
|
||||
out.a = mix(stops.opacity[i].opacity, stops.opacity[j].opacity, t);
|
||||
}
|
||||
StopRows::Split | StopRows::ColorOnly => out.a = 1.0,
|
||||
StopRows::Combined => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The default [`Sampler`] for `rows`: [`sample`].
|
||||
pub fn default_sampler(rows: StopRows) -> impl Fn(&GradientStops, f32) -> Srgba {
|
||||
move |stops, location| sample(stops, rows, location)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! [`GradientStops`]: the value a gradient stop bar edits.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a gradient's opacity is stored, which decides the rows of its stop bar.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum StopRows {
|
||||
/// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is
|
||||
/// ignored. An empty [`GradientStops::opacity`] means opaque and shows as two 100 % stops at
|
||||
/// 0 and 100 %.
|
||||
#[default]
|
||||
Split,
|
||||
/// One row of colour stops; each stop's opacity is its colour's alpha and
|
||||
/// [`GradientStops::opacity`] stays empty.
|
||||
Combined,
|
||||
/// One row of colour stops and no opacity at all: a colour's alpha is forced to 1 and the
|
||||
/// editor shows no Opacity field (PhotoCraft's Gradient Map). [`GradientStops::opacity`]
|
||||
/// stays empty.
|
||||
ColorOnly,
|
||||
}
|
||||
|
||||
/// One of the two rows of a [`StopRows::Split`] bar. [`StopRows::Combined`] and
|
||||
/// [`StopRows::ColorOnly`] have only `Color`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum StopRow {
|
||||
/// Colour stops.
|
||||
Color,
|
||||
/// Opacity stops.
|
||||
Opacity,
|
||||
}
|
||||
|
||||
/// A colour stop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorStop {
|
||||
/// Where the stop is, 0..=1.
|
||||
pub location: f32,
|
||||
/// Its colour, with the opacity in the alpha under [`StopRows::Combined`].
|
||||
pub color: Srgba,
|
||||
/// Where between this stop and the next the mix is half and half, 0..=1; 0.5 is centred. The
|
||||
/// last stop's is unused.
|
||||
pub midpoint: f32,
|
||||
/// The host's: it travels with the stop through moves and reorders, so the host can keep what
|
||||
/// the stop doesn't model (a swatch link, a stable id). An added stop has tag 0; a copy keeps
|
||||
/// its source's.
|
||||
pub tag: u64,
|
||||
}
|
||||
|
||||
/// An opacity stop of a [`StopRows::Split`] gradient.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct OpacityStop {
|
||||
/// Where the stop is, 0..=1.
|
||||
pub location: f32,
|
||||
/// Its opacity, 0..=1.
|
||||
pub opacity: f32,
|
||||
/// As [`ColorStop::midpoint`].
|
||||
pub midpoint: f32,
|
||||
/// As [`ColorStop::tag`].
|
||||
pub tag: u64,
|
||||
}
|
||||
|
||||
impl ColorStop {
|
||||
/// A stop with a centred midpoint and tag 0.
|
||||
pub const fn new(location: f32, color: Srgba) -> Self {
|
||||
Self { location, color, midpoint: 0.5, tag: 0 }
|
||||
}
|
||||
|
||||
/// The same stop with the host's `tag`.
|
||||
#[must_use]
|
||||
pub const fn with_tag(mut self, tag: u64) -> Self {
|
||||
self.tag = tag;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same stop with its midpoint at `midpoint`.
|
||||
#[must_use]
|
||||
pub const fn with_midpoint(mut self, midpoint: f32) -> Self {
|
||||
self.midpoint = midpoint;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl OpacityStop {
|
||||
/// A stop with a centred midpoint and tag 0.
|
||||
pub const fn new(location: f32, opacity: f32) -> Self {
|
||||
Self { location, opacity, midpoint: 0.5, tag: 0 }
|
||||
}
|
||||
|
||||
/// The same stop with the host's `tag`.
|
||||
#[must_use]
|
||||
pub const fn with_tag(mut self, tag: u64) -> Self {
|
||||
self.tag = tag;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same stop with its midpoint at `midpoint`.
|
||||
#[must_use]
|
||||
pub const fn with_midpoint(mut self, midpoint: f32) -> Self {
|
||||
self.midpoint = midpoint;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's stops, each list sorted by location.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientStops {
|
||||
/// The colour stops.
|
||||
pub color: Vec<ColorStop>,
|
||||
/// The opacity stops; empty under [`StopRows::Combined`], and for an opaque
|
||||
/// [`StopRows::Split`] gradient.
|
||||
pub opacity: Vec<OpacityStop>,
|
||||
}
|
||||
|
||||
impl GradientStops {
|
||||
/// Colour stops and no opacity stops.
|
||||
pub fn new(color: Vec<ColorStop>) -> Self {
|
||||
Self { color, opacity: Vec::new() }
|
||||
}
|
||||
|
||||
/// Colour stops and the opacity stops of a [`StopRows::Split`] gradient.
|
||||
pub fn with_opacity(color: Vec<ColorStop>, opacity: Vec<OpacityStop>) -> Self {
|
||||
Self { color, opacity }
|
||||
}
|
||||
|
||||
/// The opacity stops as the bar shows them: the two 100 % stops an empty list stands for.
|
||||
pub fn opacity_stops(&self) -> Cow<'_, [OpacityStop]> {
|
||||
if self.opacity.is_empty() { Cow::Owned(vec![OpacityStop::new(0.0, 1.0), OpacityStop::new(1.0, 1.0)]) } else { Cow::Borrowed(&self.opacity) }
|
||||
}
|
||||
|
||||
/// How many stops `row` shows.
|
||||
pub fn len(&self, row: StopRow) -> usize {
|
||||
match row {
|
||||
StopRow::Color => self.color.len(),
|
||||
StopRow::Opacity => self.opacity_stops().len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the colour list is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.color.is_empty()
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,13 @@
|
||||
//! The widgets are behind the `ui` feature; the colour model and conversions are in `craft-theme`.
|
||||
//! Without `ui`, the crate has the helpers that need no egui: [`AreaMode`], [`GrayModel`],
|
||||
//! [`CmykModel`], web-safe colours ([`web_safe`], [`not_web_safe`]), swatch files ([`palette`]), the display transform ([`display`]) and colour
|
||||
//! harmonies ([`harmony`]).
|
||||
//! harmonies ([`harmony`]) and gradient stops ([`gradient`]).
|
||||
//! [`AreaMode`] (and `ui::RampKind`) serialize as their [`key`](AreaMode::key); the swatch and harmony settings types serialize too.
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod cmyk;
|
||||
pub mod display;
|
||||
pub mod gradient;
|
||||
mod gray;
|
||||
pub mod harmony;
|
||||
mod mode;
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! [`GradientEditor`]: a gradient's stop bar with the fields of the selected marker under it.
|
||||
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvent, EditEvents, Mixed};
|
||||
use crate::ui::{ColorPicker, ScreenPickGesture};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, EditResponse, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::{StopColor, StopRef};
|
||||
use crate::gradient::{GradientStops, Sampler, StopRules};
|
||||
|
||||
mod bar;
|
||||
mod fields;
|
||||
|
||||
use bar::GradientBar;
|
||||
pub use bar::StopDrop;
|
||||
pub use bar::marker_texts;
|
||||
use fields::{FIRST_FIELD, PickerSetup, Row, stop_color};
|
||||
|
||||
/// The key of the colour request a stop's colour well files.
|
||||
const REQUEST_KEY: &str = "gradient-stop";
|
||||
|
||||
/// The selection the editor keeps when the host gives none: the first colour stop until set.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Selection(Option<StopRef>);
|
||||
|
||||
impl Default for Selection {
|
||||
fn default() -> Self {
|
||||
Selection(Some(StopRef::Color(0)))
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`GradientEditor::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientEditorOutput<P = ()> {
|
||||
/// This pass's edit of the stops: the bar's and the fields', folded into one event.
|
||||
pub edit: EditResponse<GradientStops>,
|
||||
/// The colour stop whose colour the host is asked to edit: a double click, Enter or Space on it, or a click on
|
||||
/// the Color well; never with `color_popover`.
|
||||
pub color_requested: Option<StopColor>,
|
||||
/// A payload dropped on the bar: where it landed and the payload.
|
||||
pub dropped: Option<(StopDrop, P)>,
|
||||
/// The popover picker's screen-pick press; the host answers with `sampled`.
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
/// The selection after this pass.
|
||||
pub selected: Option<StopRef>,
|
||||
}
|
||||
|
||||
impl<P> Outcome for GradientEditorOutput<P> {
|
||||
type Value = GradientStops;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
}
|
||||
|
||||
/// Edits a gradient's stops: `GradientEditor::new("Gradient", Bind::bound(&mut stops)).show(ui)`.
|
||||
///
|
||||
/// The bar fills the width offered. [`StopRows::Split`] rows, top to bottom: opacity markers (their midpoints just
|
||||
/// above the ramp), the ramp, the colour midpoints, colour markers; [`StopRows::Combined`]: the midpoints, the ramp,
|
||||
/// colour markers. The bar keeps its geometry right to left: the ramp is the gradient, not reading order.
|
||||
///
|
||||
/// Pointer: a press on a marker or diamond selects and grabs it without a jump; a drag moves it (stops pass their
|
||||
/// neighbours and the selection follows) and is one gesture. A stop dragged more than the tear-off distance above or
|
||||
/// below the ramp is removed while its row is above the minimum, and comes back on re-entry within the drag. Alt held
|
||||
/// at the press drags a copy, which can't be torn off. A click on empty space adds a stop there (under `Split`, above
|
||||
/// the ramp's centre an opacity stop) as one Set; a press and drag on empty space does nothing. A double click on a
|
||||
/// colour stop asks for its colour.
|
||||
///
|
||||
/// Keys (one Tab stop; the selected marker is the active descendant): `+` (or `=`) and `-` select the next and previous
|
||||
/// marker of the selected row in location order, midpoints between their stops; under `Split`, Up and Down select the
|
||||
/// opacity or colour stop nearest the selected location; Left and Right move the selected stop or midpoint by 1 %,
|
||||
/// 10 % with Shift; Delete and Backspace remove the selected stop and select the one that takes its index; Insert and
|
||||
/// Cmd/Ctrl+Enter add a stop halfway in the selected row and select it; Enter and Space on a colour stop ask for its
|
||||
/// colour, on an opacity stop or a midpoint they ask for its fields.
|
||||
///
|
||||
/// Fields (on by default): the selected marker's fields under the bar. A colour stop has a "Color" well (a click asks
|
||||
/// for the colour, or opens the colour popover with `color_popover`) and, under `Combined`, an "Opacity"; an opacity
|
||||
/// stop has an "Opacity"; a stop has a "Location" and a Delete button, disabled at the row's minimum; a midpoint has a
|
||||
/// "Midpoint" in the rules' range. The number fields are percent, and their labels scrub them. A Location run that
|
||||
/// passes a neighbour keeps the selection on its stop.
|
||||
///
|
||||
/// The selection is the host's `shared_selection` binding when given (the canvas gradient line shares it), else the editor's
|
||||
/// own: the first colour stop until set.
|
||||
#[must_use = "show the editor with `show`"]
|
||||
#[derive(Pattern)]
|
||||
#[pattern(probe(GradientEditor<'static, u8>))]
|
||||
pub struct GradientEditor<'a, P: Clone + Send + Sync + 'static = ()> {
|
||||
label: Label,
|
||||
stops: Bind<'a, GradientStops>,
|
||||
rules: StopRules,
|
||||
midpoints: bool,
|
||||
opacity_midpoints: bool,
|
||||
sampler: Option<&'a Sampler>,
|
||||
location_decimals: usize,
|
||||
fields: bool,
|
||||
color_popover: bool,
|
||||
picker: Option<PickerSetup<'a>>,
|
||||
shared_selection: Option<Bind<'a, Option<StopRef>>>,
|
||||
sampled: Option<Srgba>,
|
||||
drop_target: bool,
|
||||
enabled: bool,
|
||||
payload: PhantomData<fn() -> P>,
|
||||
}
|
||||
|
||||
impl<'a> GradientEditor<'a> {
|
||||
/// An editor named `label` ("Gradient") of `stops`.
|
||||
pub fn new(label: impl Into<Label>, stops: Bind<'a, GradientStops>) -> Self {
|
||||
GradientEditor {
|
||||
label: label.into(),
|
||||
stops,
|
||||
rules: StopRules::default(),
|
||||
midpoints: true,
|
||||
opacity_midpoints: true,
|
||||
sampler: None,
|
||||
location_decimals: 0,
|
||||
fields: true,
|
||||
color_popover: false,
|
||||
picker: None,
|
||||
shared_selection: None,
|
||||
sampled: None,
|
||||
drop_target: false,
|
||||
enabled: true,
|
||||
payload: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, P: Clone + Send + Sync + 'static> GradientEditor<'a, P> {
|
||||
/// The row layout, the fewest and most stops a row keeps and the range of a midpoint (PhotoCraft: two rows, 2 and
|
||||
/// 1024 stops, 5 % to 95 %).
|
||||
pub fn rules(mut self, rules: StopRules) -> Self {
|
||||
self.rules = rules;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the midpoint diamonds show and edit, on both rows; on by default. Off hides the opacity row's too.
|
||||
pub fn midpoints(mut self, midpoints: bool) -> Self {
|
||||
self.midpoints = midpoints;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the opacity row of a split bar has midpoint diamonds, for a host whose opacity stops carry none; on by
|
||||
/// default.
|
||||
pub fn opacity_midpoints(mut self, opacity_midpoints: bool) -> Self {
|
||||
self.opacity_midpoints = opacity_midpoints;
|
||||
self
|
||||
}
|
||||
|
||||
/// Samples the gradient for the ramp and new stops instead of the default sampler.
|
||||
pub fn sampler(mut self, sampler: &'a Sampler) -> Self {
|
||||
self.sampler = Some(sampler);
|
||||
self
|
||||
}
|
||||
|
||||
/// Decimals of a location in percent; 0 by default.
|
||||
pub fn location_decimals(mut self, decimals: usize) -> Self {
|
||||
self.location_decimals = decimals;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the selected marker's fields show under the bar; on by default.
|
||||
pub fn fields(mut self, fields: bool) -> Self {
|
||||
self.fields = fields;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the editor edits a colour stop's colour in a colour popover itself, anchored on the Color well (on the bar
|
||||
/// without the fields); off by default, when the request goes to the host in `color_requested`.
|
||||
pub fn color_popover(mut self, popover: bool) -> Self {
|
||||
self.color_popover = popover;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets up the colour popover's picker (texts, constraint, models, eyedropper): `setup` gets the Compact picker, with
|
||||
/// alpha under `Combined`.
|
||||
pub fn picker(mut self, setup: impl for<'b> Fn(ColorPicker<'b>) -> ColorPicker<'b> + 'a) -> Self {
|
||||
self.picker = Some(Box::new(setup));
|
||||
self
|
||||
}
|
||||
|
||||
/// The host's selection, shared with the canvas gradient line.
|
||||
pub fn shared_selection(mut self, selection: Bind<'a, Option<StopRef>>) -> Self {
|
||||
self.shared_selection = Some(selection);
|
||||
self
|
||||
}
|
||||
|
||||
/// The colour the host's screen pick answered with, for the popover's picker.
|
||||
pub fn sampled(mut self, color: Srgba) -> Self {
|
||||
self.sampled = Some(color);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the editor takes input.
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Takes drops of `Q` payloads: while one hovers, a line marks the place; the release is reported in
|
||||
/// `dropped` and the host applies it.
|
||||
pub fn drop_target<Q: Clone + Send + Sync + 'static>(self) -> GradientEditor<'a, Q> {
|
||||
let GradientEditor {
|
||||
label,
|
||||
stops,
|
||||
rules,
|
||||
midpoints,
|
||||
opacity_midpoints,
|
||||
sampler,
|
||||
location_decimals,
|
||||
fields,
|
||||
color_popover,
|
||||
picker,
|
||||
shared_selection,
|
||||
sampled,
|
||||
enabled,
|
||||
..
|
||||
} = self;
|
||||
GradientEditor {
|
||||
label,
|
||||
stops,
|
||||
rules,
|
||||
midpoints,
|
||||
opacity_midpoints,
|
||||
sampler,
|
||||
location_decimals,
|
||||
fields,
|
||||
color_popover,
|
||||
picker,
|
||||
shared_selection,
|
||||
sampled,
|
||||
drop_target: true,
|
||||
enabled,
|
||||
payload: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the bar and the fields.
|
||||
pub fn show(self, ui: &mut Ui) -> GradientEditorOutput<P> {
|
||||
let GradientEditor {
|
||||
label,
|
||||
mut stops,
|
||||
rules,
|
||||
midpoints,
|
||||
opacity_midpoints,
|
||||
sampler,
|
||||
location_decimals,
|
||||
fields,
|
||||
color_popover,
|
||||
picker,
|
||||
shared_selection: mut selected,
|
||||
sampled,
|
||||
drop_target,
|
||||
enabled,
|
||||
..
|
||||
} = self;
|
||||
let words = Env::of(ui).words::<super::words::GradientWords>();
|
||||
let mut output = None;
|
||||
let shown = Stack::new().fill_width().show(ui, |ui, cx| {
|
||||
let held = match selected.as_mut() {
|
||||
Some(bind) => bind.reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or(None),
|
||||
None => cx.memory::<Selection>().0,
|
||||
};
|
||||
let mut bar = GradientBar::<P>::new(label.clone(), stops.reborrowed())
|
||||
.rules(rules.clone())
|
||||
.midpoints(midpoints)
|
||||
.opacity_midpoints(opacity_midpoints)
|
||||
.location_decimals(location_decimals)
|
||||
.enabled(enabled);
|
||||
if let Some(held) = held {
|
||||
bar = bar.selected_marker(held);
|
||||
}
|
||||
if let Some(sampler) = sampler {
|
||||
bar = bar.sampler(sampler);
|
||||
}
|
||||
if drop_target {
|
||||
bar = bar.drop_target();
|
||||
}
|
||||
let bar = bar.show(ui);
|
||||
let mut edit = bar.edit;
|
||||
let mut now_selected = bar.select.unwrap_or(held);
|
||||
let mut color_requested = bar.color_requested;
|
||||
let mut screen_pick = None;
|
||||
if let Some(now) = stops.reborrow().read(cx).and_then(|stops| stops.same().cloned()) {
|
||||
let mut row = Row {
|
||||
words: &words,
|
||||
rules: &rules,
|
||||
location_decimals,
|
||||
enabled,
|
||||
fields,
|
||||
color_popover,
|
||||
picker: &picker,
|
||||
sampled,
|
||||
requested: color_requested,
|
||||
};
|
||||
if bar.field_requested && fields {
|
||||
craft_ui::runtime::focus::request(ui.ctx(), craft_ui::runtime::focus::FocusTarget::Id(cx.key(FIRST_FIELD)));
|
||||
}
|
||||
let report = row.show(ui, cx, &now, now_selected, &edit.response);
|
||||
color_requested = report.color_requested;
|
||||
screen_pick = report.screen_pick;
|
||||
if let Some(select) = report.select {
|
||||
now_selected = select;
|
||||
}
|
||||
for event in report.events {
|
||||
stops.reborrow().write(cx, &event);
|
||||
edit.events.push(event);
|
||||
}
|
||||
color_requested = color_requested.filter(|i| *i < now.color.len());
|
||||
if let Some(i) = color_requested {
|
||||
let request = ColorRequest::new(REQUEST_KEY, stop_color(&now, rules.rows, i)).title(label.clone());
|
||||
output = Some(StopColor::new(i, now.color[i].tag, request));
|
||||
}
|
||||
}
|
||||
if now_selected != held {
|
||||
match selected.as_mut() {
|
||||
Some(bind) => {
|
||||
let event = EditEvent::set(Mixed::Same(held), now_selected, Arc::from("Select stop"), None);
|
||||
bind.reborrow().write(cx, &event);
|
||||
}
|
||||
None => cx.memory::<Selection>().0 = now_selected,
|
||||
}
|
||||
}
|
||||
(edit, bar.dropped, screen_pick, now_selected)
|
||||
});
|
||||
match shown.inner {
|
||||
Some((edit, dropped, screen_pick, selected)) => GradientEditorOutput { edit, color_requested: output, dropped, screen_pick, selected },
|
||||
None => GradientEditorOutput {
|
||||
edit: EditResponse::lifted(shown.output, EditEvents::new(), None),
|
||||
color_requested: None,
|
||||
dropped: None,
|
||||
screen_pick: None,
|
||||
selected: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,879 @@
|
||||
//! `GradientBar`: the stop bar of the gradient editor, a leaf with a part per marker. The editor shows it
|
||||
//! above the fields row.
|
||||
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use craft_behavior::part::PartRef;
|
||||
use craft_behavior::{
|
||||
Axis, CursorIcon, Granularity, HitLevel, HitPriority, Intent, Metrics, NavShape, PartKey, PointerButton, PressPhase, Roving, Sense,
|
||||
};
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
use craft_theme::{Rgba, Srgba, Stateful, States};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DropMark, DropOperation, DropTarget, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Outcome,
|
||||
PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
use craft_ui::runtime::env::Units;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, Flags, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, pos2, vec2};
|
||||
|
||||
use crate::ui::gradient::ramp::GradientRamp;
|
||||
use crate::gradient::stops::{self, STOP_STEP, STOP_STEP_FAR, Sampler, StopRules, default_sampler, location, locations, midpoint, midpoint_at};
|
||||
use crate::gradient::{GradientStops, StopRow, StopRows};
|
||||
use crate::ui::gradient::StopRef;
|
||||
use crate::ui::gradient::words::GradientWords;
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
|
||||
/// The part under the whole bar: a click on it adds a stop.
|
||||
pub(super) const RAMP: PartKey = PartKey::new("ramp");
|
||||
/// Colour stop `i`: `COLOR_STOP.at(i)`.
|
||||
pub(super) const COLOR_STOP: PartKey = PartKey::new("color_stop");
|
||||
/// Opacity stop `i`.
|
||||
pub(super) const OPACITY_STOP: PartKey = PartKey::new("opacity_stop");
|
||||
/// The midpoint after colour stop `i`.
|
||||
pub(super) const COLOR_MIDPOINT: PartKey = PartKey::new("color_midpoint");
|
||||
/// The midpoint after opacity stop `i`.
|
||||
pub(super) const OPACITY_MIDPOINT: PartKey = PartKey::new("opacity_midpoint");
|
||||
|
||||
/// Stop locations as markers show them, closer than this, have no midpoint diamond between them.
|
||||
const MIN_GAP: f32 = 0.001;
|
||||
/// The tear-off distance as a multiple of the control height.
|
||||
const TEAR_OFF_SHARE: f32 = 1.17;
|
||||
|
||||
/// The keys a focused bar keeps from the app's shortcuts. `+` is claimed both as itself and as `=`: many keyboards
|
||||
/// type it with Shift.
|
||||
const CLAIMS: [Chord; 5] =
|
||||
[Chord::plain(Key::Plus), Chord::plain(Key::Equals), Chord::plain(Key::Minus), Chord::plain(Key::Insert), Chord::new(Mods::CMD, Key::Enter)];
|
||||
|
||||
/// The part of a marker.
|
||||
fn part_of(marker: StopRef) -> PartRef {
|
||||
match marker {
|
||||
StopRef::Color(i) => COLOR_STOP.at(i as u64),
|
||||
StopRef::Opacity(i) => OPACITY_STOP.at(i as u64),
|
||||
StopRef::Midpoint(StopRow::Color, i) => COLOR_MIDPOINT.at(i as u64),
|
||||
StopRef::Midpoint(StopRow::Opacity, i) => OPACITY_MIDPOINT.at(i as u64),
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker a part stands for.
|
||||
fn marker_of(part: PartRef) -> Option<StopRef> {
|
||||
let i = usize::try_from(part.index?).ok()?;
|
||||
match part.key {
|
||||
k if k == COLOR_STOP => Some(StopRef::Color(i)),
|
||||
k if k == OPACITY_STOP => Some(StopRef::Opacity(i)),
|
||||
k if k == COLOR_MIDPOINT => Some(StopRef::Midpoint(StopRow::Color, i)),
|
||||
k if k == OPACITY_MIDPOINT => Some(StopRef::Midpoint(StopRow::Opacity, i)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a payload dropped on the bar landed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum StopDrop {
|
||||
/// On colour stop `i` (DesignCraft and VectorCraft recolour it).
|
||||
OnStop(usize),
|
||||
/// At a location of the bar, 0..=1, away from the colour stops (they add a stop there).
|
||||
At(f32),
|
||||
}
|
||||
|
||||
/// The style of the stop bar.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientBarStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The width a bar asks for when the layout offers none.
|
||||
length: f32,
|
||||
/// Height of the ramp.
|
||||
ramp_height: f32,
|
||||
/// Inset of the ramp at both ends of the bar.
|
||||
inset: f32,
|
||||
/// Side of a stop marker's square.
|
||||
marker: f32,
|
||||
/// Height of a stop marker's pointer.
|
||||
pointer: f32,
|
||||
/// Radius of a midpoint diamond.
|
||||
diamond: f32,
|
||||
/// How far from a marker and a diamond a press takes it.
|
||||
hit: f32,
|
||||
/// How far above or below the ramp a dragged stop is removed.
|
||||
tear_off: f32,
|
||||
/// Marker outlines, pointers and diamonds.
|
||||
edge: Stateful<StyleColor>,
|
||||
/// The outline of a hovered marker.
|
||||
hovered: StyleColor,
|
||||
/// The outline of the selected marker and the fill of the selected diamond.
|
||||
selected: StyleColor,
|
||||
/// The one-point edge round the ramp.
|
||||
ramp_edge: Stateful<StyleColor>,
|
||||
/// The line that marks a drop place.
|
||||
drop: StyleColor,
|
||||
}
|
||||
|
||||
/// The selection and the drag the bar remembers.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Held {
|
||||
drag: Option<Drag>,
|
||||
/// The selection before the press, restored when the press is cancelled.
|
||||
before: Option<StopRef>,
|
||||
}
|
||||
|
||||
/// The marker a press captured.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Drag {
|
||||
marker: StopRef,
|
||||
/// The stops at the press: every frame of the drag edits them afresh, so a stop torn off comes back as it was.
|
||||
base: GradientStops,
|
||||
/// Where the press was and the marker's location then, so the marker doesn't jump.
|
||||
press: Pos2,
|
||||
grab: f32,
|
||||
/// Alt was held at the press: the drag moves a copy of the stop.
|
||||
copy: bool,
|
||||
}
|
||||
|
||||
/// What the bar reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientBarOutput<P = ()> {
|
||||
/// This pass's edit of the stops.
|
||||
pub edit: EditResponse<GradientStops>,
|
||||
/// The selection after this pass, when the bar changed it.
|
||||
pub select: Option<Option<StopRef>>,
|
||||
/// The colour stop whose colour is asked for: a double click on it, Enter or Space.
|
||||
pub color_requested: Option<usize>,
|
||||
/// Enter or Space on an opacity stop or a midpoint: its first field takes the focus.
|
||||
pub field_requested: bool,
|
||||
/// A payload dropped on the bar: where it landed.
|
||||
pub dropped: Option<(StopDrop, P)>,
|
||||
}
|
||||
|
||||
impl<P> Outcome for GradientBarOutput<P> {
|
||||
type Value = GradientStops;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
}
|
||||
|
||||
/// The stop bar: opacity markers, ramp and colour markers, edited by pointer and keys.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter, unregistered)]
|
||||
pub struct GradientBar<'a, P: Clone + Send + Sync + 'static = ()> {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Bind<'a, GradientStops>,
|
||||
/// The rows, the stop count and the midpoint range.
|
||||
#[prop]
|
||||
rules: StopRules,
|
||||
/// Whether the midpoint diamonds show and edit, on both rows.
|
||||
#[prop]
|
||||
midpoints: bool,
|
||||
/// Whether the opacity row of a split bar has midpoint diamonds.
|
||||
#[prop]
|
||||
opacity_midpoints: bool,
|
||||
/// Samples the gradient for the ramp and new stops instead of [`default_sampler`].
|
||||
#[prop]
|
||||
sampler: Option<&'a Sampler>,
|
||||
/// Decimals of a location in percent, for the accessible values.
|
||||
#[prop]
|
||||
location_decimals: usize,
|
||||
/// Registers the bar as a drop target for `P` payloads.
|
||||
#[prop(flag)]
|
||||
drop_target: bool,
|
||||
/// The selected marker.
|
||||
#[prop]
|
||||
selected_marker: Option<StopRef>,
|
||||
select: Option<Option<StopRef>>,
|
||||
color_requested: Option<usize>,
|
||||
field_requested: bool,
|
||||
dropped: Option<(StopDrop, P)>,
|
||||
payload: PhantomData<fn() -> P>,
|
||||
}
|
||||
|
||||
impl<'a, P: Clone + Send + Sync + 'static> GradientBar<'a, P> {
|
||||
/// A bar named `label` over `value`.
|
||||
pub fn new(label: impl Into<craft_ui::runtime::env::Label>, value: Bind<'a, GradientStops>) -> Self {
|
||||
GradientBar {
|
||||
common: Common::new(),
|
||||
value,
|
||||
rules: StopRules::default(),
|
||||
midpoints: true,
|
||||
opacity_midpoints: true,
|
||||
sampler: None,
|
||||
location_decimals: 0,
|
||||
drop_target: false,
|
||||
selected_marker: None,
|
||||
select: None,
|
||||
color_requested: None,
|
||||
field_requested: false,
|
||||
dropped: None,
|
||||
payload: PhantomData,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
}
|
||||
|
||||
fn rows(&self) -> StopRows {
|
||||
self.rules.rows
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the bar's parts are this pass.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Geometry {
|
||||
ramp: Rect,
|
||||
rows: StopRows,
|
||||
midpoints: bool,
|
||||
opacity_midpoints: bool,
|
||||
marker: f32,
|
||||
pointer: f32,
|
||||
diamond: f32,
|
||||
hit: f32,
|
||||
tear_off: f32,
|
||||
}
|
||||
|
||||
impl Geometry {
|
||||
fn new(rect: Rect, rows: StopRows, midpoints: bool, opacity_midpoints: bool, style: &GradientBarStyle) -> Self {
|
||||
let top = Self::top(rows, midpoints, opacity_midpoints, style);
|
||||
let ramp = Rect::from_min_size(
|
||||
pos2(rect.left() + style.inset, rect.top() + top),
|
||||
vec2((rect.width() - 2.0 * style.inset).max(1.0), style.ramp_height),
|
||||
);
|
||||
Geometry {
|
||||
ramp,
|
||||
|
||||
rows,
|
||||
midpoints,
|
||||
opacity_midpoints,
|
||||
marker: style.marker,
|
||||
pointer: style.pointer,
|
||||
diamond: style.diamond,
|
||||
hit: style.hit,
|
||||
tear_off: style.tear_off,
|
||||
}
|
||||
}
|
||||
|
||||
/// The room a midpoint diamond takes from the ramp's edge: its centre is two radii out.
|
||||
fn diamond_room(style: &GradientBarStyle) -> f32 {
|
||||
3.0 * style.diamond
|
||||
}
|
||||
|
||||
/// The height above the ramp: the opacity markers of a split bar, and the diamonds of the row above the ramp (the
|
||||
/// opacity row of a split bar, else the colour row).
|
||||
fn top(rows: StopRows, midpoints: bool, opacity_midpoints: bool, style: &GradientBarStyle) -> f32 {
|
||||
let (markers, diamonds) = match rows {
|
||||
StopRows::Split => (style.pointer + style.marker, midpoints && opacity_midpoints),
|
||||
_ => (0.0, midpoints),
|
||||
};
|
||||
let diamonds = if diamonds { Self::diamond_room(style) } else { 0.0 };
|
||||
markers.max(diamonds) + 1.0
|
||||
}
|
||||
|
||||
/// The height under the ramp: the colour markers, and in a split bar the colour row's diamonds.
|
||||
fn bottom(rows: StopRows, midpoints: bool, style: &GradientBarStyle) -> f32 {
|
||||
let diamonds = if midpoints && rows == StopRows::Split { Self::diamond_room(style) } else { 0.0 };
|
||||
(style.pointer + style.marker).max(diamonds) + 1.0
|
||||
}
|
||||
|
||||
/// The height of the bar.
|
||||
fn height(rows: StopRows, midpoints: bool, opacity_midpoints: bool, style: &GradientBarStyle) -> f32 {
|
||||
Self::top(rows, midpoints, opacity_midpoints, style) + style.ramp_height + Self::bottom(rows, midpoints, style)
|
||||
}
|
||||
|
||||
/// The rows the bar shows, top first.
|
||||
fn rows(&self) -> Vec<StopRow> {
|
||||
match self.rows {
|
||||
StopRows::Split => vec![StopRow::Opacity, StopRow::Color],
|
||||
_ => vec![StopRow::Color],
|
||||
}
|
||||
}
|
||||
|
||||
fn x(&self, location: f32) -> f32 {
|
||||
self.ramp.left() + location.clamp(0.0, 1.0) * self.ramp.width()
|
||||
}
|
||||
|
||||
/// The location under `x`, unclamped.
|
||||
fn location(&self, x: f32) -> f32 {
|
||||
(x - self.ramp.left()) / self.ramp.width().max(1.0)
|
||||
}
|
||||
|
||||
/// Whether `m` is a marker of `stops` on this bar.
|
||||
fn valid(&self, stops: &GradientStops, m: StopRef) -> bool {
|
||||
let has = |row| row == StopRow::Color || self.rows == StopRows::Split;
|
||||
match m {
|
||||
StopRef::Midpoint(row, i) => self.shows_midpoints(row) && has(row) && i + 1 < stops.len(row),
|
||||
m => has(m.row()) && m.index() < stops.len(m.row()),
|
||||
}
|
||||
}
|
||||
|
||||
fn shows_midpoints(&self, row: StopRow) -> bool {
|
||||
self.midpoints && (row == StopRow::Color || self.opacity_midpoints)
|
||||
}
|
||||
|
||||
/// The midpoints of `row` the bar shows, with their locations: between stops more than [`MIN_GAP`] apart.
|
||||
fn diamonds(&self, stops: &GradientStops, row: StopRow) -> Vec<(usize, f32)> {
|
||||
if !self.shows_midpoints(row) {
|
||||
return Vec::new();
|
||||
}
|
||||
let at = locations(stops, row);
|
||||
(0..at.len().saturating_sub(1)).filter(|&i| at[i + 1] - at[i] > MIN_GAP).map(|i| (i, midpoint_at(stops, row, i))).collect()
|
||||
}
|
||||
|
||||
/// The markers of `row` in location order, each midpoint between its stops.
|
||||
fn order(&self, stops: &GradientStops, row: StopRow) -> Vec<StopRef> {
|
||||
let diamonds = self.diamonds(stops, row);
|
||||
let mut out = Vec::new();
|
||||
for i in 0..stops.len(row) {
|
||||
out.push(StopRef::stop(row, i));
|
||||
if diamonds.iter().any(|(k, _)| *k == i) {
|
||||
out.push(StopRef::Midpoint(row, i));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every marker the bar shows, top row first.
|
||||
fn markers(&self, stops: &GradientStops) -> Vec<StopRef> {
|
||||
self.rows().into_iter().flat_map(|row| self.order(stops, row)).collect()
|
||||
}
|
||||
|
||||
/// Where marker `m` is, 0..=1.
|
||||
fn location_of(&self, stops: &GradientStops, m: StopRef) -> f32 {
|
||||
match m {
|
||||
StopRef::Midpoint(row, i) => midpoint_at(stops, row, i),
|
||||
m => location(stops, m.row(), m.index()),
|
||||
}
|
||||
}
|
||||
|
||||
fn diamond_center(&self, row: StopRow, at: f32) -> Pos2 {
|
||||
let d = 2.0 * self.diamond;
|
||||
let y = match (row, self.rows) {
|
||||
(StopRow::Color, StopRows::Split) => self.ramp.bottom() + d,
|
||||
_ => self.ramp.top() - d,
|
||||
};
|
||||
pos2(self.x(at), y)
|
||||
}
|
||||
|
||||
/// The square of a stop marker of `row` at `at`. Colour markers hang below the ramp, opacity markers stand above it.
|
||||
fn body(&self, row: StopRow, at: f32) -> Rect {
|
||||
let top = match row {
|
||||
StopRow::Color => self.ramp.bottom() + self.pointer,
|
||||
StopRow::Opacity => self.ramp.top() - self.pointer - self.marker,
|
||||
};
|
||||
Rect::from_min_size(pos2(self.x(at) - self.marker / 2.0, top), vec2(self.marker, self.marker))
|
||||
}
|
||||
|
||||
/// What a press takes for marker `m`: a stop within `hit` across, from a diamond's radius away from the ramp's edge
|
||||
/// to the marker's far edge; a midpoint within `hit` of its diamond.
|
||||
fn hit_rect(&self, stops: &GradientStops, m: StopRef) -> Rect {
|
||||
match m {
|
||||
StopRef::Midpoint(row, i) => {
|
||||
Rect::from_center_size(self.diamond_center(row, midpoint_at(stops, row, i)), vec2(self.hit, 2.0 * self.diamond))
|
||||
}
|
||||
m => {
|
||||
let (row, x) = (m.row(), self.x(location(stops, m.row(), m.index())));
|
||||
let (near, far) = match row {
|
||||
StopRow::Color => (self.ramp.bottom() + self.diamond, self.body(row, 0.0).bottom()),
|
||||
StopRow::Opacity => (self.body(row, 0.0).top(), self.ramp.top() - self.diamond),
|
||||
};
|
||||
Rect::from_x_y_ranges((x - self.hit / 2.0)..=(x + self.hit / 2.0), near..=far)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour stop or location a payload dropped at `pos` lands on.
|
||||
fn drop_place(&self, stops: &GradientStops, pos: Pos2) -> StopDrop {
|
||||
let near = stops
|
||||
.color
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| (i, (self.x(s.location) - pos.x).abs()))
|
||||
.filter(|(_, d)| *d <= self.hit)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1));
|
||||
match near {
|
||||
Some((i, _)) => StopDrop::OnStop(i),
|
||||
None => StopDrop::At(stops::round_location(self.location(pos.x))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The accessible name and value of marker `m` of `stops`, as the bar and the canvas gradient line's parts read them.
|
||||
pub fn marker_texts(
|
||||
words: &GradientWords,
|
||||
units: &Units,
|
||||
rows: StopRows,
|
||||
stops: &GradientStops,
|
||||
m: StopRef,
|
||||
location_decimals: usize,
|
||||
) -> (String, String) {
|
||||
let percent = |v: f32, decimals: usize| units.text(UnitKind::Percent, f64::from(v) * 100.0, decimals..=decimals);
|
||||
let location_text = |at: f32| percent(at, location_decimals);
|
||||
let count = locations(stops, m.row()).len();
|
||||
let (n, number) = (count.to_string(), |i: usize| (i + 1).to_string());
|
||||
match m {
|
||||
StopRef::Color(i) => {
|
||||
let stop = stops.color[i];
|
||||
let hex = Rgba::from(Srgba { a: 1.0, ..stop.color }).to_hex().to_uppercase();
|
||||
let (at, opacity) = (location_text(stop.location), percent(stop.color.a, 0));
|
||||
let value = match rows {
|
||||
StopRows::Combined => words.color_opacity_value.fill(&[("location", &at), ("hex", &hex), ("opacity", &opacity)]),
|
||||
_ => words.color_value.fill(&[("location", &at), ("hex", &hex)]),
|
||||
};
|
||||
(words.color_stop.fill(&[("i", &number(i)), ("n", &n)]), value)
|
||||
}
|
||||
StopRef::Opacity(i) => {
|
||||
let stop = stops.opacity_stops()[i];
|
||||
let value = words.opacity_value.fill(&[("location", &location_text(stop.location)), ("opacity", &percent(stop.opacity, 0))]);
|
||||
(words.opacity_stop.fill(&[("i", &number(i)), ("n", &n)]), value)
|
||||
}
|
||||
StopRef::Midpoint(row, i) => {
|
||||
let template = match row {
|
||||
StopRow::Color => &words.midpoint,
|
||||
StopRow::Opacity => &words.opacity_midpoint,
|
||||
};
|
||||
(template.fill(&[("i", &number(i))]), percent(midpoint(stops, row, i), 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A diamond of radius `r` round `center`.
|
||||
fn diamond(center: Pos2, r: f32) -> PaintShape {
|
||||
PaintShape::Polygon(vec![center + vec2(0.0, -r), center + vec2(r, 0.0), center + vec2(0.0, r), center + vec2(-r, 0.0)])
|
||||
}
|
||||
|
||||
/// Where a payload dropped on the bar lands: the bar's stops decide.
|
||||
struct OnBar<'s, P> {
|
||||
geo: Geometry,
|
||||
stops: &'s GradientStops,
|
||||
live: bool,
|
||||
payload: PhantomData<fn() -> P>,
|
||||
}
|
||||
|
||||
impl<P: Clone + Send + Sync + 'static> DropTarget<P> for OnBar<'_, P> {
|
||||
type Drop = (StopDrop, P);
|
||||
|
||||
fn accept(&self, payload: &P, at: Pos2, _: DropOperation) -> Option<Self::Drop> {
|
||||
self.live.then(|| (self.geo.drop_place(self.stops, at), payload.clone()))
|
||||
}
|
||||
|
||||
fn mark(&self, drop: &Self::Drop) -> DropMark {
|
||||
let x = match drop.0 {
|
||||
StopDrop::OnStop(i) => self.geo.x(self.stops.color[i].location),
|
||||
StopDrop::At(at) => self.geo.x(at),
|
||||
};
|
||||
DropMark::line(pos2(x, self.geo.ramp.top()), pos2(x, self.geo.ramp.bottom()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Clone + Send + Sync + 'static> GradientBar<'_, P> {
|
||||
fn geometry(&self, rect: Rect, style: &GradientBarStyle) -> Geometry {
|
||||
Geometry::new(rect, self.rows(), self.midpoints, self.opacity_midpoints, style)
|
||||
}
|
||||
|
||||
/// Selects `marker`, as the bar's report to the editor.
|
||||
fn choose(&mut self, marker: Option<StopRef>) {
|
||||
self.selected_marker = marker;
|
||||
self.select = Some(marker);
|
||||
}
|
||||
|
||||
/// The drag's stops with the marker at the pointer: moved, copied, or torn off.
|
||||
fn drag_to(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, drag: &Drag, pos: Pos2) {
|
||||
let Drag { marker, ref base, press, grab, copy, .. } = *drag;
|
||||
let to = grab + geo.location(pos.x) - geo.location(press.x);
|
||||
let moved = pos.x != press.x;
|
||||
let off = pos.y > geo.ramp.bottom() + geo.tear_off || pos.y < geo.ramp.top() - geo.tear_off;
|
||||
let rules = &self.rules;
|
||||
let (stops, selected) = match marker {
|
||||
StopRef::Midpoint(row, i) => {
|
||||
let at = locations(base, row);
|
||||
let m = (to - at[i]) / (at[i + 1] - at[i]).max(MIN_GAP);
|
||||
match moved {
|
||||
true => stops::set_midpoint(base, row, i, m, rules).map_or((base.clone(), Some(marker)), |(s, _)| (s, Some(marker))),
|
||||
false => (base.clone(), Some(marker)),
|
||||
}
|
||||
}
|
||||
m => {
|
||||
let (row, i, at) = (m.row(), m.index(), stops::round_location(to));
|
||||
// At the row's minimum a stop dragged off the bar stays and moves.
|
||||
let torn = (off && !copy).then(|| stops::remove(base, row, i, rules)).flatten().map(|(s, _)| (s, None));
|
||||
let edited = torn.or_else(|| match (moved, copy) {
|
||||
(false, _) => None,
|
||||
(true, true) => stops::copy(base, row, i, at, rules).map(|(s, j)| (s, Some(StopRef::stop(row, j)))),
|
||||
(true, false) => stops::move_to(base, row, i, at, rules).map(|(s, j)| (s, Some(StopRef::stop(row, j)))),
|
||||
});
|
||||
edited.unwrap_or_else(|| (base.clone(), Some(marker)))
|
||||
}
|
||||
};
|
||||
self.choose(selected);
|
||||
cx.propose(stops);
|
||||
}
|
||||
|
||||
/// The press, drag and release of the marker `marker`.
|
||||
fn pointer(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, stops: &GradientStops, marker: StopRef) {
|
||||
let part = part_of(marker);
|
||||
let press = cx.part(part).press;
|
||||
match press.phase {
|
||||
PressPhase::Down { .. } => {
|
||||
cx.memory::<Held>().before = self.selected_marker;
|
||||
self.choose(Some(marker));
|
||||
cx.focus_part(part);
|
||||
if press.double_pressed()
|
||||
&& let StopRef::Color(i) = marker
|
||||
{
|
||||
self.color_requested = Some(i);
|
||||
}
|
||||
}
|
||||
PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => {
|
||||
let drag = Drag {
|
||||
marker,
|
||||
base: stops.clone(),
|
||||
press: start.origin,
|
||||
grab: geo.location_of(stops, marker),
|
||||
copy: press.mods.alt && marker.is_stop(),
|
||||
};
|
||||
self.choose(Some(marker));
|
||||
cx.begin();
|
||||
self.drag_to(cx, geo, &drag, pos);
|
||||
cx.memory::<Held>().drag = Some(drag);
|
||||
}
|
||||
PressPhase::Drag { pos, .. } => {
|
||||
if let Some(drag) = cx.memory::<Held>().drag.clone() {
|
||||
self.drag_to(cx, geo, &drag, pos);
|
||||
}
|
||||
}
|
||||
PressPhase::Release { pos, start, .. } => match cx.memory::<Held>().drag.take() {
|
||||
Some(drag) => {
|
||||
self.drag_to(cx, geo, &drag, pos);
|
||||
cx.commit();
|
||||
}
|
||||
None if start.button == PointerButton::Secondary => self.choose(Some(marker)),
|
||||
None => {}
|
||||
},
|
||||
PressPhase::Cancel { .. } => {
|
||||
let held = cx.memory::<Held>();
|
||||
held.drag = None;
|
||||
let before = held.before;
|
||||
if self.selected_marker != before {
|
||||
self.choose(before);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stop added where a click on empty space was: above the ramp's centre in the opacity row of a split bar, else in
|
||||
/// the colour row.
|
||||
fn add_at(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, stops: &GradientStops, pos: Pos2) {
|
||||
let row = match geo.rows {
|
||||
StopRows::Split if pos.y < geo.ramp.center().y => StopRow::Opacity,
|
||||
_ => StopRow::Color,
|
||||
};
|
||||
let default = default_sampler(self.rows());
|
||||
let sampler: &Sampler = self.sampler.unwrap_or(&default);
|
||||
if let Some((added, j)) = stops::add(stops, row, stops::round_location(geo.location(pos.x)), sampler, &self.rules) {
|
||||
self.choose(Some(StopRef::stop(row, j)));
|
||||
cx.set(added);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the next or previous marker of the selected row; the first or last with nothing selected.
|
||||
fn step(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, stops: &GradientStops, forward: bool) {
|
||||
let row = self.selected_marker.map_or(StopRow::Color, StopRef::row);
|
||||
let order = geo.order(stops, row);
|
||||
let Some(last) = order.len().checked_sub(1) else { return };
|
||||
let k = match self.selected_marker.and_then(|s| order.iter().position(|m| *m == s)) {
|
||||
None if forward => 0,
|
||||
None => last,
|
||||
Some(k) if forward => (k + 1).min(last),
|
||||
Some(k) => k.saturating_sub(1),
|
||||
};
|
||||
self.choose(Some(order[k]));
|
||||
cx.focus_part(part_of(order[k]));
|
||||
}
|
||||
|
||||
/// Selects the stop of `row` nearest the selected marker's location.
|
||||
fn switch(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, stops: &GradientStops, row: StopRow) {
|
||||
if self.selected_marker.is_some_and(|s| s.row() == row) {
|
||||
return;
|
||||
}
|
||||
let at = self.selected_marker.map_or(0.0, |s| geo.location_of(stops, s));
|
||||
let nearest = locations(stops, row).into_iter().enumerate().min_by(|a, b| (a.1 - at).abs().total_cmp(&(b.1 - at).abs())).map(|(i, _)| i);
|
||||
if let Some(i) = nearest {
|
||||
self.choose(Some(StopRef::stop(row, i)));
|
||||
cx.focus_part(part_of(StopRef::stop(row, i)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Selection, moves, deletes and additions while the bar has focus and no drag is under way. Each pass's changes are
|
||||
/// one Set.
|
||||
fn keys(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, shown: &GradientStops) {
|
||||
let mut stops = shown.clone();
|
||||
while cx.take_claimed(Chord::plain(Key::Plus)) | cx.take_claimed(Chord::plain(Key::Equals)) {
|
||||
self.step(cx, geo, &stops, true);
|
||||
}
|
||||
while cx.take_claimed(Chord::plain(Key::Minus)) {
|
||||
self.step(cx, geo, &stops, false);
|
||||
}
|
||||
while cx.take_claimed(Chord::plain(Key::Insert)) | cx.take_claimed(Chord::new(Mods::CMD, Key::Enter)) {
|
||||
let row = self.selected_marker.map_or(StopRow::Color, StopRef::row);
|
||||
let after = self.selected_marker.map(StopRef::index).filter(|i| *i < stops.len(row));
|
||||
let default = default_sampler(self.rows());
|
||||
let sampler: &Sampler = self.sampler.unwrap_or(&default);
|
||||
if let Some((added, j)) = stops::add(&stops, row, stops::halfway(&stops, row, after), sampler, &self.rules) {
|
||||
stops = added;
|
||||
self.choose(Some(StopRef::stop(row, j)));
|
||||
cx.focus_part(part_of(StopRef::stop(row, j)));
|
||||
}
|
||||
}
|
||||
// Enter on a focused marker activates that part (Intent::Activate is not delivered while a part is active).
|
||||
let activated = self.selected_marker.is_some_and(|m| matches!(cx.part_activated(part_of(m)), Some(FireSource::Key | FireSource::Access)));
|
||||
if activated {
|
||||
match self.selected_marker {
|
||||
Some(StopRef::Color(i)) => self.color_requested = Some(i),
|
||||
Some(_) => self.field_requested = true,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some(m) = self.selected_marker.filter(|m| geo.valid(&stops, *m)) {
|
||||
let removed = [true, false].into_iter().any(|forward| cx.intents().take_exact(&Intent::delete(forward, Granularity::Unit)));
|
||||
if removed
|
||||
&& m.is_stop()
|
||||
&& let Some((out, j)) = stops::remove(&stops, m.row(), m.index(), &self.rules)
|
||||
{
|
||||
stops = out;
|
||||
self.choose(Some(StopRef::stop(m.row(), j)));
|
||||
cx.focus_part(part_of(StopRef::stop(m.row(), j)));
|
||||
}
|
||||
}
|
||||
while let Some((dir, mods)) = cx.intents().take_nudge() {
|
||||
if mods.alt || mods.ctrl || mods.cmd {
|
||||
continue;
|
||||
}
|
||||
if dir.y != 0.0 && geo.rows == StopRows::Split {
|
||||
self.switch(cx, geo, &stops, if dir.y < 0.0 { StopRow::Opacity } else { StopRow::Color });
|
||||
continue;
|
||||
}
|
||||
let by = dir.x.signum() * if mods.shift { STOP_STEP_FAR } else { STOP_STEP };
|
||||
let Some(m) = self.selected_marker.filter(|m| geo.valid(&stops, *m)).filter(|_| dir.x != 0.0) else { continue };
|
||||
let moved = match m {
|
||||
StopRef::Midpoint(row, i) => stops::set_midpoint(&stops, row, i, midpoint(&stops, row, i) + by, &self.rules).map(|(s, _)| (s, m)),
|
||||
_ => stops::move_to(&stops, m.row(), m.index(), location(&stops, m.row(), m.index()) + by, &self.rules)
|
||||
.map(|(s, j)| (s, m.with_index(j))),
|
||||
};
|
||||
if let Some((out, now)) = moved {
|
||||
stops = out;
|
||||
self.choose(Some(now));
|
||||
cx.focus_part(part_of(now));
|
||||
}
|
||||
}
|
||||
if stops != *shown {
|
||||
cx.set(stops);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Clone + Send + Sync + 'static> Component for GradientBar<'_, P> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const OVERLAYS: bool = false;
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_activate(ActivateKeys::Both).with_deletes().with_chrome_key(false).with_claims(&CLAIMS);
|
||||
type Style = GradientBarStyle;
|
||||
type Output = GradientBarOutput<P>;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: GradientBarStyleKey<P>) -> GradientBarStyle {
|
||||
let tokens = cx.tokens;
|
||||
let (size, stroke, colors) = (&tokens.size, &tokens.stroke, &tokens.color);
|
||||
let (rest, disabled) = (cx.color(colors.text.muted), cx.color(colors.text.disabled));
|
||||
let (ramp_rest, ramp_disabled) = (cx.color(colors.line.control_edge), cx.color(colors.text.disabled));
|
||||
GradientBarStyle {
|
||||
metrics: Metrics::new(),
|
||||
focus: cx.focus_look(),
|
||||
length: size.length.track,
|
||||
ramp_height: cx.control().height,
|
||||
inset: tokens.space.pad.control,
|
||||
marker: size.handle.md,
|
||||
pointer: size.handle.sm / 2.0 + stroke.thin,
|
||||
diamond: size.handle.sm,
|
||||
hit: size.hit.target,
|
||||
tear_off: cx.control().height * TEAR_OFF_SHARE,
|
||||
edge: Stateful::new(rest).off(States::new(rest, rest, rest, disabled)),
|
||||
hovered: cx.color(colors.text.normal),
|
||||
selected: cx.color(colors.accent.solid),
|
||||
ramp_edge: Stateful::new(ramp_rest).off(States::new(ramp_rest, ramp_rest, ramp_rest, ramp_disabled)),
|
||||
drop: cx.color(colors.accent.solid),
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let width = cx.room.filter(|room| room.is_finite()).unwrap_or(cx.style.length);
|
||||
Vec2::new(width, Geometry::height(self.rows(), self.midpoints, self.opacity_midpoints, cx.style))
|
||||
}
|
||||
|
||||
fn fills(&self) -> Option<Axis> {
|
||||
Some(Axis::X)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, GradientStops>> {
|
||||
Some(self.value.reborrow())
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let Some(stops) = cx.value().cloned() else { return };
|
||||
let geo = self.geometry(rect, cx.style);
|
||||
cx.part(RAMP, rect).sense(Sense::CLICK | Sense::TAKE_FOCUS).pointer_only("Insert adds a stop after the selected marker");
|
||||
let markers = geo.markers(&stops);
|
||||
for marker in &markers {
|
||||
let priority = HitPriority::new(HitLevel::Handle, u8::from(marker.is_stop()));
|
||||
let part = cx
|
||||
.part(part_of(*marker), geo.hit_rect(&stops, *marker))
|
||||
.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS)
|
||||
.priority(priority)
|
||||
.cursor(CursorIcon::ResizeHorizontal)
|
||||
.focusable()
|
||||
.nudges()
|
||||
.focus_shape(FocusShape::Rect);
|
||||
if self.selected_marker == Some(*marker) {
|
||||
part.selected().flags(Flags::SELECTED);
|
||||
}
|
||||
}
|
||||
if !markers.is_empty() {
|
||||
cx.roving(Roving::new(NavShape::Flat));
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let Some(stops) = cx.value().cloned() else { return };
|
||||
let geo = self.geometry(cx.rect, cx.style);
|
||||
let enabled = cx.resolved.enabled;
|
||||
let was = self.selected_marker;
|
||||
self.selected_marker = self.selected_marker.filter(|m| geo.valid(&stops, *m));
|
||||
if enabled {
|
||||
let focused = cx.active_part().and_then(marker_of).filter(|m| geo.valid(&stops, *m));
|
||||
// Focus arriving at a marker selects it, unless a press holds it (the press selects by its own rule).
|
||||
if let Some(part) = cx.focus_arrived_by_key()
|
||||
&& let Some(m) = marker_of(part).filter(|m| geo.valid(&stops, *m))
|
||||
{
|
||||
self.choose(Some(m));
|
||||
}
|
||||
for marker in geo.markers(&stops) {
|
||||
self.pointer(cx, &geo, &stops, marker);
|
||||
}
|
||||
let ramp = cx.part(RAMP).press;
|
||||
if let PressPhase::Release { pos, start, click: true, .. } = ramp.phase
|
||||
&& start.button == PointerButton::Primary
|
||||
&& cx.memory::<Held>().drag.is_none()
|
||||
{
|
||||
self.add_at(cx, &geo, &stops, pos);
|
||||
}
|
||||
if focused.is_some() && cx.memory::<Held>().drag.is_none() && cx.gesture().is_none() {
|
||||
self.keys(cx, &geo, &stops);
|
||||
}
|
||||
if self.drop_target {
|
||||
let target = OnBar::<P> { geo, stops: &stops, live: true, payload: PhantomData };
|
||||
self.dropped = cx.drop_target::<P, _>(&target);
|
||||
}
|
||||
}
|
||||
if self.selected_marker != was && self.select.is_none() {
|
||||
self.select = Some(self.selected_marker);
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let Some(stops) = cx.value() else { return };
|
||||
let words = cx.words::<GradientWords>();
|
||||
let units = cx.env.units();
|
||||
let geo = self.geometry(cx.rect, cx.style);
|
||||
let count = |n: usize| (n, n.to_string());
|
||||
let value = match self.rows() {
|
||||
StopRows::Split => {
|
||||
let (colors, opacities) = (count(stops.color.len()), count(stops.opacity_stops().len()));
|
||||
words.split_value.fill(&[
|
||||
("colors", &words.color_stops.text(colors.0 as u64, &colors.1)),
|
||||
("opacities", &words.opacity_stops.text(opacities.0 as u64, &opacities.1)),
|
||||
])
|
||||
}
|
||||
_ => {
|
||||
let n = count(stops.color.len());
|
||||
words.bar_stops.text(n.0 as u64, &n.1)
|
||||
}
|
||||
};
|
||||
access.value(value);
|
||||
for marker in geo.markers(stops) {
|
||||
let (name, value) = marker_texts(&words, &units, self.rows(), stops, marker, self.location_decimals);
|
||||
let node = access.node(part_of(marker), Role::GRAPHICS_OBJECT);
|
||||
node.name = Name::Text(name);
|
||||
node.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let Some(stops) = cx.value() else { return };
|
||||
let style = cx.style;
|
||||
let geo = self.geometry(cx.rect, style);
|
||||
let default = default_sampler(self.rows());
|
||||
let sampler: &Sampler = self.sampler.unwrap_or(&default);
|
||||
GradientRamp::paint(&ui.content_painter(cx), geo.ramp, egui::CornerRadius::ZERO, &GradientRamp::colors(stops, sampler));
|
||||
let dragging = cx.recall::<Held>().drag.is_some();
|
||||
let draw = ui.draw();
|
||||
draw.stroke(&PaintShape::Rect(geo.ramp, CornerRadius::ZERO), StrokeWidth::Thin, cx.resolve(&style.ramp_edge));
|
||||
let edge_of = |m: StopRef| {
|
||||
if self.selected_marker == Some(m) {
|
||||
style.selected
|
||||
} else if !dragging && cx.hover_pos(part_of(m)).is_some() {
|
||||
style.hovered
|
||||
} else {
|
||||
cx.resolve(&style.edge)
|
||||
}
|
||||
};
|
||||
let mut markers = geo.markers(stops);
|
||||
// The selected marker on top of the others.
|
||||
markers.sort_by_key(|m| self.selected_marker == Some(*m));
|
||||
for m in markers {
|
||||
let edge = edge_of(m);
|
||||
match m {
|
||||
StopRef::Midpoint(row, i) => {
|
||||
let shape = diamond(geo.diamond_center(row, midpoint_at(stops, row, i)), geo.diamond);
|
||||
if self.selected_marker == Some(m) {
|
||||
draw.fill(&shape, style.selected);
|
||||
}
|
||||
draw.stroke(&shape, StrokeWidth::Thin, edge);
|
||||
}
|
||||
m => {
|
||||
let (row, at) = (m.row(), location(stops, m.row(), m.index()));
|
||||
let content = match row {
|
||||
StopRow::Color => Color32::from(Srgba { a: 1.0, ..stops.color[m.index()].color }),
|
||||
StopRow::Opacity => Color32::from_gray((stops.opacity_stops()[m.index()].opacity.clamp(0.0, 1.0) * 255.0).round() as u8),
|
||||
};
|
||||
let (body, x, half) = (geo.body(row, at), geo.x(at), geo.marker / 2.0);
|
||||
let (tip, base) = match row {
|
||||
StopRow::Color => (geo.ramp.bottom() + 1.0, body.top()),
|
||||
StopRow::Opacity => (geo.ramp.top() - 1.0, body.bottom()),
|
||||
};
|
||||
draw.fill(&PaintShape::Polygon(vec![pos2(x, tip), pos2(x + half, base), pos2(x - half, base)]), edge);
|
||||
let square = PaintShape::Rect(body, CornerRadius::ZERO);
|
||||
draw.data_fill(&square, DataColor::new(content));
|
||||
draw.stroke(&square, StrokeWidth::Thin, edge);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> GradientBarOutput<P> {
|
||||
GradientBarOutput {
|
||||
edit: cx.edit_response(),
|
||||
select: self.select,
|
||||
color_requested: self.color_requested,
|
||||
field_requested: self.field_requested,
|
||||
dropped: self.dropped,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
//! The fields under the bar: the selected marker's Color well, Opacity, Location, Midpoint and Delete, each an
|
||||
//! edit of the editor's stops.
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvent, GestureId, IconId, Mixed};
|
||||
use crate::ui::{ColorPicker, ColorPopover, PickedColor, ScreenPickGesture};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::choice::Swatch;
|
||||
use craft_ui::contract::{Bind, BodyCx, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Id, Ui};
|
||||
|
||||
use crate::gradient::stops::{self, StopRules, locations, midpoint};
|
||||
use crate::gradient::{GradientStops, StopRow, StopRows};
|
||||
use crate::ui::gradient::StopRef;
|
||||
use crate::ui::gradient::words::GradientWords;
|
||||
|
||||
/// The key of the id of the first number field, which Enter or Space on an opacity stop or a midpoint focuses.
|
||||
pub(super) const FIRST_FIELD: &str = "first-field";
|
||||
|
||||
/// The setup closure of the popover's picker.
|
||||
pub(super) type PickerSetup<'a> = Box<dyn for<'b> Fn(ColorPicker<'b>) -> ColorPicker<'b> + 'a>;
|
||||
|
||||
/// Which number field of the fields row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Number {
|
||||
Opacity,
|
||||
Location,
|
||||
Midpoint,
|
||||
}
|
||||
|
||||
/// A number field of one stop: which field, in which row, of which stop.
|
||||
#[derive(Clone, Copy)]
|
||||
struct At {
|
||||
field: Number,
|
||||
row: StopRow,
|
||||
i: usize,
|
||||
}
|
||||
|
||||
/// The Location field's run under way: the stops as it began and the stop's index in them. Every value of the run
|
||||
/// moves that stop from there, as a drag edits the stops at its press, so a run that passes a neighbour and comes
|
||||
/// back leaves the stops as they were.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct LocationRun {
|
||||
run: Option<(Option<GestureId>, StopRow, usize)>,
|
||||
base: GradientStops,
|
||||
}
|
||||
|
||||
/// Whether the colour popover is open.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PopoverOpen(bool);
|
||||
|
||||
/// What the fields row decides in a pass.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Report {
|
||||
/// The edits of the stops, in the order made.
|
||||
pub events: Vec<EditEvent<GradientStops>>,
|
||||
/// The selection the fields moved.
|
||||
pub select: Option<Option<StopRef>>,
|
||||
/// The colour stop whose colour the host is asked to edit.
|
||||
pub color_requested: Option<usize>,
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
/// What the row reads from the editor.
|
||||
pub(super) struct Row<'r, 'a> {
|
||||
pub words: &'r GradientWords,
|
||||
pub rules: &'r StopRules,
|
||||
pub location_decimals: usize,
|
||||
pub enabled: bool,
|
||||
pub fields: bool,
|
||||
pub color_popover: bool,
|
||||
pub picker: &'r Option<PickerSetup<'a>>,
|
||||
pub sampled: Option<Srgba>,
|
||||
/// The colour request of the bar, when the bar asked for one.
|
||||
pub requested: Option<usize>,
|
||||
}
|
||||
|
||||
/// A 0..=1 value in percent, without the binary fraction an `f32` adds (0.3 is 30, not 30.0000012).
|
||||
fn percent(v: f32) -> f64 {
|
||||
(f64::from(v) * 1e6).round() / 1e4
|
||||
}
|
||||
|
||||
/// A label of `word`.
|
||||
fn label(word: &str) -> Label {
|
||||
Label::from(word.to_owned())
|
||||
}
|
||||
|
||||
/// What `field` of stop `i` of `row` shows, in percent.
|
||||
fn field_value(field: Number, stops: &GradientStops, row: StopRow, i: usize) -> f64 {
|
||||
percent(match (field, row) {
|
||||
(Number::Opacity, StopRow::Color) => stops.color[i].color.a,
|
||||
(Number::Opacity, StopRow::Opacity) => stops.opacity_stops()[i].opacity,
|
||||
(Number::Location, _) => locations(stops, row)[i],
|
||||
(Number::Midpoint, _) => midpoint(stops, row, i),
|
||||
})
|
||||
}
|
||||
|
||||
/// `stops` with `field` of stop `i` of `row` at `v` percent, and the stop's index after it.
|
||||
fn set_field(field: Number, stops: &GradientStops, row: StopRow, i: usize, v: f64, rules: &StopRules) -> Option<(GradientStops, usize)> {
|
||||
let v = (v / 100.0) as f32;
|
||||
match (field, row) {
|
||||
(Number::Opacity, StopRow::Color) => {
|
||||
let mut out = stops.clone();
|
||||
out.color[i].color.a = v;
|
||||
Some((out, i))
|
||||
}
|
||||
(Number::Opacity, StopRow::Opacity) => {
|
||||
let mut out = GradientStops::with_opacity(stops.color.clone(), stops.opacity_stops().into_owned());
|
||||
out.opacity[i].opacity = v;
|
||||
Some((out, i))
|
||||
}
|
||||
(Number::Location, _) => stops::move_to(stops, row, i, v, rules),
|
||||
(Number::Midpoint, _) => stops::set_midpoint(stops, row, i, v, rules),
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour stop `i` of `stops` in `color`; a split gradient's colour stops keep their own alpha, which nothing shows.
|
||||
pub(super) fn with_color(stops: &GradientStops, rows: StopRows, i: usize, color: Srgba) -> GradientStops {
|
||||
let mut out = stops.clone();
|
||||
let stop = &mut out.color[i].color;
|
||||
*stop = match rows {
|
||||
StopRows::Combined => color,
|
||||
StopRows::Split => Srgba { a: stop.a, ..color },
|
||||
_ => Srgba { a: 1.0, ..color },
|
||||
};
|
||||
out
|
||||
}
|
||||
|
||||
/// Colour stop `i`'s colour as the well shows it: opaque unless the alpha is the colour's.
|
||||
pub(super) fn stop_color(stops: &GradientStops, rows: StopRows, i: usize) -> Srgba {
|
||||
let color = stops.color[i].color;
|
||||
if rows == StopRows::Combined { color } else { Srgba { a: 1.0, ..color } }
|
||||
}
|
||||
|
||||
/// One `Set` of the stops, replacing `before`.
|
||||
fn set_event(before: &GradientStops, after: GradientStops, name: &str) -> EditEvent<GradientStops> {
|
||||
EditEvent::set(Mixed::Same(before.clone()), after, Arc::from(name), None)
|
||||
}
|
||||
|
||||
/// A number field in percent named `name`, which its label scrubs.
|
||||
fn number(
|
||||
ui: &mut Ui,
|
||||
id: Option<Id>,
|
||||
name: &str,
|
||||
value: f64,
|
||||
range: RangeInclusive<f64>,
|
||||
decimals: usize,
|
||||
enabled: bool,
|
||||
) -> craft_ui::contract::EditResponse<Option<f64>> {
|
||||
let shown = Field::new(label(name)).show(ui, |ui, _| {
|
||||
let field = NumberField::new(label(name), Bind::given(Some(value)))
|
||||
.unit_kind(UnitKind::Percent)
|
||||
.range(range.clone())
|
||||
.step(1.0)
|
||||
.commit_decimals(decimals)
|
||||
.scrub_by_label()
|
||||
.enabled(enabled);
|
||||
match id {
|
||||
Some(id) => field.id(id),
|
||||
None => field,
|
||||
}
|
||||
.show(ui)
|
||||
.edit
|
||||
});
|
||||
shown.inner.unwrap_or_else(|| craft_ui::contract::EditResponse::lifted(shown.output, craft_behavior::EditEvents::new(), None))
|
||||
}
|
||||
|
||||
impl Row<'_, '_> {
|
||||
/// The selected marker's fields under the bar, as the rows of PhotoCraft's panel, and the colour popover. `now` are
|
||||
/// the stops as the pass leaves them; each edit is drawn from them and reported in the order made.
|
||||
pub(super) fn show(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
cx: &mut BodyCx<'_>,
|
||||
now: &GradientStops,
|
||||
selected: Option<StopRef>,
|
||||
anchor: &egui::Response,
|
||||
) -> Report {
|
||||
let mut report = Report { color_requested: self.requested.filter(|_| !self.color_popover), ..Report::default() };
|
||||
let selected = selected.filter(|m| match *m {
|
||||
StopRef::Midpoint(row, i) => i + 1 < now.len(row),
|
||||
m => m.index() < now.len(m.row()),
|
||||
});
|
||||
let Some(marker) = selected else {
|
||||
cx.memory::<PopoverOpen>().0 = false;
|
||||
return report;
|
||||
};
|
||||
if self.fields {
|
||||
FieldGroup::new(label(self.words.stop_fields.as_str())).show(ui, |ui, _| self.rows(ui, cx, now, marker, &mut report));
|
||||
} else if let StopRef::Color(i) = marker {
|
||||
if self.requested.is_some() {
|
||||
cx.memory::<PopoverOpen>().0 = true;
|
||||
}
|
||||
self.popover(ui, cx, now, i, anchor, &mut report);
|
||||
}
|
||||
if !matches!(marker, StopRef::Color(_)) {
|
||||
cx.memory::<PopoverOpen>().0 = false;
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
fn rows(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, now: &GradientStops, marker: StopRef, report: &mut Report) {
|
||||
let rows = self.rules.rows;
|
||||
match marker {
|
||||
StopRef::Color(i) => {
|
||||
let well = Field::new(label(self.words.color.as_str()))
|
||||
.show(ui, |ui, _| Swatch::new(label(self.words.color.as_str()), stop_color(now, rows, i)).enabled(self.enabled).show(ui))
|
||||
.inner;
|
||||
if let Some(well) = well {
|
||||
if self.color_popover {
|
||||
let open = &mut cx.memory::<PopoverOpen>().0;
|
||||
if well.clicked {
|
||||
*open = !*open;
|
||||
} else if self.requested.is_some() {
|
||||
*open = true;
|
||||
}
|
||||
self.popover(ui, cx, now, i, &well.response, report);
|
||||
} else if well.clicked {
|
||||
report.color_requested = Some(i);
|
||||
}
|
||||
}
|
||||
if rows == StopRows::Combined {
|
||||
self.number(ui, cx, now, At { field: Number::Opacity, row: StopRow::Color, i }, report);
|
||||
}
|
||||
self.number(ui, cx, now, At { field: Number::Location, row: StopRow::Color, i }, report);
|
||||
self.delete(ui, now, StopRow::Color, i, report);
|
||||
}
|
||||
StopRef::Opacity(i) => {
|
||||
self.number(ui, cx, now, At { field: Number::Opacity, row: StopRow::Opacity, i }, report);
|
||||
self.number(ui, cx, now, At { field: Number::Location, row: StopRow::Opacity, i }, report);
|
||||
self.delete(ui, now, StopRow::Opacity, i, report);
|
||||
}
|
||||
StopRef::Midpoint(row, i) => self.number(ui, cx, now, At { field: Number::Midpoint, row, i }, report),
|
||||
}
|
||||
}
|
||||
|
||||
/// The range and decimals of `field`, in percent.
|
||||
fn range(&self, field: Number) -> (RangeInclusive<f64>, usize) {
|
||||
match field {
|
||||
Number::Opacity => (0.0..=100.0, 0),
|
||||
Number::Location => (0.0..=100.0, self.location_decimals),
|
||||
Number::Midpoint => (percent(*self.rules.midpoint.start())..=percent(*self.rules.midpoint.end()), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The number field `field` of stop `i` of `row`, and its edit mapped onto the stops.
|
||||
fn number(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, now: &GradientStops, at: At, report: &mut Report) {
|
||||
let At { field, row, i } = at;
|
||||
let name = match field {
|
||||
Number::Opacity => self.words.opacity.as_str(),
|
||||
Number::Location => self.words.location.as_str(),
|
||||
Number::Midpoint => self.words.midpoint_field.as_str(),
|
||||
};
|
||||
let (range, decimals) = self.range(field);
|
||||
let id = (field != Number::Location && !(row == StopRow::Color && field == Number::Opacity)).then(|| cx.key(FIRST_FIELD));
|
||||
let shown = number(ui, id, name, field_value(field, now, row, i), range, decimals, self.enabled);
|
||||
let rules = self.rules.clone();
|
||||
for event in shown.events {
|
||||
if field != Number::Location {
|
||||
report.events.push(event.map(|v| v.and_then(|v| set_field(field, now, row, i, v, &rules)).map_or_else(|| now.clone(), |(s, _)| s)));
|
||||
continue;
|
||||
}
|
||||
// Each value of a run moves the stop from where the run began; the selection follows it past a neighbour.
|
||||
let run = cx.memory::<LocationRun>();
|
||||
let id = event.id();
|
||||
if run.run.map(|(id, ..)| id) != Some(id) {
|
||||
*run = LocationRun { run: Some((id, row, i)), base: now.clone() };
|
||||
}
|
||||
let (base, from) = (run.base.clone(), run.run.map_or(i, |(_, _, from)| from));
|
||||
if let Some(v) = event.value().copied().flatten()
|
||||
&& let Some((_, j)) = stops::move_to(&base, row, from, (v / 100.0) as f32, &rules)
|
||||
{
|
||||
report.select = Some(Some(StopRef::stop(row, j)));
|
||||
}
|
||||
if event.phase().is_none_or(|phase| matches!(phase, craft_behavior::GesturePhase::Commit | craft_behavior::GesturePhase::Cancel)) {
|
||||
*cx.memory::<LocationRun>() = LocationRun::default();
|
||||
}
|
||||
report.events.push(
|
||||
event.map(|v| v.and_then(|v| stops::move_to(&base, row, from, (v / 100.0) as f32, &rules)).map_or_else(|| now.clone(), |(s, _)| s)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Delete button, disabled at the row's minimum.
|
||||
fn delete(&mut self, ui: &mut Ui, now: &GradientStops, row: StopRow, i: usize, report: &mut Report) {
|
||||
let enabled = self.enabled && now.len(row) > self.rules.min;
|
||||
let name = label(self.words.delete.as_str());
|
||||
let button = IconButton::new(IconId::new("trash")).label(name).enabled(enabled).show(ui);
|
||||
if clicked(&button)
|
||||
&& let Some((out, j)) = stops::remove(now, row, i, self.rules)
|
||||
{
|
||||
report.select = Some(Some(StopRef::stop(row, j)));
|
||||
report.events.push(set_event(now, out, self.words.delete.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour popover of colour stop `i`, hung from `opener`, while it is open.
|
||||
fn popover(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, now: &GradientStops, i: usize, opener: &egui::Response, report: &mut Report) {
|
||||
let rows = self.rules.rows;
|
||||
let host = self.picker.as_deref();
|
||||
let sampled = self.sampled;
|
||||
let mut open = cx.memory::<PopoverOpen>().0;
|
||||
let shown = ColorPopover::new(label(self.words.popover.as_str()), Bind::given(PickedColor::rgb(stop_color(now, rows, i))))
|
||||
.picker(move |picker| {
|
||||
let picker = picker.alpha(rows == StopRows::Combined);
|
||||
let picker = match sampled {
|
||||
Some(color) => picker.sampled(color),
|
||||
None => picker,
|
||||
};
|
||||
match host {
|
||||
Some(host) => host(picker),
|
||||
None => picker,
|
||||
}
|
||||
})
|
||||
.anchor(opener, Bind::bound(&mut open))
|
||||
.show(ui);
|
||||
cx.memory::<PopoverOpen>().0 = open && shown.open;
|
||||
report.screen_pick = shown.screen_pick;
|
||||
for event in shown.events {
|
||||
report.events.push(event.map(|picked| with_color(now, rows, i, picked.color)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! The gradient stop bar's widgets: [`GradientEditor`], the stop bar that edits the stops, and [`GradientRamp`], the paint.
|
||||
//!
|
||||
//! The model and the stop rules ([`GradientStops`], [`stops`]) need no egui and live in [`crate::gradient`]; they are
|
||||
//! re-exported here so a widget user imports the editor and its model from one path.
|
||||
|
||||
mod editor;
|
||||
mod ramp;
|
||||
mod value;
|
||||
mod words;
|
||||
|
||||
pub use crate::gradient::{ColorStop, GradientStops, OpacityStop, Sampler, StopRow, StopRows, StopRules, default_sampler, stops};
|
||||
pub use editor::{GradientEditor, GradientEditorOutput, StopDrop, marker_texts};
|
||||
pub use ramp::GradientRamp;
|
||||
pub use value::{StopColor, StopRef};
|
||||
pub use words::GradientWords;
|
||||
@@ -0,0 +1,72 @@
|
||||
//! [`GradientRamp`]: a gradient drawn across a rect over the checkerboard.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::SwatchMetrics;
|
||||
use craft_ui::primitives::{Checker, ContentPainterCx, PaintShape, StrokeWidth};
|
||||
use craft_ui::style::{DataColor, StyleColor, StyleCx};
|
||||
use egui::{Color32, CornerRadius, Rect};
|
||||
|
||||
use crate::gradient::{GradientStops, Sampler, StopRow};
|
||||
|
||||
/// Even samples added to a stop bar's own, so a custom sampler's curve shows.
|
||||
const EVEN_SAMPLES: usize = 64;
|
||||
|
||||
/// Paint for a gradient: a mesh across a rect, over the checkerboard where it is translucent.
|
||||
/// The ramp has no edge; [`GradientSwatch`](super::GradientSwatch) draws a swatch's rings and the
|
||||
/// stop bar its edge.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GradientRamp;
|
||||
|
||||
impl GradientRamp {
|
||||
/// Width to height of a gradient chip, a swatch or a palette cell: wide enough that the ramp reads along it.
|
||||
pub const CHIP_ASPECT: (u16, u16) = (16, 9);
|
||||
|
||||
/// The colours to draw `stops` with at the locations a mesh needs: the ends, every stop and
|
||||
/// midpoint of both rows, and even steps between, from `sampler`.
|
||||
pub fn colors(stops: &GradientStops, sampler: &Sampler) -> Vec<(f32, Srgba)> {
|
||||
let mut at = vec![0.0, 1.0];
|
||||
at.extend((1..EVEN_SAMPLES).map(|k| k as f32 / EVEN_SAMPLES as f32));
|
||||
let mut rows = vec![(StopRow::Color, stops.color.iter().map(|s| (s.location, s.midpoint)).collect::<Vec<_>>())];
|
||||
rows.push((StopRow::Opacity, stops.opacity.iter().map(|s| (s.location, s.midpoint)).collect()));
|
||||
for (_, list) in &rows {
|
||||
for (k, &(a, m)) in list.iter().enumerate() {
|
||||
at.push(a);
|
||||
if let Some(&(b, _)) = list.get(k + 1) {
|
||||
at.push(a + m * (b - a));
|
||||
}
|
||||
}
|
||||
}
|
||||
at.retain(|x| x.is_finite());
|
||||
at.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0));
|
||||
at.sort_by(f32::total_cmp);
|
||||
at.dedup_by(|a, b| (*a - *b).abs() < 1e-4);
|
||||
at.into_iter().map(|x| (x, sampler(stops, x))).collect()
|
||||
}
|
||||
|
||||
/// Paints `colors` (location 0..=1, sorted) across `rect` with corners of `radius`, straight lines
|
||||
/// between them, over the theme's checkerboard where a colour is translucent; the end colours
|
||||
/// continue to the rect's ends.
|
||||
pub fn paint(cx: &ContentPainterCx<'_>, rect: Rect, radius: CornerRadius, colors: &[(f32, Srgba)]) {
|
||||
if colors.is_empty() || rect.width() <= 0.0 || rect.height() <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if colors.iter().any(|(_, c)| c.a < 1.0) {
|
||||
cx.checker_with(&Checker::new(), rect, radius);
|
||||
}
|
||||
let stops: Vec<(f32, DataColor)> = colors.iter().map(|&(at, c)| (at, DataColor::new(Color32::from(c)))).collect();
|
||||
cx.ramp(rect, radius, &stops, Axis::X);
|
||||
}
|
||||
|
||||
/// The corners and the ring of a gradient chip: the colour swatch's corners and `line.control_edge`.
|
||||
pub fn chip_look(cx: &StyleCx<'_>) -> (CornerRadius, StyleColor) {
|
||||
(SwatchMetrics::of(cx).radius, cx.color(cx.tokens.color.line.control_edge))
|
||||
}
|
||||
|
||||
/// A gradient chip: `colors` across `rect` in corners of `radius`, inside a thin `edge` ring that separates it
|
||||
/// from the panel.
|
||||
pub fn paint_chip(cx: &ContentPainterCx<'_>, rect: Rect, radius: CornerRadius, colors: &[(f32, Srgba)], edge: StyleColor) {
|
||||
Self::paint(cx, rect, radius, colors);
|
||||
cx.with_draw(|draw| draw.stroke(&PaintShape::Rect(rect, radius), StrokeWidth::Thin, edge));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! The stop bar's marker vocabulary: [`StopRef`] and [`StopColor`].
|
||||
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
|
||||
use crate::gradient::StopRow;
|
||||
|
||||
/// A marker of the stop bar: a colour stop, an opacity stop, or the midpoint after stop `i` of a
|
||||
/// row. Indices are into the stops as the bar shows them ([`GradientStops::opacity_stops`] for
|
||||
/// the opacity row).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum StopRef {
|
||||
/// Colour stop `i`.
|
||||
Color(usize),
|
||||
/// Opacity stop `i`.
|
||||
Opacity(usize),
|
||||
/// The midpoint after stop `i` of the given row.
|
||||
Midpoint(StopRow, usize),
|
||||
}
|
||||
|
||||
impl StopRef {
|
||||
/// The row the marker belongs to.
|
||||
pub fn row(self) -> StopRow {
|
||||
match self {
|
||||
StopRef::Color(_) => StopRow::Color,
|
||||
StopRef::Opacity(_) => StopRow::Opacity,
|
||||
StopRef::Midpoint(row, _) => row,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop `i` of `row`.
|
||||
pub(crate) fn stop(row: StopRow, i: usize) -> Self {
|
||||
match row {
|
||||
StopRow::Color => StopRef::Color(i),
|
||||
StopRow::Opacity => StopRef::Opacity(i),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stop's index, or for a midpoint the index of the stop before it.
|
||||
pub(crate) fn index(self) -> usize {
|
||||
match self {
|
||||
StopRef::Color(i) | StopRef::Opacity(i) | StopRef::Midpoint(_, i) => i,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same kind of marker at index `i`.
|
||||
pub(crate) fn with_index(self, i: usize) -> Self {
|
||||
match self {
|
||||
StopRef::Color(_) => StopRef::Color(i),
|
||||
StopRef::Opacity(_) => StopRef::Opacity(i),
|
||||
StopRef::Midpoint(row, _) => StopRef::Midpoint(row, i),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the marker is a stop and not a midpoint.
|
||||
pub(crate) fn is_stop(self) -> bool {
|
||||
!matches!(self, StopRef::Midpoint(..))
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour stop whose colour the host is asked to edit, with the request to hand to its colour
|
||||
/// picker dialog.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct StopColor {
|
||||
/// The colour stop's index.
|
||||
pub index: usize,
|
||||
/// The stop's tag.
|
||||
pub tag: u64,
|
||||
/// The request, opened at the stop's colour.
|
||||
pub request: ColorRequest,
|
||||
}
|
||||
|
||||
impl StopColor {
|
||||
/// A request to edit colour stop `index`, whose tag is `tag`.
|
||||
pub fn new(index: usize, tag: u64, request: ColorRequest) -> Self {
|
||||
Self { index, tag, request }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! The words of the gradient stop bar, its fields and the canvas gradient line.
|
||||
|
||||
craft_ui::words! {
|
||||
/// The gradient editor's words. Templates take `{i}`, `{n}`, `{location}`, `{hex}`, `{opacity}`, `{colors}`,
|
||||
/// `{opacities}`, `{x}` and `{y}`.
|
||||
pub struct GradientWords {
|
||||
/// A colour stop's accessible name: "Color stop {i} of {n}".
|
||||
color_stop: template "gradient.colorStop" = "Color stop {i} of {n}";
|
||||
/// A colour stop's accessible value: "{location}, {hex}".
|
||||
color_value: template "gradient.colorValue" = "{location}, {hex}";
|
||||
/// A colour stop's accessible value under `StopRows::Combined`.
|
||||
color_opacity_value: template "gradient.colorOpacityValue" = "{location}, {hex}, opacity {opacity}";
|
||||
/// An opacity stop's accessible name: "Opacity stop {i} of {n}".
|
||||
opacity_stop: template "gradient.opacityStop" = "Opacity stop {i} of {n}";
|
||||
/// An opacity stop's accessible value: "{location}, opacity {opacity}".
|
||||
opacity_value: template "gradient.opacityValue" = "{location}, opacity {opacity}";
|
||||
/// A colour midpoint's accessible name: "Midpoint {i}".
|
||||
midpoint: template "gradient.midpoint" = "Midpoint {i}";
|
||||
/// An opacity midpoint's accessible name: "Opacity midpoint {i}".
|
||||
opacity_midpoint: template "gradient.opacityMidpoint" = "Opacity midpoint {i}";
|
||||
/// The count of colour stops in the bar's value under `StopRows::Split`.
|
||||
color_stops: count "gradient.colorStops" = "{n} color stop" | "{n} color stops";
|
||||
/// The count of opacity stops in the bar's value under `StopRows::Split`.
|
||||
opacity_stops: count "gradient.opacityStops" = "{n} opacity stop" | "{n} opacity stops";
|
||||
/// The bar's value under `StopRows::Split`: "{colors}, {opacities}".
|
||||
split_value: template "gradient.splitValue" = "{colors}, {opacities}";
|
||||
/// The count of stops in the bar's value under `StopRows::Combined`.
|
||||
bar_stops: count "gradient.barStops" = "{n} stop" | "{n} stops";
|
||||
/// A canvas gradient line's end handle value, a point in document units: "{x}, {y}".
|
||||
point_value: template "gradient.pointValue" = "{x}, {y}";
|
||||
/// The Color field's label.
|
||||
color: "gradient.color" = "Color";
|
||||
/// The Opacity field's label.
|
||||
opacity: "gradient.opacity" = "Opacity";
|
||||
/// The Location field's label.
|
||||
location: "gradient.location" = "Location";
|
||||
/// The Midpoint field's label.
|
||||
midpoint_field: "gradient.midpointField" = "Midpoint";
|
||||
/// The Delete button's accessible name and tooltip: "Delete stop".
|
||||
delete: "gradient.deleteStop" = "Delete stop";
|
||||
/// The name of the selected stop's fields.
|
||||
stop_fields: "gradient.stopFields" = "Selected stop";
|
||||
/// The name of the colour popover.
|
||||
popover: "gradient.colorPopover" = "Stop color";
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ mod choice;
|
||||
mod disc;
|
||||
mod droppers;
|
||||
mod eyedropper;
|
||||
pub mod gradient;
|
||||
mod harmony;
|
||||
mod hex;
|
||||
mod lut_picker;
|
||||
|
||||
@@ -440,7 +440,11 @@ impl ScreenPick {
|
||||
}
|
||||
};
|
||||
let windows = WindowHost::of(ctx);
|
||||
let size = windows.screenshot_facts();
|
||||
// P3(canvas-widgets-w13): cw.C66 — `screenshot_facts` takes the viewport and gives `None` when it is not running.
|
||||
let Some(size) = windows.screenshot_facts(windows.current()) else {
|
||||
self.hold = None;
|
||||
return None;
|
||||
};
|
||||
let inside = at.x >= 0.0 && at.y >= 0.0 && at.x < size.size_points.x && at.y < size.size_points.y;
|
||||
let back = self.monitor.as_ref().and_then(|(_, back)| back.clone());
|
||||
let hold = self.hold.get_or_insert_with(|| Hold { owner: key, slot: None, frame: None });
|
||||
|
||||
@@ -226,7 +226,7 @@ impl From<Rgba> for Oklch {
|
||||
|
||||
/// An encoded sRGB colour with float channels in 0..=1 and straight alpha: the value a colour
|
||||
/// picker edits. Eight bits lose the precision that HSB and OKLCH edits need.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Srgba {
|
||||
/// Red, encoded.
|
||||
pub r: f32,
|
||||
|
||||
Reference in New Issue
Block a user