mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
Preset sources: the remaining framework callers, the popover replay trial and the preset count trials
ParamRows and ParamDialog take a PresetSource for their pattern rows (a hosted dialog's build gives one over owned inputs); the export and PDF export dialogs, the swatch list (swatch_source, thumbs from the drawn colours), the gradient palette and Gradient Map picker, the pattern fill editor, the text style picker (style_source) and the Layer Style dialog (patterns, style presets, contour_source) build their presets from sources. Their painters are fns: RampSampler, SwatchPainter, ContourSampler. Key types and the model types they are built from are memo props. A memoized view inside an open popover replays while nothing changes; an open preset picker runs no list row while nothing changes; a Size drag in the Brush Preset picker runs its head and replays the list. The Swatches panel's rows stay public as `swatch_rows(groups, words)`, which the source's rows fn calls.
This commit is contained in:
@@ -7,6 +7,7 @@ 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)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[non_exhaustive]
|
||||
pub enum StopRows {
|
||||
/// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is
|
||||
@@ -36,6 +37,7 @@ pub enum StopRow {
|
||||
|
||||
/// A colour stop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorStop {
|
||||
@@ -56,6 +58,7 @@ pub struct ColorStop {
|
||||
|
||||
/// An opacity stop of a [`StopRows::Split`] gradient.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct OpacityStop {
|
||||
@@ -120,6 +123,7 @@ impl OpacityStop {
|
||||
|
||||
/// A gradient's stops, each list sorted by location.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientStops {
|
||||
|
||||
@@ -97,6 +97,7 @@ impl SwatchFormat {
|
||||
|
||||
/// A swatch colour in its own model.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(tag = "model", content = "values", rename_all = "camelCase")]
|
||||
pub enum SwatchColor {
|
||||
/// Encoded RGB, 0–1 each, in the RGB working space.
|
||||
@@ -148,6 +149,7 @@ impl SwatchColor {
|
||||
|
||||
/// How an `.ase` file marks a colour.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SwatchKind {
|
||||
#[default]
|
||||
@@ -161,6 +163,7 @@ pub enum SwatchKind {
|
||||
|
||||
/// One named swatch.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct SwatchEntry {
|
||||
/// The swatch's label.
|
||||
pub name: String,
|
||||
@@ -181,6 +184,7 @@ impl SwatchEntry {
|
||||
/// A named group of swatches, as the Swatches panel shows them. A file without groups reads as
|
||||
/// one group named after the file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct SwatchGroup {
|
||||
/// The group's label.
|
||||
pub name: String,
|
||||
|
||||
@@ -87,7 +87,7 @@ pub use screen_picker::{CaptureResult, CaptureSource, LOUPE_PIXELS, LOUPE_ZOOM,
|
||||
pub use strip::{ColorStrip, ColorStripStyle};
|
||||
pub use swatches::{
|
||||
MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput,
|
||||
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows,
|
||||
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, swatch_source,
|
||||
};
|
||||
pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle};
|
||||
pub use wheel::{
|
||||
|
||||
@@ -14,14 +14,14 @@ use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey};
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace};
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch};
|
||||
use craft_ui::contract::{
|
||||
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages,
|
||||
PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo};
|
||||
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState};
|
||||
use craft_ui::primitives::textures::CachedTexture;
|
||||
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
@@ -30,7 +30,7 @@ use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx}
|
||||
use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2};
|
||||
|
||||
use super::popover::compact_picker;
|
||||
use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, SwatchesWords, swatch_rows};
|
||||
use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, swatch_source};
|
||||
use crate::palette::{SwatchColor, SwatchGroup};
|
||||
|
||||
pub(crate) mod paint_list;
|
||||
@@ -475,7 +475,6 @@ impl Component for PaintChip<'_> {
|
||||
let solid = cx.memory::<LastSolid>().0.unwrap_or(self.fallback);
|
||||
let current = FillKind::of(&paint);
|
||||
let sampled = self.sampled;
|
||||
let swatch_words = cx.words::<SwatchesWords>();
|
||||
let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let full_picker = self.full_picker;
|
||||
let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
@@ -514,21 +513,14 @@ impl Component for PaintChip<'_> {
|
||||
}
|
||||
if let Some((groups, state)) = swatches.as_mut() {
|
||||
let groups: &[SwatchGroup] = groups;
|
||||
let rows = swatch_rows(groups, &swatch_words);
|
||||
let source = swatch_source(groups, cmyk);
|
||||
let colors: HashMap<&str, &SwatchColor> =
|
||||
groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
|
||||
let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows)
|
||||
let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &source)
|
||||
.toolbar(false)
|
||||
.row_menu(false)
|
||||
.default_open(DefaultOpen::None)
|
||||
.room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS)
|
||||
.thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = colors.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect);
|
||||
}
|
||||
})
|
||||
.show(ui);
|
||||
for event in out.events {
|
||||
if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event
|
||||
|
||||
@@ -11,7 +11,7 @@ pub(crate) mod panel;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows};
|
||||
pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows, swatch_source};
|
||||
pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput};
|
||||
pub use panel::{SwatchesPanel, SwatchesPanelOutput};
|
||||
|
||||
|
||||
@@ -2,8 +2,15 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::SwatchFace;
|
||||
use craft_ui::contract::ReorderMove;
|
||||
use craft_ui::patterns::presets::{PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, PresetState, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use egui::Rect;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::{MAX_GROUPS, MAX_SWATCHES, SWATCH_ZOOM, SwatchesWords};
|
||||
use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport};
|
||||
@@ -11,7 +18,7 @@ use crate::ui::PickedColor;
|
||||
|
||||
/// What the browser names its rows by. Swatch names are unique across the library and group names among groups, so
|
||||
/// both survive reordering.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum SwatchKey {
|
||||
/// A group, by name.
|
||||
@@ -556,8 +563,27 @@ impl SwatchLibrary {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as its
|
||||
/// tooltip and accessible name. `SwatchesPanel` and `PaintChip`'s swatches list build their rows with it.
|
||||
/// The swatch list's inputs: the library's groups and each swatch's colour as drawn, by name.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct SwatchInputs<'a> {
|
||||
groups: &'a [SwatchGroup],
|
||||
drawn: BTreeMap<&'a str, Srgba>,
|
||||
}
|
||||
|
||||
/// The presets of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as
|
||||
/// its tooltip and accessible name, painted in its colour through `cmyk`. `SwatchesPanel` and `PaintChip`'s swatches
|
||||
/// list show it.
|
||||
pub fn swatch_source<'a>(groups: &'a [SwatchGroup], cmyk: &CmykConverter) -> PresetSource<'a, SwatchKey> {
|
||||
let drawn = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), e.color.to_srgb(cmyk)))).collect();
|
||||
PresetSource::new(SwatchInputs { groups, drawn }, PresetFns::new(source_rows).thumb(paint_swatch))
|
||||
}
|
||||
|
||||
fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>> {
|
||||
swatch_rows(inputs.groups, &env.words::<SwatchesWords>())
|
||||
}
|
||||
|
||||
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
|
||||
/// colour value.
|
||||
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
|
||||
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
|
||||
for group in groups {
|
||||
@@ -570,6 +596,14 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetR
|
||||
rows
|
||||
}
|
||||
|
||||
fn paint_swatch(inputs: &SwatchInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>) {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = inputs.drawn.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(*color).selected(info.selected).paint(cx, rect);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
//! `SwatchesPanel`: the panel body, its state and what it reports.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_i18n::Format;
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::bars::StatusMessage;
|
||||
use craft_ui::choice::SwatchFace;
|
||||
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _, request_rename};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords};
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use egui::{Rect, Response, Ui};
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::library::{find_swatch, has};
|
||||
use super::menu::event_edits;
|
||||
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows};
|
||||
use crate::palette::{SwatchColor, SwatchGroup, SwatchNote, SwatchReport};
|
||||
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_source};
|
||||
use crate::palette::{SwatchGroup, SwatchNote, SwatchReport};
|
||||
|
||||
/// What [`SwatchesPanel::show`] reports.
|
||||
#[derive(Debug)]
|
||||
@@ -99,21 +95,13 @@ impl<'a> SwatchesPanel<'a> {
|
||||
if st.selected.as_ref().is_some_and(|k| !has(groups, k)) {
|
||||
st.selected = None;
|
||||
}
|
||||
let rows = swatch_rows(groups, &words);
|
||||
let source = swatch_source(groups, cmyk);
|
||||
let out = {
|
||||
let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
|
||||
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows)
|
||||
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source)
|
||||
.thumb_range(SWATCH_ZOOM)
|
||||
.toolbar(true)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()))
|
||||
.thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = colors.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(cx, rect);
|
||||
}
|
||||
});
|
||||
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()));
|
||||
if let Some(key) = &st.selected {
|
||||
browser = browser.selected(key.clone());
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, Sh
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PickerField, PresetPicker, PresetRow};
|
||||
use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::style::TypeRole;
|
||||
use egui::{Response, Ui};
|
||||
@@ -136,26 +136,18 @@ impl<'a> GradientMapEditor<'a> {
|
||||
(words.preset.clone(), words.custom.clone(), words.import_presets.clone(), words.stops.clone());
|
||||
let (reverse_label, dither_label) = (words.reverse.clone(), words.dither.clone());
|
||||
let shown = Stack::new().label(self.label.clone()).show(ui, |ui, cx| {
|
||||
let rows: Vec<PresetRow<GradientRef>> = self
|
||||
.presets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(group, g)| {
|
||||
let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0);
|
||||
let items =
|
||||
g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1));
|
||||
std::iter::once(header).chain(items)
|
||||
})
|
||||
.collect();
|
||||
let source = PresetSource::new(self.presets, PresetFns::new(preset_rows));
|
||||
// Stop tags identify host data, so they do not determine which preset's colours match.
|
||||
let matches = |&key: &GradientRef| {
|
||||
self.preset_colors(key).is_some_and(|colors| colors.map(|s| s.with_tag(0)).eq(base.stops.color.iter().map(|s| s.with_tag(0))))
|
||||
};
|
||||
let preferred = cx.keep::<PickedPreset>().0.filter(matches);
|
||||
let current = preferred.or_else(|| rows.iter().map(|row| row.key).find(matches));
|
||||
let mut items =
|
||||
self.presets.iter().enumerate().flat_map(|(group, g)| (0..g.items.len()).map(move |item| GradientRef::Item { group, item }));
|
||||
let current = preferred.or_else(|| items.find(matches));
|
||||
let picked = Field::new(preset_label.clone())
|
||||
.show(ui, |ui, _| {
|
||||
PresetPicker::new(preset_label.clone(), Bind::given(current), &rows, Bind::kept())
|
||||
PresetPicker::new(preset_label.clone(), Bind::given(current), &source, Bind::kept())
|
||||
.field(PickerField::Name)
|
||||
.placeholder(custom.clone())
|
||||
.show(ui)
|
||||
@@ -200,3 +192,16 @@ impl<'a> GradientMapEditor<'a> {
|
||||
GradientMapOutput { response: shown.output, event, color_requested, import }
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker's rows: each group's header, then its presets. A header's key names no preset (`item == usize::MAX`).
|
||||
fn preset_rows(presets: &&[GradientGroup], _: &Env) -> Vec<PresetRow<GradientRef>> {
|
||||
presets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(group, g)| {
|
||||
let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0);
|
||||
let items = g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1));
|
||||
std::iter::once(header).chain(items)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -21,6 +21,6 @@ pub use fill_editor::{GradientFillEditor, GradientFillEditorOutput, GradientFill
|
||||
pub use gradient_line::{GradientLine, LineGradient, LinePart};
|
||||
pub use gradient_overlay::{GradientLineWords, GradientOverlay, GradientOverlayOutput, GradientOverlayStyle};
|
||||
pub use map::{GradientMap, GradientMapEditor, GradientMapOutput};
|
||||
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef};
|
||||
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef, RampSampler};
|
||||
pub use swatch::{GradientSwatch, GradientSwatchOutput};
|
||||
pub use tile::{FocusOutline, GradientTile};
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
//! family's [`PresetBrowser`]: the browser owns the grid, the list, the roving focus, the keys and the accessible tree;
|
||||
//! the palette supplies the rows and paints each preset's thumbnail as a gradient ramp.
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, NoValue, Outcome, Pattern};
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetRow, PresetState, PresetTiles};
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetTiles, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Response, Ui};
|
||||
use egui::{Rect, Response, Ui};
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -18,7 +20,7 @@ use super::GradientTile;
|
||||
const MAX_ROWS: f32 = 6.0;
|
||||
|
||||
/// A named group of gradient presets.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientGroup {
|
||||
/// The group's heading.
|
||||
@@ -35,7 +37,7 @@ impl GradientGroup {
|
||||
}
|
||||
|
||||
/// A named gradient preset.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientItem {
|
||||
/// The preset's name.
|
||||
@@ -62,7 +64,7 @@ impl GradientItem {
|
||||
|
||||
/// The preset a pick names: a recent gradient by its place in the list the host passed, or an
|
||||
/// item of a group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum GradientRef {
|
||||
/// Place in the Recent list.
|
||||
@@ -163,9 +165,10 @@ pub struct GradientPalette<'a> {
|
||||
/// The row layout the ramps are sampled with.
|
||||
#[prop]
|
||||
rows: StopRows,
|
||||
/// Samples a ramp; the default sampler of the rows by default.
|
||||
/// Samples a ramp; the default sampler of the rows by default. A `fn`, which captures nothing, so the palette's
|
||||
/// presets key it by its address.
|
||||
#[prop]
|
||||
sampler: Option<&'a Sampler>,
|
||||
sampler: Option<RampSampler>,
|
||||
/// The selected preset.
|
||||
#[prop]
|
||||
selected: Option<GradientRef>,
|
||||
@@ -186,55 +189,17 @@ impl<'a> GradientPalette<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the groups: the header of each group, then its presets. A header's key names no preset
|
||||
/// (`item == usize::MAX`).
|
||||
fn preset_rows(&self) -> Vec<PresetRow<GradientRef>> {
|
||||
let mut rows = Vec::new();
|
||||
if !self.recent.is_empty() {
|
||||
rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), self.recent_label.clone(), 0));
|
||||
for i in 0..self.recent.len() {
|
||||
rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", self.recent_label, i + 1), 1));
|
||||
}
|
||||
}
|
||||
for (group, g) in self.groups.iter().enumerate() {
|
||||
rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0));
|
||||
for (item, preset) in g.items.iter().enumerate() {
|
||||
rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Shows the palette across the available width.
|
||||
pub fn show(self, ui: &mut Ui) -> GradientPaletteOutput {
|
||||
let rows = self.preset_rows();
|
||||
let default = default_sampler(self.rows);
|
||||
let sampler: &Sampler = self.sampler.unwrap_or(&default);
|
||||
let (groups, recent) = (self.groups, self.recent);
|
||||
let (wide, high) = GradientRamp::CHIP_ASPECT;
|
||||
// The browser has one cell shape for the grid and the list, so any tile makes every cell square.
|
||||
let square = groups.iter().flat_map(|g| &g.items).any(|item| item.tile != GradientTile::Ramp);
|
||||
let thumb =
|
||||
move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect, info: craft_ui::patterns::presets::ThumbInfo<'_, GradientRef>| {
|
||||
if let Some(stops) = stops_of(groups, recent, *info.key) {
|
||||
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
|
||||
let tile = item_of(groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
|
||||
if tile != GradientTile::Ramp {
|
||||
tile.paint(cx, rect, radius, stops, sampler, edge);
|
||||
return;
|
||||
}
|
||||
let chip = if square {
|
||||
egui::Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
|
||||
} else {
|
||||
rect
|
||||
};
|
||||
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
|
||||
}
|
||||
};
|
||||
let inputs = PaletteInputs { groups, recent, recent_label: self.recent_label, rows: self.rows, sampler: self.sampler, square };
|
||||
let source = PresetSource::new(inputs, PresetFns::new(preset_rows).thumb(paint_thumb));
|
||||
let most = Env::of(ui).tokens.size.control.sm * MAX_ROWS;
|
||||
let shape = if square { CellShape::Square } else { CellShape::ratio(wide, high) };
|
||||
let mut browser =
|
||||
PresetBrowser::new(self.label, self.state, &rows).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most).thumb(thumb);
|
||||
let mut browser = PresetBrowser::new(self.label, self.state, &source).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most);
|
||||
if let Some(selected) = self.selected {
|
||||
browser = browser.selected(selected);
|
||||
}
|
||||
@@ -251,6 +216,64 @@ impl<'a> GradientPalette<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples a gradient's ramp at a location 0..=1.
|
||||
pub type RampSampler = fn(&GradientStops, f32) -> Srgba;
|
||||
|
||||
/// What the palette's presets are built from.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct PaletteInputs<'a> {
|
||||
groups: &'a [GradientGroup],
|
||||
recent: &'a [GradientStops],
|
||||
recent_label: String,
|
||||
rows: StopRows,
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
sampler: Option<RampSampler>,
|
||||
/// Whether every cell is square: some preset has a tile other than the ramp.
|
||||
square: bool,
|
||||
}
|
||||
|
||||
/// The rows of the groups: the header of each group, then its presets. A header's key names no preset
|
||||
/// (`item == usize::MAX`).
|
||||
fn preset_rows(inputs: &PaletteInputs<'_>, _: &Env) -> Vec<PresetRow<GradientRef>> {
|
||||
let mut rows = Vec::new();
|
||||
if !inputs.recent.is_empty() {
|
||||
rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), inputs.recent_label.clone(), 0));
|
||||
for i in 0..inputs.recent.len() {
|
||||
rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", inputs.recent_label, i + 1), 1));
|
||||
}
|
||||
}
|
||||
for (group, g) in inputs.groups.iter().enumerate() {
|
||||
rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0));
|
||||
for (item, preset) in g.items.iter().enumerate() {
|
||||
rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Paints a preset's thumbnail: its tile, or its ramp chip, which keeps the chip's aspect in a square cell.
|
||||
fn paint_thumb(inputs: &PaletteInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, GradientRef>) {
|
||||
let Some(stops) = stops_of(inputs.groups, inputs.recent, *info.key) else { return };
|
||||
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
|
||||
let default = default_sampler(inputs.rows);
|
||||
let sampler: &Sampler = match &inputs.sampler {
|
||||
Some(sampler) => sampler,
|
||||
None => &default,
|
||||
};
|
||||
let tile = item_of(inputs.groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
|
||||
if tile != GradientTile::Ramp {
|
||||
tile.paint(cx, rect, radius, stops, sampler, edge);
|
||||
return;
|
||||
}
|
||||
let (wide, high) = GradientRamp::CHIP_ASPECT;
|
||||
let chip = if inputs.square {
|
||||
Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
|
||||
} else {
|
||||
rect
|
||||
};
|
||||
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
|
||||
}
|
||||
|
||||
/// The stops of the preset `key` names; none for a group header.
|
||||
pub(super) fn stops_of<'a>(groups: &'a [GradientGroup], recent: &'a [GradientStops], key: GradientRef) -> Option<&'a GradientStops> {
|
||||
match key {
|
||||
|
||||
@@ -79,7 +79,7 @@ pub use crop::{
|
||||
pub use crop::{PerspectiveCropQuad, PerspectiveQuad};
|
||||
pub use gradient::{
|
||||
FocusOutline, GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette,
|
||||
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart,
|
||||
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart, RampSampler,
|
||||
};
|
||||
pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle};
|
||||
pub use measure::{
|
||||
|
||||
@@ -7,9 +7,8 @@ use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use egui::{Rect, Ui};
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Photoshop's Pattern Fill dialog (Layer, New Fill Layer, Pattern...; a Pattern Fill layer's thumbnail; Layer Content
|
||||
@@ -49,8 +48,8 @@ impl PatternFillDialog {
|
||||
|
||||
/// Paints a swatch's tile (see [`PatternFillEditor::thumbnails`]).
|
||||
#[must_use]
|
||||
pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
|
||||
self.thumbnails = Some(SwatchPainter::new(paint));
|
||||
pub fn thumbnails(mut self, paint: SwatchPainter) -> Self {
|
||||
self.thumbnails = Some(paint);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -160,8 +159,8 @@ impl StackDialog for PatternFillDialog {
|
||||
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
|
||||
}
|
||||
let mut editor = PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches);
|
||||
if let Some(painter) = thumbnails.clone() {
|
||||
editor = editor.thumbnails(move |cx, rect, swatch| painter.paint(cx, rect, swatch));
|
||||
if let Some(paint) = *thumbnails {
|
||||
editor = editor.thumbnails(paint);
|
||||
}
|
||||
editor.show(ui);
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ use craft_ui::contract::{Bind, FieldLayout, Outcome, Props as _, Remember as _,
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetPicker, PresetRow, PresetState, PresetView, ThumbInfo};
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, PresetView};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
use craft_ui::text::NumberField;
|
||||
@@ -21,20 +21,16 @@ use egui::{Rect, Response, Ui};
|
||||
/// The angle of the dial runs over half a turn each way.
|
||||
pub(super) const ANGLE_RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
|
||||
|
||||
type SwatchPaintFn = Arc<dyn Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync>;
|
||||
/// The host's painter of a swatch's tile. A `fn`, which captures nothing, so the presets that paint it key it by its
|
||||
/// address.
|
||||
pub type SwatchPainter = fn(&ContentPainterCx<'_>, Rect, &PatternSwatch);
|
||||
|
||||
/// The host's painter of a swatch's tile, shared with the preset rows that paint it.
|
||||
#[derive(Clone)]
|
||||
pub struct SwatchPainter(SwatchPaintFn);
|
||||
|
||||
impl SwatchPainter {
|
||||
pub(super) fn new(paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
|
||||
SwatchPainter(Arc::new(paint))
|
||||
}
|
||||
|
||||
pub(super) fn paint(&self, cx: &ContentPainterCx<'_>, rect: Rect, swatch: &PatternSwatch) {
|
||||
(self.0)(cx, rect, swatch);
|
||||
}
|
||||
/// What the editor's presets are built from.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct TileInputs<'a> {
|
||||
swatches: &'a [PatternSwatch],
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
thumbnails: Option<SwatchPainter>,
|
||||
}
|
||||
|
||||
/// What [`PatternFillEditor`] reports.
|
||||
@@ -86,8 +82,8 @@ impl<'a> PatternFillEditor<'a> {
|
||||
}
|
||||
|
||||
/// Paints a swatch's tile into a rect (the picker's field and cells, the preset grid).
|
||||
pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
|
||||
self.thumbnails = Some(SwatchPainter::new(paint));
|
||||
pub fn thumbnails(mut self, paint: SwatchPainter) -> Self {
|
||||
self.thumbnails = Some(paint);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -98,7 +94,7 @@ impl<'a> PatternFillEditor<'a> {
|
||||
let words = env.words::<PatternWords>();
|
||||
let units = env.units();
|
||||
let name: Arc<str> = label.as_str().into();
|
||||
let rows: Vec<PresetRow<String>> = swatches.iter().map(|swatch| tile_row(swatch, thumbnails.as_ref())).collect();
|
||||
let rows = PresetSource::new(TileInputs { swatches, thumbnails }, PresetFns::new(tile_rows));
|
||||
let mut events = EditEvents::new();
|
||||
let shown = FieldGroup::new(label).show(ui, |ui, cx| {
|
||||
events = EditEvents::new();
|
||||
@@ -108,20 +104,13 @@ impl<'a> PatternFillEditor<'a> {
|
||||
let mut take = |edits: EditEvents<PatternFillOptions>| next.extend(edits);
|
||||
if let Some(colors) = current.colors {
|
||||
let browser = Field::new(words.pattern.clone()).id_salt("grid").show(ui, |ui, _| {
|
||||
let thumbs = thumbnails.clone();
|
||||
let mut browser = PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
|
||||
PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
|
||||
.selected(current.pattern.clone())
|
||||
.cell_shape(CellShape::Square)
|
||||
.view_lock(PresetView::Grid)
|
||||
.row_menu(false);
|
||||
if let Some(thumbs) = thumbs {
|
||||
browser = browser.thumb(move |cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, String>| {
|
||||
if let Some(swatch) = swatches.iter().find(|swatch| swatch.id == *info.key) {
|
||||
thumbs.paint(cx, rect, swatch);
|
||||
}
|
||||
});
|
||||
}
|
||||
browser.show(ui).events
|
||||
.row_menu(false)
|
||||
.show(ui)
|
||||
.events
|
||||
});
|
||||
for picked in browser.inner.into_iter().flatten().filter_map(selected_key) {
|
||||
if picked != current.pattern {
|
||||
@@ -206,16 +195,19 @@ impl<'a> PatternFillEditor<'a> {
|
||||
/// The most decimals the Scale field shows.
|
||||
const SCALE_DECIMALS: usize = 2;
|
||||
|
||||
/// The preset row of `swatch`: its name, with the tile painter when the host gave one.
|
||||
fn tile_row(swatch: &PatternSwatch, thumbnails: Option<&SwatchPainter>) -> PresetRow<String> {
|
||||
let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0);
|
||||
match thumbnails {
|
||||
Some(painter) => {
|
||||
let (painter, swatch) = (painter.clone(), swatch.clone());
|
||||
row.preview(CellShape::Square.aspect(), move |cx, rect| painter.paint(cx, rect, &swatch))
|
||||
/// The preset row of each swatch: its name, with the tile painter when the host gave one.
|
||||
fn tile_rows(inputs: &TileInputs<'_>, _: &Env) -> Vec<PresetRow<String>> {
|
||||
let tile_row = |swatch: &PatternSwatch| {
|
||||
let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0);
|
||||
match inputs.thumbnails {
|
||||
Some(paint) => {
|
||||
let swatch = swatch.clone();
|
||||
row.preview(CellShape::Square.aspect(), move |cx, rect| paint(cx, rect, &swatch))
|
||||
}
|
||||
None => row,
|
||||
}
|
||||
None => row,
|
||||
}
|
||||
};
|
||||
inputs.swatches.iter().map(tile_row).collect()
|
||||
}
|
||||
|
||||
/// The key a browser event picked: a click or Enter on a tile.
|
||||
|
||||
@@ -17,7 +17,7 @@ pub use words::PatternWords;
|
||||
/// A pattern the editor offers: the app's pattern library (PhotoCraft's Patterns, a bitmap each)
|
||||
/// or its preset patterns (PowerPoint's "pct25", "dkHorz", …). The app paints each swatch's tile
|
||||
/// ([`PatternFillEditor::thumbnails`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct PatternSwatch {
|
||||
/// The app's id, which [`PatternFillOptions::pattern`] holds.
|
||||
|
||||
@@ -7,7 +7,8 @@ use craft_draw::ui::brush_settings::TipAngle;
|
||||
use craft_ui::contract::{Bind, Role, SaveKey};
|
||||
use craft_ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial};
|
||||
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -222,3 +223,35 @@ fn escape_reverts_size_hardness_angle_and_roundness() {
|
||||
fixture.idle(3);
|
||||
assert_eq!(host.borrow().values, OPENED, "Escape puts all four back");
|
||||
}
|
||||
|
||||
/// The memoized views of `props` that ran in the last frame.
|
||||
fn views_ran(fixture: &Fixture, props: &str) -> usize {
|
||||
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count()
|
||||
}
|
||||
|
||||
/// The memoized views of `props` that replayed in the last frame.
|
||||
fn views_replayed(fixture: &Fixture, props: &str) -> usize {
|
||||
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Replayed).count()
|
||||
}
|
||||
|
||||
/// While nothing changes the open picker's head and preset list replay; each move of a Size drag runs the head's view
|
||||
/// and replays the list.
|
||||
#[trial]
|
||||
fn a_size_drag_runs_the_head_and_replays_the_preset_list() {
|
||||
let (mut fixture, host) = opened_rig(true, false);
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!((views_ran(&fixture, "HeadProps"), views_ran(&fixture, "ListProps")), (0, 0), "an idle frame runs neither view");
|
||||
let slider = fixture.by_role(Role::SLIDER).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Size"));
|
||||
let slider = slider.expect("the Size slider shows").rect;
|
||||
let from = slider.left_center() + Vec2::new(slider.width() * 0.3, 0.0);
|
||||
fixture.frame(vec![moved(from)]);
|
||||
fixture.frame(vec![press(from)]);
|
||||
for step in 1..=4 {
|
||||
fixture.frame(vec![moved(from + Vec2::new(8.0 * step as f32, 0.0))]);
|
||||
assert!(views_ran(&fixture, "HeadProps") > 0, "move {step} runs the head");
|
||||
assert_eq!(views_ran(&fixture, "ListProps"), 0, "move {step} runs no list view");
|
||||
assert!(views_replayed(&fixture, "ListProps") > 0, "move {step} replays the list");
|
||||
}
|
||||
fixture.frame(vec![release(from + Vec2::new(32.0, 0.0))]);
|
||||
assert_ne!(host.borrow().values.diameter, OPENED.diameter, "the drag edited the size");
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
/// A contour point, input and output in 0..=1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct ContourPoint {
|
||||
/// Input value, 0..=1 (the horizontal axis).
|
||||
pub input: f32,
|
||||
@@ -15,6 +16,7 @@ pub struct ContourPoint {
|
||||
/// Built-in presets carry their preset name; an edited preset is named "Custom"; imported
|
||||
/// contours keep their own name and points.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct Contour {
|
||||
#[allow(missing_docs)]
|
||||
pub name: String,
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::Ui;
|
||||
|
||||
use super::{ContourAction, ContourRequest, ContourWords, SharedSampler, from_curve, to_curve};
|
||||
use super::{ContourAction, ContourRequest, ContourSampler, ContourWords, from_curve, to_curve};
|
||||
use crate::layer_style::Contour;
|
||||
use crate::ui::curve::CurveEditor;
|
||||
|
||||
@@ -49,7 +49,7 @@ pub struct ContourEditorDialog {
|
||||
key: String,
|
||||
initial: Contour,
|
||||
draft: Draft,
|
||||
sampler: Option<SharedSampler>,
|
||||
sampler: Option<ContourSampler>,
|
||||
changed: bool,
|
||||
action: Option<ContourAction>,
|
||||
focus_name: bool,
|
||||
@@ -72,8 +72,8 @@ impl ContourEditorDialog {
|
||||
|
||||
/// The interpolation of the points, as the engine does it. Without it the curve is a monotone cubic.
|
||||
#[must_use]
|
||||
pub fn sampler(mut self, sampler: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
|
||||
self.sampler = Some(std::sync::Arc::new(sampler));
|
||||
pub fn sampler(mut self, sampler: ContourSampler) -> Self {
|
||||
self.sampler = Some(sampler);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ impl StackDialog for ContourEditorDialog {
|
||||
let extras = [(Extra::Load, &words.load), (Extra::Save, &words.save), (Extra::New, &words.new)];
|
||||
let named = Cell::new(false);
|
||||
let focus_name = std::mem::take(&mut self.focus_name);
|
||||
let sampler = self.sampler.clone();
|
||||
let sampler = self.sampler;
|
||||
let shown = FormDialog::new(words.editor.clone(), Bind::bound(&mut self.draft))
|
||||
.outer_gesture(true)
|
||||
.history(true)
|
||||
@@ -171,8 +171,8 @@ impl StackDialog for ContourEditorDialog {
|
||||
.percent()
|
||||
.corners()
|
||||
.between(between);
|
||||
if let Some(sampler) = sampler.clone() {
|
||||
editor = editor.sampler(move |points| sampler(points));
|
||||
if let Some(sampler) = sampler {
|
||||
editor = editor.sampler(sampler);
|
||||
}
|
||||
let edit = editor.show(ui);
|
||||
if let Some(next) = edit.events.value().and_then(|curve| from_curve(curve, &draft.contour.name)) {
|
||||
|
||||
@@ -5,14 +5,12 @@ mod editor;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvents, Mixed};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, EditResponse, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::list::ThumbAspect;
|
||||
use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFooterEvent, PresetPicker, PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFns, PresetFooterEvent, PresetPicker, PresetRow, PresetSource, PresetState};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Rect, Response, Ui};
|
||||
@@ -78,14 +76,15 @@ impl ContourWords {
|
||||
}
|
||||
}
|
||||
|
||||
/// A host's interpolation of a contour's points, shared with the thumbnails' painters.
|
||||
pub(crate) type SharedSampler = Arc<dyn Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync>;
|
||||
/// A host's interpolation of a contour's points (levels in, levels out), shared with the thumbnails' painters. A `fn`,
|
||||
/// which captures nothing, so the contour presets key it by its address.
|
||||
pub type ContourSampler = fn(&[[f32; 2]]) -> Vec<f32>;
|
||||
|
||||
/// The levels of a contour as a curve: input and output run `0..=255`.
|
||||
const LEVELS: f32 = 255.0;
|
||||
|
||||
/// A contour a picker lists: one of the built-in contours or one of the user's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum ContourKey {
|
||||
/// The built-in contour at this place of [`Contour::presets`].
|
||||
@@ -153,24 +152,39 @@ impl Outcome for ContourFieldOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the contour picker: the built-in contours, then the user's, named by `words`, with a thumbnail of each
|
||||
/// curve. `sampler` interpolates the points as the engine does; without it the thumbnails use a monotone cubic.
|
||||
pub fn contour_rows(presets: &[Contour], user: &[Contour], words: &ContourWords, sampler: Option<SharedSampler>) -> Vec<PresetRow<ContourKey>> {
|
||||
/// What the contour presets are built from.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct ContourInputs<'a> {
|
||||
presets: &'a [Contour],
|
||||
user: &'a [Contour],
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
sampler: Option<ContourSampler>,
|
||||
}
|
||||
|
||||
/// The presets of the contour picker: the built-in contours, then the user's, with a thumbnail of each curve; the
|
||||
/// user's may be deleted. `sampler` interpolates the points as the engine does; without it the thumbnails use a
|
||||
/// monotone cubic.
|
||||
pub fn contour_source<'a>(presets: &'a [Contour], user: &'a [Contour], sampler: Option<ContourSampler>) -> PresetSource<'a, ContourKey> {
|
||||
let fns = PresetFns::new(contour_rows).can_delete(|_, key| matches!(key, ContourKey::User(_)));
|
||||
PresetSource::new(ContourInputs { presets, user, sampler }, fns)
|
||||
}
|
||||
|
||||
/// The rows of the contour picker, named by the scope's words.
|
||||
fn contour_rows(inputs: &ContourInputs<'_>, env: &Env) -> Vec<PresetRow<ContourKey>> {
|
||||
let words = env.words::<ContourWords>();
|
||||
let sampler = inputs.sampler;
|
||||
let row = |key: ContourKey, contour: &Contour| {
|
||||
let name = words.contour_name(&contour.name).to_owned();
|
||||
let curve = Arc::new(to_curve(contour));
|
||||
let sampler = sampler.clone();
|
||||
PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler.as_deref()))
|
||||
let curve = to_curve(contour);
|
||||
PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler))
|
||||
};
|
||||
let presets = presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour));
|
||||
let user = user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour));
|
||||
let presets = inputs.presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour));
|
||||
let user = inputs.user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour));
|
||||
presets.chain(user).collect()
|
||||
}
|
||||
|
||||
type SamplerFn = dyn Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync;
|
||||
|
||||
/// A thumbnail of a contour: its curve in the curve preview's look (plot, quarter grid, diagonal).
|
||||
fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<&SamplerFn>) {
|
||||
fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<ContourSampler>) {
|
||||
let Curve::Points { points, corners } = curve else { return };
|
||||
let outputs = Curve::through(points, corners, |points| match sampler {
|
||||
Some(sampler) => sampler(points),
|
||||
@@ -206,21 +220,22 @@ pub fn from_curve(curve: &Curve, name: &str) -> Option<Contour> {
|
||||
pub struct ContourField<'a> {
|
||||
label: Label,
|
||||
contour: Bind<'a, Contour>,
|
||||
rows: &'a [PresetRow<ContourKey>],
|
||||
source: &'a PresetSource<'a, ContourKey>,
|
||||
state: Bind<'a, PresetState<ContourKey>>,
|
||||
user: &'a [Contour],
|
||||
anti_alias: Option<Bind<'a, Option<bool>>>,
|
||||
}
|
||||
|
||||
impl<'a> ContourField<'a> {
|
||||
/// A field named `label` over `contour`, choosing among `rows` ([`contour_rows`]); `state` is the browser's view.
|
||||
/// A field named `label` over `contour`, choosing among `source` ([`contour_source`]); `state` is the browser's
|
||||
/// view.
|
||||
pub fn new(
|
||||
label: impl Into<Label>,
|
||||
contour: Bind<'a, Contour>,
|
||||
rows: &'a [PresetRow<ContourKey>],
|
||||
source: &'a PresetSource<'a, ContourKey>,
|
||||
state: Bind<'a, PresetState<ContourKey>>,
|
||||
) -> Self {
|
||||
Self { label: label.into(), contour, rows, state, user: &[], anti_alias: None }
|
||||
Self { label: label.into(), contour, source, state, user: &[], anti_alias: None }
|
||||
}
|
||||
|
||||
/// The user's contours, the targets of [`ContourKey::User`].
|
||||
@@ -237,7 +252,7 @@ impl<'a> ContourField<'a> {
|
||||
|
||||
/// Shows the field and returns this pass's edit and requests.
|
||||
pub fn show(self, ui: &mut Ui) -> ContourFieldOutput {
|
||||
let Self { label, mut contour, rows, mut state, user, mut anti_alias } = self;
|
||||
let Self { label, mut contour, source, mut state, user, mut anti_alias } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ContourWords>();
|
||||
let presets = Contour::presets();
|
||||
@@ -254,10 +269,9 @@ impl<'a> ContourField<'a> {
|
||||
let mut anti_events = EditEvents::new();
|
||||
let mut picked = None;
|
||||
Row::new().show(ui, |ui, root| {
|
||||
let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), rows, state.reborrowed())
|
||||
let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), source, state.reborrowed())
|
||||
.field(PickerField::Thumbnail)
|
||||
.columns(4)
|
||||
.can_delete(|key| matches!(key, ContourKey::User(_)))
|
||||
.edit_face()
|
||||
.show(ui);
|
||||
for event in &picker.events {
|
||||
|
||||
@@ -3,11 +3,10 @@
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::patterns::presets::PresetState;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{ContourField, ContourKey, ContourWords, contour_rows};
|
||||
use super::{ContourField, ContourKey, contour_source};
|
||||
use crate::layer_style::{Contour, ContourPoint};
|
||||
|
||||
fn user_contours() -> Vec<Contour> {
|
||||
@@ -18,9 +17,9 @@ fn user_contours() -> Vec<Contour> {
|
||||
/// The field over `start` with its Anti-aliased check box, in the host's Field, and the contour it holds as the
|
||||
/// readout.
|
||||
fn field(ui: &mut Ui, data: &mut StoryData, start: Contour, anti_alias: bool) -> StoryOutput {
|
||||
let words = Env::of(ui).words::<ContourWords>();
|
||||
let user = user_contours();
|
||||
let rows = contour_rows(&Contour::presets(), &user, &words, None);
|
||||
let presets = Contour::presets();
|
||||
let rows = contour_source(&presets, &user, None);
|
||||
let ((contour, state, anti_alias), field_at) = data.value_at("field", (start, PresetState::<ContourKey>::new(), Some(anti_alias)));
|
||||
let shown = Field::new("Contour").show(ui, |ui, _| {
|
||||
ContourField::new("Contour", field_at.bind(&mut *contour), &rows, field_at.bind(&mut *state))
|
||||
|
||||
@@ -8,18 +8,17 @@ use craft_theme::{Srgba, TypeRole};
|
||||
use craft_ui::contract::{CommandSet as _, Entry, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::{Divider, Text};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetSource};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::blending::{BlendingInput, blending_page};
|
||||
use super::contour::SharedSampler;
|
||||
use super::contour::{ContourAction, ContourRequest, ContourWords};
|
||||
use super::contour::{ContourAction, ContourRequest, ContourSampler};
|
||||
use super::labels::LayerStyleWords;
|
||||
use super::list::{LayerStyleCommand, ListAction, effect_list};
|
||||
use super::page::{PageInput, StyleOp, effect_page, push_edit, set_edit};
|
||||
use super::styles::{StylePresets, styles_page};
|
||||
use super::styles::styles_page;
|
||||
use craft_behavior::EditEvents;
|
||||
|
||||
use crate::layer_style::{Contour, EffectId, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue};
|
||||
@@ -102,8 +101,8 @@ impl LayerStyleOutput {
|
||||
/// before the page changes.
|
||||
/// - The page title is the effect's name, plain. New Style… and the Preview check box are the host's, in the button
|
||||
/// column under OK and Cancel (Photoshop's place), the check over [`LayerStyleDraft::preview`].
|
||||
/// - The Styles page ([`StylePresets`]), the Blending Options page, or an effect page drawn from the kind's
|
||||
/// [`EffectSpec`].
|
||||
/// - The Styles page ([`style_presets`](Self::style_presets)), the Blending Options page, or an effect page drawn from
|
||||
/// the kind's [`EffectSpec`].
|
||||
/// - Use Global Light: on an effect that uses it, the Angle edits the shared light angle of every such effect
|
||||
/// ([`LayerStyleDraft::set_param`]).
|
||||
///
|
||||
@@ -123,10 +122,10 @@ pub struct LayerStyleDialog<'a> {
|
||||
specs: Option<&'a [EffectSpec]>,
|
||||
blend_keys: Option<&'a HashMap<String, String>>,
|
||||
blend_modes: &'a [Entry<String>],
|
||||
patterns: &'a [PresetRow<String>],
|
||||
patterns: Option<&'a PresetSource<'a, String>>,
|
||||
user_contours: &'a [Contour],
|
||||
sampler: Option<SharedSampler>,
|
||||
style_presets: Option<StylePresets<'a>>,
|
||||
sampler: Option<ContourSampler>,
|
||||
style_presets: Option<&'a PresetSource<'a, String>>,
|
||||
gradient_presets: &'a [(String, GradientStops)],
|
||||
}
|
||||
|
||||
@@ -141,7 +140,7 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
specs: None,
|
||||
blend_keys: None,
|
||||
blend_modes: &[],
|
||||
patterns: &[],
|
||||
patterns: None,
|
||||
user_contours: &[],
|
||||
sampler: None,
|
||||
style_presets: None,
|
||||
@@ -177,8 +176,8 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
}
|
||||
|
||||
/// The patterns Pattern Overlay offers, keyed by the pattern's key.
|
||||
pub fn patterns(mut self, patterns: &'a [PresetRow<String>]) -> Self {
|
||||
self.patterns = patterns;
|
||||
pub fn patterns(mut self, patterns: &'a PresetSource<'a, String>) -> Self {
|
||||
self.patterns = Some(patterns);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -190,19 +189,14 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
|
||||
/// The host's interpolation of a contour's points: the output of every input level through the points, so the
|
||||
/// contour fields draw the curve the engine renders; a monotone cubic by default.
|
||||
pub fn sampler(mut self, sample: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
|
||||
self.sampler = Some(std::sync::Arc::new(sample));
|
||||
pub fn sampler(mut self, sample: ContourSampler) -> Self {
|
||||
self.sampler = Some(sample);
|
||||
self
|
||||
}
|
||||
|
||||
/// [`sampler`](Self::sampler) as the host keeps it: `None` for the default.
|
||||
pub(super) fn shared_sampler(mut self, sampler: Option<SharedSampler>) -> Self {
|
||||
self.sampler = sampler;
|
||||
self
|
||||
}
|
||||
|
||||
/// The Styles page's presets; without them the page shows only its title.
|
||||
pub fn style_presets(mut self, presets: StylePresets<'a>) -> Self {
|
||||
/// The Styles page's presets, keyed by the preset's name and painted by the source's thumbnail painter; without
|
||||
/// them the page shows only its title.
|
||||
pub fn style_presets(mut self, presets: &'a PresetSource<'a, String>) -> Self {
|
||||
self.style_presets = Some(presets);
|
||||
self
|
||||
}
|
||||
@@ -225,7 +219,6 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<LayerStyleWords>();
|
||||
let contour_words = env.words::<ContourWords>();
|
||||
let units = env.units();
|
||||
let base: Cow<'_, [EffectSpec]> = match specs {
|
||||
Some(specs) => Cow::Borrowed(specs),
|
||||
@@ -239,6 +232,8 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
}
|
||||
None => &base,
|
||||
};
|
||||
let none = PresetSource::new((), PresetFns::new(|_, _| Vec::new()));
|
||||
let patterns = patterns.unwrap_or(&none);
|
||||
let mut work = Work { next: draft.clone(), edit: EditEvents::new(), extras: Extras::default() };
|
||||
let title = page_title(draft.page, draft, &words);
|
||||
let name = label.as_str().to_owned();
|
||||
@@ -255,14 +250,13 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
blend_modes,
|
||||
patterns,
|
||||
user_contours,
|
||||
sampler: sampler.as_ref(),
|
||||
sampler,
|
||||
gradient_presets,
|
||||
channel_names,
|
||||
words: &words,
|
||||
contour_words: &contour_words,
|
||||
units: &units,
|
||||
};
|
||||
work.page(ui, &page, style_presets.as_ref());
|
||||
work.page(ui, &page, style_presets);
|
||||
});
|
||||
});
|
||||
let Work { next, edit, extras } = work;
|
||||
@@ -333,13 +327,12 @@ struct PageEnv<'a> {
|
||||
draft: &'a LayerStyleDraft,
|
||||
specs: &'a [EffectSpec],
|
||||
blend_modes: &'a [Entry<String>],
|
||||
patterns: &'a [PresetRow<String>],
|
||||
patterns: &'a PresetSource<'a, String>,
|
||||
user_contours: &'a [Contour],
|
||||
sampler: Option<&'a SharedSampler>,
|
||||
sampler: Option<ContourSampler>,
|
||||
gradient_presets: &'a [(String, GradientStops)],
|
||||
channel_names: &'a [String],
|
||||
words: &'a LayerStyleWords,
|
||||
contour_words: &'a ContourWords,
|
||||
units: &'a craft_ui::runtime::env::Units,
|
||||
}
|
||||
|
||||
@@ -389,7 +382,7 @@ impl Work {
|
||||
}
|
||||
|
||||
/// Draws the page of the pass; its controls add their edits to the pass's.
|
||||
fn page(&mut self, ui: &mut Ui, env: &PageEnv<'_>, presets: Option<&StylePresets<'_>>) {
|
||||
fn page(&mut self, ui: &mut Ui, env: &PageEnv<'_>, presets: Option<&PresetSource<'_, String>>) {
|
||||
let (words, draft) = (env.words, env.draft);
|
||||
let instance = match draft.page {
|
||||
LayerStylePage::Effect(id) => draft.style.effect(id).cloned(),
|
||||
@@ -423,7 +416,6 @@ impl Work {
|
||||
sampler: env.sampler,
|
||||
gradient_presets: env.gradient_presets,
|
||||
words,
|
||||
contour_words: env.contour_words,
|
||||
units: env.units,
|
||||
};
|
||||
let out = effect_page(ui, &input);
|
||||
|
||||
@@ -12,7 +12,7 @@ use craft_ui::contract::{
|
||||
};
|
||||
use craft_ui::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
use craft_ui::patterns::presets::{PresetRow, ThumbInfo};
|
||||
use craft_ui::patterns::presets::PresetSource;
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
@@ -20,9 +20,9 @@ use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use egui::{Context, Rect, Response, Ui, Vec2};
|
||||
|
||||
use super::contour::SharedSampler;
|
||||
use super::contour::ContourSampler;
|
||||
use super::labels::LayerStyleWords;
|
||||
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput, StylePresets};
|
||||
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput};
|
||||
use crate::layer_style::{
|
||||
Contour, EffectId, EffectKind, EffectSpec, FieldKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue,
|
||||
};
|
||||
@@ -66,9 +66,6 @@ impl LayerStyleOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints a style preset's thumbnail.
|
||||
type Thumb = dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send;
|
||||
|
||||
/// Paints the preview swatch beside the footer buttons from the draft.
|
||||
type PreviewPaint = dyn Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync;
|
||||
|
||||
@@ -158,10 +155,10 @@ pub struct HostedLayerStyle {
|
||||
specs: Option<Vec<EffectSpec>>,
|
||||
blend_keys: Option<HashMap<String, String>>,
|
||||
blend_modes: Vec<Entry<String>>,
|
||||
patterns: Vec<PresetRow<String>>,
|
||||
patterns: Option<PresetSource<'static, String>>,
|
||||
user_contours: Vec<Contour>,
|
||||
sampler: Option<SharedSampler>,
|
||||
styles: Option<(Vec<PresetRow<String>>, Box<Thumb>)>,
|
||||
sampler: Option<ContourSampler>,
|
||||
styles: Option<PresetSource<'static, String>>,
|
||||
gradient_presets: Vec<(String, GradientStops)>,
|
||||
canvas: Option<egui::Id>,
|
||||
preview_thumb: Option<Arc<PreviewPaint>>,
|
||||
@@ -187,7 +184,7 @@ impl HostedLayerStyle {
|
||||
specs: None,
|
||||
blend_keys: None,
|
||||
blend_modes: Vec::new(),
|
||||
patterns: Vec::new(),
|
||||
patterns: None,
|
||||
user_contours: Vec::new(),
|
||||
sampler: None,
|
||||
styles: None,
|
||||
@@ -224,8 +221,8 @@ impl HostedLayerStyle {
|
||||
|
||||
/// [`LayerStyleDialog::patterns`].
|
||||
#[must_use]
|
||||
pub fn patterns(mut self, patterns: Vec<PresetRow<String>>) -> Self {
|
||||
self.patterns = patterns;
|
||||
pub fn patterns(mut self, patterns: PresetSource<'static, String>) -> Self {
|
||||
self.patterns = Some(patterns);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -238,19 +235,15 @@ impl HostedLayerStyle {
|
||||
|
||||
/// [`LayerStyleDialog::sampler`].
|
||||
#[must_use]
|
||||
pub fn sampler(mut self, sample: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
|
||||
self.sampler = Some(std::sync::Arc::new(sample));
|
||||
pub fn sampler(mut self, sample: ContourSampler) -> Self {
|
||||
self.sampler = Some(sample);
|
||||
self
|
||||
}
|
||||
|
||||
/// The Styles page's presets `rows`, each thumbnail painted by `thumb` ([`StylePresets::new`]).
|
||||
/// [`LayerStyleDialog::style_presets`].
|
||||
#[must_use]
|
||||
pub fn style_presets(
|
||||
mut self,
|
||||
rows: Vec<PresetRow<String>>,
|
||||
thumb: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send + 'static,
|
||||
) -> Self {
|
||||
self.styles = Some((rows, Box::new(thumb)));
|
||||
pub fn style_presets(mut self, presets: PresetSource<'static, String>) -> Self {
|
||||
self.styles = Some(presets);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -379,18 +372,22 @@ impl StackDialog for HostedLayerStyle {
|
||||
}
|
||||
let mut body = LayerStyleDialog::new(label.clone(), draft, channel_names.as_slice())
|
||||
.blend_modes(blend_modes.as_slice())
|
||||
.patterns(patterns.as_slice())
|
||||
.user_contours(user_contours.as_slice())
|
||||
.shared_sampler(sampler.clone())
|
||||
.gradient_presets(gradient_presets.as_slice());
|
||||
if let Some(patterns) = patterns.as_ref() {
|
||||
body = body.patterns(patterns);
|
||||
}
|
||||
if let Some(sampler) = *sampler {
|
||||
body = body.sampler(sampler);
|
||||
}
|
||||
if let Some(specs) = specs.as_deref() {
|
||||
body = body.specs(specs);
|
||||
}
|
||||
if let Some(map) = blend_keys.as_ref() {
|
||||
body = body.blend_keys(map);
|
||||
}
|
||||
if let Some((rows, thumb)) = styles.as_ref() {
|
||||
body = body.style_presets(StylePresets::new(rows, |cx, rect, info| thumb(cx, rect, info)));
|
||||
if let Some(presets) = styles.as_ref() {
|
||||
body = body.style_presets(presets);
|
||||
}
|
||||
let out = body.show(ui);
|
||||
#[cfg(feature = "screen-testing")]
|
||||
|
||||
@@ -36,13 +36,12 @@ mod styles;
|
||||
|
||||
pub use blend_if::{BlendIfBar, BlendIfWords};
|
||||
pub use contour::{
|
||||
ContourAction, ContourEditorDialog, ContourField, ContourFieldOutput, ContourKey, ContourRequest, ContourWords, contour_rows, from_curve,
|
||||
to_curve,
|
||||
ContourAction, ContourEditorDialog, ContourField, ContourFieldOutput, ContourKey, ContourRequest, ContourSampler, ContourWords, contour_source,
|
||||
from_curve, to_curve,
|
||||
};
|
||||
pub use dialog::{LayerStyleDialog, LayerStyleOutput};
|
||||
pub use hosted::{HostedLayerStyle, LayerStyleAsk};
|
||||
pub use labels::LayerStyleWords;
|
||||
pub use list::LayerStyleCommand;
|
||||
pub use styles::StylePresets;
|
||||
|
||||
pub use crate::layer_style::LayerStylePage;
|
||||
|
||||
@@ -12,16 +12,16 @@ use craft_ui::display::Text;
|
||||
use craft_ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::patterns::presets::{PresetPicker, PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PresetPicker, PresetSource, PresetState};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Label, UnitKind, Units};
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind, Units};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::text::NumberField;
|
||||
use craft_ui::value_drag::AngleDial;
|
||||
use egui::Ui;
|
||||
|
||||
use super::blending::BlendingOp;
|
||||
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourWords, SharedSampler, contour_rows};
|
||||
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourSampler, contour_source};
|
||||
use super::labels::LayerStyleWords;
|
||||
use crate::layer_style::{
|
||||
Contour, EffectField, EffectId, EffectInstance, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, StyleParams,
|
||||
@@ -86,12 +86,11 @@ pub(super) struct PageInput<'a> {
|
||||
pub instance: &'a EffectInstance,
|
||||
pub style: &'a LayerStyle,
|
||||
pub blend_modes: &'a [Entry<String>],
|
||||
pub patterns: &'a [PresetRow<String>],
|
||||
pub patterns: &'a PresetSource<'a, String>,
|
||||
pub user_contours: &'a [Contour],
|
||||
pub sampler: Option<&'a SharedSampler>,
|
||||
pub sampler: Option<ContourSampler>,
|
||||
pub gradient_presets: &'a [(String, GradientStops)],
|
||||
pub words: &'a LayerStyleWords,
|
||||
pub contour_words: &'a ContourWords,
|
||||
pub units: &'a Units,
|
||||
}
|
||||
|
||||
@@ -329,7 +328,7 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
|
||||
}
|
||||
FieldKind::Pattern => {
|
||||
let stored = text_of(shown.get(key)).filter(|t| !t.is_empty());
|
||||
let first = input.patterns.iter().find(|row| !row.is_group()).map(|row| row.key.clone());
|
||||
let first = input.patterns.rows(ui.ctx(), &Env::of(ui)).iter().find(|row| !row.is_group()).map(|row| row.key.clone());
|
||||
let current = stored.map(str::to_owned).or(first.clone());
|
||||
let picker = Field::new(label.clone())
|
||||
.id_salt(key)
|
||||
@@ -351,7 +350,7 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
|
||||
let before = anti_alias.as_deref().map(|k| shown.bool(k).unwrap_or(false));
|
||||
let mut checked = before;
|
||||
let presets = Contour::presets();
|
||||
let rows = contour_rows(&presets, input.user_contours, input.contour_words, input.sampler.cloned());
|
||||
let rows = contour_source(&presets, input.user_contours, input.sampler);
|
||||
// A field with no visible label (Emboss's contour under its check box) is still named for assistive tech.
|
||||
let name = if label.as_str().is_empty() {
|
||||
words.field("contour").cloned().unwrap_or_else(|| Label::from(field.key.to_string()))
|
||||
|
||||
@@ -7,10 +7,11 @@ use craft_theme::Srgba;
|
||||
use craft_ui::contract::Entry;
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut, blend_entries};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
use egui::{Rect, Ui};
|
||||
|
||||
use super::{HostedLayerStyle, LayerStyleDialog};
|
||||
use crate::layer_style::{BlendIf, Blending, EffectId, EffectInstance, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage};
|
||||
@@ -71,7 +72,8 @@ fn gradient_presets(words: &LayerStyleStoryWords) -> Vec<(String, GradientStops)
|
||||
]
|
||||
}
|
||||
|
||||
fn patterns(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
fn pattern_rows(_: &(), env: &Env) -> Vec<PresetRow<String>> {
|
||||
let words = env.words::<LayerStyleStoryWords>();
|
||||
vec![
|
||||
PresetRow::group("group".to_owned(), words.pattern_group.as_str(), 0),
|
||||
PresetRow::item("bubbles".to_owned(), words.pattern_bubbles.as_str(), 1),
|
||||
@@ -79,7 +81,8 @@ fn patterns(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
]
|
||||
}
|
||||
|
||||
fn style_rows(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
fn style_rows(_: &(), env: &Env) -> Vec<PresetRow<String>> {
|
||||
let words = env.words::<LayerStyleStoryWords>();
|
||||
vec![
|
||||
PresetRow::group("group".to_owned(), words.style_group.as_str(), 0),
|
||||
PresetRow::item("Soft".to_owned(), words.style_soft.as_str(), 1),
|
||||
@@ -87,6 +90,11 @@ fn style_rows(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The Styles page's fake thumbnails.
|
||||
fn checker(_: &(), cx: &ContentPainterCx<'_>, rect: Rect, _: ThumbInfo<'_, String>) {
|
||||
cx.checker(rect);
|
||||
}
|
||||
|
||||
/// A style with one instance of each of `kinds`, turned on, in `kinds` order.
|
||||
fn style_of(kinds: &[EffectKind]) -> LayerStyle {
|
||||
let effects = kinds
|
||||
@@ -105,9 +113,9 @@ fn host(ui: &mut Ui, data: &mut StoryData, start: impl FnOnce() -> LayerStyleDra
|
||||
hosted(ui, data, (), || {
|
||||
HostedLayerStyle::new("Layer Style", start(), names)
|
||||
.blend_modes(blend_modes(&words))
|
||||
.patterns(patterns(&words))
|
||||
.patterns(PresetSource::new((), PresetFns::new(pattern_rows)))
|
||||
.gradient_presets(gradient_presets(&words))
|
||||
.style_presets(style_rows(&words), |cx, rect, _| cx.checker(rect))
|
||||
.style_presets(PresetSource::new((), PresetFns::new(style_rows).thumb(checker)))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
use craft_theme::TypeRole;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use egui::{Rect, Ui};
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetSource, PresetState};
|
||||
use egui::Ui;
|
||||
|
||||
use super::labels::LayerStyleWords;
|
||||
|
||||
@@ -13,23 +12,6 @@ use super::labels::LayerStyleWords;
|
||||
/// dialog page around it scrolls too.
|
||||
const STYLE_ROWS: u16 = 5;
|
||||
|
||||
/// The host's style presets for the Styles page: the rows (groups and presets keyed by the preset's name) and the
|
||||
/// painter of one preset's thumbnail. The page shows them in the library [`PresetBrowser`] grid and keeps the
|
||||
/// browser's view state itself.
|
||||
pub struct StylePresets<'a> {
|
||||
pub(super) rows: &'a [PresetRow<String>],
|
||||
pub(super) thumb: Thumb<'a>,
|
||||
}
|
||||
|
||||
type Thumb<'a> = Box<dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + 'a>;
|
||||
|
||||
impl<'a> StylePresets<'a> {
|
||||
/// The presets `rows`, each thumbnail painted by `thumb`.
|
||||
pub fn new(rows: &'a [PresetRow<String>], thumb: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + 'a) -> Self {
|
||||
StylePresets { rows, thumb: Box::new(thumb) }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Styles page asked for.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct StylesOutput {
|
||||
@@ -39,15 +21,13 @@ pub(super) struct StylesOutput {
|
||||
pub apply_style: Option<String>,
|
||||
}
|
||||
|
||||
/// Draws the page: the title, then the browser. Without presets the page shows only the title.
|
||||
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&StylePresets<'_>>, words: &LayerStyleWords) -> StylesOutput {
|
||||
/// Draws the page: the title, then the host's style presets (groups and presets keyed by the preset's name) in the
|
||||
/// library browser grid, whose view state the page keeps. Without presets the page shows only the title.
|
||||
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&PresetSource<'_, String>>, words: &LayerStyleWords) -> StylesOutput {
|
||||
Text::new(words.styles.clone()).role(TypeRole::Title).show(ui);
|
||||
let mut out = StylesOutput { apply_style: None };
|
||||
if let Some(StylePresets { rows, thumb }) = presets {
|
||||
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), rows)
|
||||
.thumb(move |cx, rect, info| thumb(cx, rect, info))
|
||||
.row_menu(false)
|
||||
.max_rows(STYLE_ROWS);
|
||||
if let Some(presets) = presets {
|
||||
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), presets).row_menu(false).max_rows(STYLE_ROWS);
|
||||
for event in browser.show(ui).events {
|
||||
if let PresetEvent::Select { key, .. } | PresetEvent::Activate { key, .. } = event {
|
||||
out.apply_style = Some(key);
|
||||
|
||||
@@ -86,7 +86,7 @@ pub use histogram::{
|
||||
};
|
||||
pub use layer_style::{
|
||||
BlendIfBar, BlendIfWords, ContourField, ContourFieldOutput, ContourWords, HostedLayerStyle, LayerStyleAsk, LayerStyleDialog, LayerStyleOutput,
|
||||
LayerStyleWords, StylePresets,
|
||||
LayerStyleWords,
|
||||
};
|
||||
pub use liquify::{
|
||||
LiquifyCommands, LiquifyDone, LiquifyEvent, LiquifyOpen, LiquifyPanel, LiquifyPanelOutput, LiquifySession, LiquifySettings, LiquifySource,
|
||||
|
||||
@@ -4,10 +4,9 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_imaging::layer_style::Contour;
|
||||
use craft_imaging::ui::layer_style::{ContourField, ContourKey, ContourRequest, ContourWords, contour_rows};
|
||||
use craft_imaging::ui::layer_style::{ContourField, ContourKey, ContourRequest, contour_source};
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_ui::patterns::presets::PresetState;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, pos2};
|
||||
|
||||
@@ -18,8 +17,8 @@ fn rig() -> (Fixture, Rc<RefCell<Vec<ContourRequest>>>) {
|
||||
let mut contour = Contour::linear();
|
||||
let mut state = PresetState::<ContourKey>::new();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let words = Env::of(ui).words::<ContourWords>();
|
||||
let rows = contour_rows(&Contour::presets(), &[], &words, None);
|
||||
let presets = Contour::presets();
|
||||
let rows = contour_source(&presets, &[], None);
|
||||
let out = ContourField::new("Contour", Bind::bound(&mut contour), &rows, Bind::bound(&mut state)).show(ui);
|
||||
seen.borrow_mut().extend(out.edit_contour);
|
||||
});
|
||||
|
||||
@@ -10,9 +10,9 @@ use craft_imaging::layer_style::{
|
||||
EffectField, EffectId, EffectInstance, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams,
|
||||
StyleValue,
|
||||
};
|
||||
use craft_imaging::ui::layer_style::{LayerStyleDialog, StylePresets};
|
||||
use craft_imaging::ui::layer_style::LayerStyleDialog;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::testing::access::{NodeKey, name};
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, Target, trial};
|
||||
@@ -26,7 +26,6 @@ struct Host {
|
||||
draft: LayerStyleDraft,
|
||||
specs: Vec<EffectSpec>,
|
||||
channels: Vec<String>,
|
||||
patterns: Vec<PresetRow<String>>,
|
||||
edits: Vec<EditEvent<LayerStyle>>,
|
||||
made: Vec<StyleParams>,
|
||||
}
|
||||
@@ -40,26 +39,24 @@ fn instance(id: u32, kind: EffectKind, on: bool) -> EffectInstance {
|
||||
}
|
||||
|
||||
fn host(draft: LayerStyleDraft, specs: Vec<EffectSpec>) -> Host {
|
||||
Host { draft, specs, channels: ["R", "G", "B"].map(String::from).to_vec(), patterns: Vec::new(), edits: Vec::new(), made: Vec::new() }
|
||||
Host { draft, specs, channels: ["R", "G", "B"].map(String::from).to_vec(), edits: Vec::new(), made: Vec::new() }
|
||||
}
|
||||
|
||||
fn rig_of(host: Host) -> (Fixture, Rc<RefCell<Host>>) {
|
||||
let host = Rc::new(RefCell::new(host));
|
||||
let shown = host.clone();
|
||||
let rows = vec![
|
||||
PresetRow::group("g".to_owned(), "Basics", 0),
|
||||
PresetRow::item("Soft".to_owned(), "Soft", 1),
|
||||
PresetRow::item("Hard".to_owned(), "Hard", 1),
|
||||
];
|
||||
let rows = |_: &(), _: &_| {
|
||||
vec![
|
||||
PresetRow::group("g".to_owned(), "Basics", 0),
|
||||
PresetRow::item("Soft".to_owned(), "Soft", 1),
|
||||
PresetRow::item("Hard".to_owned(), "Hard", 1),
|
||||
]
|
||||
};
|
||||
let presets = PresetSource::new((), PresetFns::new(rows).thumb(|_, cx, rect, _| cx.checker(rect)));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut guard = shown.borrow_mut();
|
||||
let host = &mut *guard;
|
||||
let presets = StylePresets::new(&rows, |cx, rect, _| cx.checker(rect));
|
||||
let out = LayerStyleDialog::new("Layer Style", &host.draft, &host.channels)
|
||||
.specs(&host.specs)
|
||||
.patterns(&host.patterns)
|
||||
.style_presets(presets)
|
||||
.show(ui);
|
||||
let out = LayerStyleDialog::new("Layer Style", &host.draft, &host.channels).specs(&host.specs).style_presets(&presets).show(ui);
|
||||
out.apply_view(&mut host.draft);
|
||||
for event in out.edit {
|
||||
if let Some(value) = event.value() {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod picker;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
pub use picker::{NamedStyleRow, StylePreview, style_rows};
|
||||
pub use picker::{NamedStyleRow, StylePreview, style_source};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The panels' words, English by default.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! The rows of the style picker: the document's named styles as the rows of a `PresetPicker`.
|
||||
//! The presets of the style picker: the document's named styles as the source of a `PresetPicker`.
|
||||
|
||||
use crate::styles::{group_by_folder, style_leaf};
|
||||
use craft_behavior::IconId;
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::patterns::presets::{PresetKey, PresetRow};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetKey, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::style::TypeRole;
|
||||
|
||||
/// What a style row shows before its name.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum StylePreview {
|
||||
/// A swatch (colour and fill styles).
|
||||
@@ -25,7 +26,7 @@ pub enum StylePreview {
|
||||
}
|
||||
|
||||
/// One style in the picker; its folder is the name's ([`crate::styles::style_folder`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct NamedStyleRow {
|
||||
/// The style's id.
|
||||
@@ -59,11 +60,15 @@ impl NamedStyleRow {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker's rows: styles with no folder first, then each folder as a group row over its styles, in order of
|
||||
/// The picker's presets: styles with no folder first, then each folder as a group row over its styles, in order of
|
||||
/// first appearance. A style's key is `PresetKey::Item(id)`.
|
||||
pub fn style_rows(styles: &[NamedStyleRow]) -> Vec<PresetRow<PresetKey<u64>>> {
|
||||
pub fn style_source(styles: &[NamedStyleRow]) -> PresetSource<'_, PresetKey<u64>> {
|
||||
PresetSource::new(styles, PresetFns::new(style_rows))
|
||||
}
|
||||
|
||||
fn style_rows(styles: &&[NamedStyleRow], _: &Env) -> Vec<PresetRow<PresetKey<u64>>> {
|
||||
let mut rows = Vec::new();
|
||||
for (folder, group) in group_by_folder(styles, |style: &NamedStyleRow| style.name.as_str()) {
|
||||
for (folder, group) in group_by_folder(*styles, |style: &NamedStyleRow| style.name.as_str()) {
|
||||
let depth = usize::from(!folder.is_empty());
|
||||
if depth == 1 {
|
||||
rows.push(PresetRow::group(PresetKey::group([folder.clone()]), folder.clone(), 0).count(group.len()));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `TextStylesPanel` and of the style picker built on `PresetPicker`.
|
||||
|
||||
use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_rows};
|
||||
use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_source};
|
||||
use craft_behavior::{IconId, Mixed, Selection};
|
||||
use craft_ui::patterns::presets::{PresetKey, PresetPicker, PresetState};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
@@ -54,7 +54,8 @@ fn picker_styles() -> Vec<NamedStyleRow> {
|
||||
|
||||
#[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn style_picker_over_style_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let rows = style_rows(&picker_styles());
|
||||
let styles = picker_styles();
|
||||
let rows = style_source(&styles);
|
||||
let ((applied, state), picker_at) = data.value_at("picker", (Mixed::Same(Some(PresetKey::Item(2_u64))), PresetState::<PresetKey<u64>>::new()));
|
||||
PresetPicker::new("Style", picker_at.bind_mixed(applied), &rows, picker_at.bind(state)).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -951,6 +951,20 @@ impl MemoProps for craft_theme::Srgba {
|
||||
}
|
||||
}
|
||||
|
||||
impl MemoProps for craft_theme::Rgba {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
let craft_theme::Rgba(channels) = *self;
|
||||
channels.key(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash` over a unit enum.
|
||||
impl MemoProps for craft_theme::TypeRole {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
key.feed_hash(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash` (`#[non_exhaustive]`).
|
||||
impl MemoProps for craft_theme::variant::Tone {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
@@ -1048,13 +1062,6 @@ impl MemoProps for egui::LayerId {
|
||||
}
|
||||
}
|
||||
|
||||
/// By what the scope's numbers and units are written with: its words, its format and its point size.
|
||||
impl MemoProps for crate::runtime::env::Units {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
self.feed(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash` (an opaque hash value).
|
||||
impl MemoProps for egui::Id {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
|
||||
-11
@@ -323,17 +323,6 @@ impl crate::contract::MemoProps for Units {
|
||||
}
|
||||
}
|
||||
|
||||
impl Units {
|
||||
/// Feeds what the readers and writers are built from: the scope's words (the unit words come from them), the
|
||||
/// number format and the point size. The readers built so far are a cache of these.
|
||||
pub(crate) fn feed(&self, key: &mut crate::contract::MemoKey) {
|
||||
use crate::contract::MemoProps as _;
|
||||
self.scope_words.key(key);
|
||||
self.format.key(key);
|
||||
self.point_size.key(key);
|
||||
}
|
||||
}
|
||||
|
||||
impl Units {
|
||||
/// The codec of a zoom field in percent: the percent reader, up to two decimals (the zoom ladder has rungs such as
|
||||
/// 66.67 %), with zoom typing (`a/b` as a ratio, a second separator cutting the text), so every zoom field reads
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview.
|
||||
|
||||
use super::fields::{DialogFields, FieldValue};
|
||||
use crate::patterns::presets::{PresetKind, PresetRow};
|
||||
use crate::patterns::presets::{PresetKind, PresetRow, PresetSource};
|
||||
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
|
||||
|
||||
use super::form::{FormDialog, FormDialogWords};
|
||||
@@ -243,9 +243,10 @@ pub struct ParamDialog<'a> {
|
||||
/// dialog open; a press comes back as `ParamDialogOutput::footer_action`.
|
||||
#[prop]
|
||||
extra_buttons: Vec<(String, Label)>,
|
||||
/// The patterns the dialog's [`ParamKind::Pattern`] rows offer.
|
||||
/// The patterns the dialog's [`ParamKind::Pattern`] rows offer. A hosted dialog's build gives a source over
|
||||
/// owned inputs.
|
||||
#[prop]
|
||||
patterns: Cow<'a, [PresetRow<String>]>,
|
||||
patterns: Option<PresetSource<'a, String>>,
|
||||
/// A muted line at the footer's start edge, left of the buttons (a file size estimate, say).
|
||||
#[prop(into)]
|
||||
footer_note: Option<Label>,
|
||||
@@ -314,7 +315,7 @@ impl<'a> ParamDialog<'a> {
|
||||
click_centres: true,
|
||||
canvas: None,
|
||||
extra_buttons: Vec::new(),
|
||||
patterns: Cow::Borrowed(&[]),
|
||||
patterns: None,
|
||||
footer_note: None,
|
||||
below: None,
|
||||
shaped: None,
|
||||
@@ -494,7 +495,8 @@ impl<'a> ParamDialog<'a> {
|
||||
let shown = form.show(ui, |ui, cx, values| {
|
||||
if cx.first() && !host_opened {
|
||||
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<DialogFields>>(key).clone());
|
||||
Self::open_values(¶ms, &patterns, saved.as_ref(), values);
|
||||
let offered = patterns.as_ref().map(|source| source.rows(ui.ctx(), &Env::of(ui))).unwrap_or_default();
|
||||
Self::open_values(¶ms, &offered, saved.as_ref(), values);
|
||||
}
|
||||
for answer in cx.take_answers() {
|
||||
let answered = match &answer {
|
||||
@@ -531,10 +533,10 @@ impl<'a> ParamDialog<'a> {
|
||||
live.view = live.view.centred_on(point, texture.size);
|
||||
}
|
||||
let mut show_rows = |ui: &mut Ui, values: &mut DialogFields| {
|
||||
let mut shown = ParamRows::new(title.clone(), ¶ms, Bind::bound(values))
|
||||
.patterns(&patterns)
|
||||
.preview_colors(&preview_colors)
|
||||
.sliders(layout.sliders());
|
||||
let mut shown = ParamRows::new(title.clone(), ¶ms, Bind::bound(values)).preview_colors(&preview_colors).sliders(layout.sliders());
|
||||
if let Some(source) = patterns.as_ref() {
|
||||
shown = shown.patterns(source);
|
||||
}
|
||||
if let Some(canvas) = canvas {
|
||||
shown = shown.canvas(canvas);
|
||||
}
|
||||
@@ -811,7 +813,9 @@ impl HostedParamDialog {
|
||||
) -> Self {
|
||||
let key = key.into();
|
||||
let ParamDialog { params, remember, patterns, previews, .. } = build(&mut fields);
|
||||
let (params, patterns) = (params.into_owned(), patterns.into_owned());
|
||||
// No pass runs here: the rows are built in the root scope, whose words name them; only their keys are read.
|
||||
let patterns = patterns.map(|source| source.rows(ctx, &Env::of_root(ctx))).unwrap_or_default();
|
||||
let params = params.into_owned();
|
||||
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
|
||||
ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut fields);
|
||||
let id = dialog_id(key.as_str());
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::contract::clicked;
|
||||
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field};
|
||||
use crate::patterns::form_dialogs::form::{read_bind, write_bind};
|
||||
use crate::patterns::presets::{
|
||||
GroupPath, NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetLibrary, PresetPicker, PresetRow, PresetState,
|
||||
GroupPath, NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetFns, PresetLibrary, PresetPicker, PresetRow, PresetSource, PresetState,
|
||||
};
|
||||
use crate::runtime::requests::{HostAnswer, PathFilter, PathKind, PathRequest};
|
||||
use crate::text::TextField;
|
||||
@@ -720,7 +720,8 @@ impl Pass<'_> {
|
||||
let words = self.words;
|
||||
let shown = {
|
||||
let presets = library.borrow();
|
||||
let rows: Vec<PresetRow<String>> = presets.items().iter().map(|item| PresetRow::item(item.name.clone(), item.name.clone(), 0)).collect();
|
||||
let names: Vec<String> = presets.items().iter().map(|item| item.name.clone()).collect();
|
||||
let rows = PresetSource::new(names, PresetFns::new(name_rows));
|
||||
let current = presets.items().iter().find(|item| item.value == *options).map(|item| item.name.clone());
|
||||
let picker = PresetPicker::new(words.preset.clone(), Bind::given(current), &rows, Bind::bound(&mut held.picker)).field(PickerField::Name);
|
||||
NamedPresetRow::new(words.preset.clone(), picker)
|
||||
@@ -958,3 +959,8 @@ fn choose<T: craft_behavior::Value>(ui: &mut Ui, name: &Label, salt: &str, entri
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One preset row per name, keyed by it.
|
||||
fn name_rows(names: &Vec<String>, _: &Env) -> Vec<PresetRow<String>> {
|
||||
names.iter().map(|name| PresetRow::item(name.clone(), name.clone(), 0)).collect()
|
||||
}
|
||||
|
||||
@@ -21,7 +21,9 @@ use crate::form::{Field, FieldGroup};
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::list::{List, ListRow};
|
||||
use crate::notices::{Notice, NoticeLayout};
|
||||
use crate::patterns::presets::{NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetState};
|
||||
use crate::patterns::presets::{
|
||||
NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState,
|
||||
};
|
||||
use crate::pickers::Select;
|
||||
use crate::runtime::env::{Env, Label, UnitKind};
|
||||
use crate::runtime::overlay::CloseReason;
|
||||
@@ -328,10 +330,9 @@ impl<'a> PdfExportDialog<'a> {
|
||||
}
|
||||
|
||||
// The preset row.
|
||||
let rows: Vec<PresetRow<String>> = presets
|
||||
.iter()
|
||||
.map(|preset| PresetRow::item(preset.name.clone(), words.preset_name(&preset.name, &app).as_str().to_owned(), 0))
|
||||
.collect();
|
||||
let names: Vec<(String, String)> =
|
||||
presets.iter().map(|preset| (preset.name.clone(), words.preset_name(&preset.name, &app).as_str().to_owned())).collect();
|
||||
let rows = PresetSource::new(names, PresetFns::new(preset_rows));
|
||||
let selected = live.preset.as_ref().and_then(|name| presets.iter().find(|preset| preset.name == *name));
|
||||
let modified = selected.is_some_and(|preset| {
|
||||
let mut shown = work.clone();
|
||||
@@ -497,3 +498,8 @@ impl<'a> PdfExportDialog<'a> {
|
||||
PdfExportOutput { response: shown.response, closed: shown.closed, result, settings: shown.value, presets: events }
|
||||
}
|
||||
}
|
||||
|
||||
/// One preset row per (name, shown name), keyed by the name.
|
||||
fn preset_rows(names: &Vec<(String, String)>, _: &Env) -> Vec<PresetRow<String>> {
|
||||
names.iter().map(|(name, shown)| PresetRow::item(name.clone(), shown.clone(), 0)).collect()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::fields::{DialogFields, FieldValue};
|
||||
use super::file_list::{FileList, FileListMode, FileListPicker};
|
||||
use crate::patterns::blend_keys::{BlendKeyEntry, BlendKeys, BlendShortcut, BlendStep, blend_entries};
|
||||
use crate::patterns::presets::{PresetKind, PresetPicker, PresetRow};
|
||||
use crate::patterns::presets::{PresetFns, PresetKind, PresetPicker, PresetSource};
|
||||
use crate::runtime::commands::{CommandState, Commands as _};
|
||||
use crate::runtime::requests::{ColorRequest, EyedropperRequest, ListingRequest, PathRequest};
|
||||
|
||||
@@ -108,7 +108,7 @@ pub struct ParamRows<'a> {
|
||||
seed: Option<Bind<'a, u64>>,
|
||||
read_only: bool,
|
||||
canvas: Option<Id>,
|
||||
patterns: &'a [PresetRow<String>],
|
||||
patterns: Option<&'a PresetSource<'a, String>>,
|
||||
preview_colors: &'a [(String, Srgba)],
|
||||
sliders: SliderFieldLayout,
|
||||
}
|
||||
@@ -123,7 +123,7 @@ impl<'a> ParamRows<'a> {
|
||||
seed: None,
|
||||
read_only: false,
|
||||
canvas: None,
|
||||
patterns: &[],
|
||||
patterns: None,
|
||||
preview_colors: &[],
|
||||
sliders: SliderFieldLayout::Inline,
|
||||
}
|
||||
@@ -159,8 +159,8 @@ impl<'a> ParamRows<'a> {
|
||||
}
|
||||
|
||||
/// The patterns a [`ParamKind::Pattern`] row offers, by id.
|
||||
pub fn patterns(mut self, rows: &'a [PresetRow<String>]) -> Self {
|
||||
self.patterns = rows;
|
||||
pub fn patterns(mut self, source: &'a PresetSource<'a, String>) -> Self {
|
||||
self.patterns = Some(source);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ struct Pass<'p> {
|
||||
/// An eyedropper row is armed.
|
||||
sampling: bool,
|
||||
/// The patterns a pattern row offers.
|
||||
patterns: &'p [PresetRow<String>],
|
||||
patterns: Option<&'p PresetSource<'p, String>>,
|
||||
/// The canvas a custom row can ask about.
|
||||
canvas: Option<Id>,
|
||||
/// The colours shown in colour rows in place of their values (`ParamRows::preview_colors`).
|
||||
@@ -306,7 +306,7 @@ impl Line<'_> {
|
||||
}
|
||||
|
||||
impl<'p> Pass<'p> {
|
||||
fn new(words: &'p ParamWords, units: &'p Units, patterns: &'p [PresetRow<String>], canvas: Option<Id>) -> Self {
|
||||
fn new(words: &'p ParamWords, units: &'p Units, patterns: Option<&'p PresetSource<'p, String>>, canvas: Option<Id>) -> Self {
|
||||
Pass {
|
||||
words,
|
||||
units,
|
||||
@@ -663,21 +663,19 @@ impl<'p> Pass<'p> {
|
||||
/// A pattern row: the stored id when the rows have it as a pattern, else the first pattern is shown. A pick writes
|
||||
/// the pattern's id; the group headers of the list take no pick.
|
||||
fn pattern(&mut self, ui: &mut Ui, line: &Line<'_>) {
|
||||
let rows = self.patterns;
|
||||
let is_pattern = |row: &&PresetRow<String>| matches!(row.kind, PresetKind::Item);
|
||||
let none = PresetSource::new((), PresetFns::new(|_, _| Vec::new()));
|
||||
let source = self.patterns.unwrap_or(&none);
|
||||
let rows = source.rows(ui.ctx(), &Env::of(ui));
|
||||
let mut patterns = rows.iter().filter(|row| matches!(row.kind, PresetKind::Item)).map(|row| &row.key);
|
||||
let stored = self.work.text(line.key);
|
||||
let current = rows
|
||||
.iter()
|
||||
.filter(is_pattern)
|
||||
.find(|row| Some(row.key.as_str()) == stored)
|
||||
.or_else(|| rows.iter().find(is_pattern))
|
||||
.map(|row| row.key.clone());
|
||||
let first = patterns.clone().next();
|
||||
let current = patterns.find(|key| Some(key.as_str()) == stored).or(first).cloned();
|
||||
// With no pattern to offer the row is disabled and writes nothing.
|
||||
let line =
|
||||
Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some(), compact: line.compact };
|
||||
line.show(ui, |ui| {
|
||||
let picked = PresetPicker::pattern(line.name.clone(), Bind::given(current.clone()), rows, Bind::kept()).show(ui).picked;
|
||||
if let Some(id) = picked.filter(|id| rows.iter().filter(is_pattern).any(|row| row.key == *id)) {
|
||||
let picked = PresetPicker::pattern(line.name.clone(), Bind::given(current.clone()), source, Bind::kept()).show(ui).picked;
|
||||
if let Some(id) = picked.filter(|id| rows.iter().any(|row| matches!(row.kind, PresetKind::Item) && row.key == *id)) {
|
||||
self.work.set(line.key, FieldValue::Text(id));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -5,8 +5,8 @@ use crate::runtime::requests::PathKind;
|
||||
|
||||
use crate::patterns::blend_keys::{BlendKeyEntry, BlendShortcut};
|
||||
use crate::patterns::form_dialogs::{NumberUnit, Param, ParamKind};
|
||||
use crate::patterns::presets::PresetRow;
|
||||
use crate::runtime::env::UnitKind;
|
||||
use crate::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use crate::runtime::env::{Env, UnitKind};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
|
||||
use egui::Ui;
|
||||
@@ -14,7 +14,7 @@ use egui::Ui;
|
||||
const SPEC: &str = r#"{"radius":0.1..1000=1,"method":"spin|zoom","smooth":bool,"seed":u32=0,"tint":color=#336699}"#;
|
||||
|
||||
/// The patterns the pattern row offers: a group and two patterns in it.
|
||||
fn patterns() -> Vec<PresetRow<String>> {
|
||||
fn pattern_rows(_: &(), _: &Env) -> Vec<PresetRow<String>> {
|
||||
vec![
|
||||
PresetRow::group("nature".to_owned(), "Nature", 0),
|
||||
PresetRow::item("grass".to_owned(), "Grass", 1),
|
||||
@@ -22,6 +22,10 @@ fn patterns() -> Vec<PresetRow<String>> {
|
||||
]
|
||||
}
|
||||
|
||||
fn patterns() -> PresetSource<'static, String> {
|
||||
PresetSource::new((), PresetFns::new(pattern_rows))
|
||||
}
|
||||
|
||||
/// One row of every kind the rows show, a section, a row that waits for a check box, a row with a unit menu, a
|
||||
/// multi-line text row, a text row forty characters wide, a searchable choice, a radio row with a disabled option, a radio row with its options in a row,
|
||||
/// a blend row, a pattern row, a files row in folder mode and a section of read-only rows.
|
||||
|
||||
@@ -606,7 +606,6 @@ impl<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser<'_,
|
||||
query: local.filter.trim().to_owned(),
|
||||
view: view_lock.unwrap_or(local.view),
|
||||
zoom: local.zoom,
|
||||
default_open,
|
||||
selected: selected.clone(),
|
||||
menu_target,
|
||||
cell_shape,
|
||||
@@ -676,7 +675,6 @@ struct ListProps<'p, 'a, K: 'static> {
|
||||
query: String,
|
||||
view: PresetView,
|
||||
zoom: f64,
|
||||
default_open: DefaultOpen,
|
||||
selected: Option<K>,
|
||||
menu_target: Option<K>,
|
||||
cell_shape: CellShape,
|
||||
@@ -711,10 +709,9 @@ fn list_view<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static>(props: &m
|
||||
let source = props.source;
|
||||
let kept = source.rows(ui.ctx(), &env);
|
||||
let rows = kept.as_slice();
|
||||
let ListProps { label, list_id, view, zoom, default_open, cell_shape, tiles: tile_size, columns, max_rows, reorder, drop_zone, row_menu, .. } =
|
||||
&*props;
|
||||
let (list_id, view, zoom, default_open, cell_shape, tile_size, columns, max_rows, reorder, drop_zone, row_menu) =
|
||||
(*list_id, *view, *zoom, *default_open, *cell_shape, *tile_size, *columns, *max_rows, *reorder, *drop_zone, *row_menu);
|
||||
let ListProps { label, list_id, view, zoom, cell_shape, tiles: tile_size, columns, max_rows, reorder, drop_zone, row_menu, .. } = &*props;
|
||||
let (list_id, view, zoom, cell_shape, tile_size, columns, max_rows, reorder, drop_zone, row_menu) =
|
||||
(*list_id, *view, *zoom, *cell_shape, *tile_size, *columns, *max_rows, *reorder, *drop_zone, *row_menu);
|
||||
let label = label.clone();
|
||||
let actions = props.actions;
|
||||
let extra_items = props.extra_items;
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::PresetRow;
|
||||
/// A group or folder by its names from the top group down: `["Brushes", "Dry Media"]`. The empty
|
||||
/// path is the library's root, which holds the ungrouped presets and the top groups. Names are
|
||||
/// unique among siblings, so a path names one group.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, crate::contract::MemoProps)]
|
||||
#[serde(transparent)]
|
||||
pub struct GroupPath(Vec<String>);
|
||||
|
||||
@@ -55,7 +55,7 @@ impl GroupPath {
|
||||
/// key never collide (PhotoCraft's `"group:{name}"` strings, the private key of
|
||||
/// `SwatchesPanel`). `I` is the preset's id: [`PresetId`] in a [`PresetLibrary`]; PhotoCraft's
|
||||
/// engine library uses the preset's name (`PresetKey<String>`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, crate::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum PresetKey<I> {
|
||||
/// A group or folder.
|
||||
@@ -77,7 +77,7 @@ impl<I> PresetKey<I> {
|
||||
}
|
||||
|
||||
/// One preset of a [`PresetLibrary`], unique by id; ids are never reused.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, crate::contract::MemoProps)]
|
||||
#[serde(transparent)]
|
||||
pub struct PresetId(u64);
|
||||
|
||||
|
||||
@@ -24,14 +24,13 @@ use crate::contract::{
|
||||
use crate::layout_components::Stack;
|
||||
use crate::pickers::{FaceKind, SelectFace};
|
||||
use crate::popover::Popover;
|
||||
use crate::primitives::ContentPainterCx;
|
||||
use crate::runtime::env::{Env, EnvView, Label};
|
||||
use crate::runtime::memory::StageAccess;
|
||||
use crate::runtime::overlay::CloseReason;
|
||||
use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook, UiTokens};
|
||||
use crate::tile_grid::TileZoom;
|
||||
use craft_behavior::{EditEvent, EditEvents, HitLevel, HitPriority, Intent, Metrics, Mixed, NumberCodec, PartKey, PressPhase, Sense, Value};
|
||||
use egui::{Pos2, Rect, Response, Ui, Vec2};
|
||||
use egui::{Pos2, Response, Ui, Vec2};
|
||||
use std::hash::Hash;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ impl<'a, K: Clone + PartialEq + Send + Sync + 'static> PresetSource<'a, K> {
|
||||
let mut key = MemoKey::new();
|
||||
self.0.key(&mut key);
|
||||
crate::contract::MemoProps::key(&units, &mut key);
|
||||
let id = Id::new(("preset-rows", key.finish()));
|
||||
let id = Id::NULL.with(("preset-rows", key.finish()));
|
||||
derived(ctx, id, &RowsKey { source: self, units: &units }, || self.0.rows(env))
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft_ui::dialog::{DialogHost, DialogResult, HeldAnswer, HeldOk, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult,
|
||||
};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -18,7 +18,6 @@ use craft_ui::testing::{Fixture, trial};
|
||||
use egui::load::SizedTexture;
|
||||
use egui::{Key, Modifiers, TextureId, Vec2, vec2};
|
||||
use serde_json::json;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
@@ -477,12 +476,11 @@ fn filter_params(narrow: bool) -> Vec<Param> {
|
||||
|
||||
/// A remembering filter dialog; `narrow` offers fewer patterns.
|
||||
fn filter(fields: &mut DialogFields, narrow: bool) -> ParamDialog<'_> {
|
||||
let ids: &[&str] = if narrow { &["dots"] } else { &["dots", "stripes"] };
|
||||
let patterns: Vec<PresetRow<String>> = ids.iter().map(|id| PresetRow::item((*id).to_owned(), *id, 0)).collect();
|
||||
let ids: &'static [&'static str] = if narrow { &["dots"] } else { &["dots", "stripes"] };
|
||||
ParamDialog::new("filter", "Filter", filter_params(narrow))
|
||||
.values(Bind::bound(fields))
|
||||
.remember(SaveKey::new("trial.filter"))
|
||||
.patterns(Cow::Owned(patterns))
|
||||
.patterns(PresetSource::new(ids, PresetFns::new(|ids, _| ids.iter().map(|id| PresetRow::item((*id).to_owned(), *id, 0)).collect())))
|
||||
}
|
||||
|
||||
fn wide_filter(fields: &mut DialogFields) -> ParamDialog<'_> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut};
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, NumberUnit, Param, ParamDialog, ParamKind, ParamRows, set_param_field};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::{Label, Scale, UnitKind};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::value_drag::SliderScale;
|
||||
@@ -350,11 +350,16 @@ fn paired_parameter_fields_15539_leave_no_gap_when_both_are_hidden() {
|
||||
/// id, and a group header takes no pick.
|
||||
#[trial]
|
||||
fn a_pattern_row_picks_its_pattern() {
|
||||
let rows = vec![
|
||||
PresetRow::group("nature".to_owned(), "Nature", 0),
|
||||
PresetRow::item("grass".to_owned(), "Grass", 1),
|
||||
PresetRow::item("sand".to_owned(), "Sand", 1),
|
||||
];
|
||||
let rows = PresetSource::new(
|
||||
(),
|
||||
PresetFns::new(|_, _| {
|
||||
vec![
|
||||
PresetRow::group("nature".to_owned(), "Nature", 0),
|
||||
PresetRow::item("grass".to_owned(), "Grass", 1),
|
||||
PresetRow::item("sand".to_owned(), "Sand", 1),
|
||||
]
|
||||
}),
|
||||
);
|
||||
let values = Rc::new(RefCell::new(DialogFields::from_pairs([("fill", "ghost")])));
|
||||
let shown = values.clone();
|
||||
let params = vec![Param::new("fill", "Fill", ParamKind::pattern(None))];
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState};
|
||||
use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, PresetView};
|
||||
use craft_ui::popover::Popover;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_runs, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
@@ -134,3 +134,35 @@ fn a_chip_with_a_caption_range_keeps_its_width_as_the_caption_grows() {
|
||||
assert_eq!(place(&fixture), first, "caption {next}: the chip and the button after it stay in place");
|
||||
}
|
||||
}
|
||||
|
||||
/// The list views and component runs of the last frame: the views of `props` that ran, and the list rows that ran.
|
||||
fn list_runs(fixture: &Fixture, props: &str) -> (usize, u32) {
|
||||
let views = last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count();
|
||||
let rows = last_pass_runs(fixture.ctx()).into_iter().filter(|(name, _)| *name == "ListRow").map(|(_, runs)| runs).sum();
|
||||
(views, rows)
|
||||
}
|
||||
|
||||
/// An open picker's list runs its rows when it opens, then, while nothing changes, replays: no list row runs.
|
||||
#[trial]
|
||||
fn an_open_picker_with_nothing_changing_runs_no_list_row() {
|
||||
let mut value = Some(CORAL);
|
||||
let mut state = PresetState::<u32>::new();
|
||||
let rows = PresetSource::new((), PresetFns::new(|_, _| (0..12).map(|key| PresetRow::item(CORAL + key, format!("Preset {key}"), 0)).collect()));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = PresetPicker::new("Swatch", Bind::bound(&mut value), &rows, Bind::bound(&mut state)).view(PresetView::List).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(800.0, 800.0));
|
||||
fixture.settle();
|
||||
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the field shows");
|
||||
fixture.click(&field);
|
||||
let mut opened = list_runs(&fixture, "ListProps").0;
|
||||
for _ in 0..4 {
|
||||
fixture.idle(1);
|
||||
opened += list_runs(&fixture, "ListProps").0;
|
||||
}
|
||||
assert!(opened > 0, "the list view runs when the popover opens");
|
||||
fixture.settle();
|
||||
fixture.frame(vec![]);
|
||||
assert!(fixture.by_label("Preset 3").is_some(), "the popover stays open");
|
||||
assert_eq!(list_runs(&fixture, "ListProps"), (0, 0), "an idle frame runs neither the list view nor a row");
|
||||
}
|
||||
|
||||
@@ -324,7 +324,7 @@ pub(super) fn hexagon(rect: Rect) -> Vec<Pos2> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The face of a swatch outside a `Swatch`: a preset thumbnail of a colour (`PresetBrowser::thumb`). It paints
|
||||
/// The face of a swatch outside a `Swatch`: a preset thumbnail of a colour (`PresetFns::thumb`). It paints
|
||||
/// what a non-cell `Swatch` of the same colour paints, from the style that `Swatch` resolves, with the selected
|
||||
/// ring when `selected`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
||||
@@ -1147,6 +1147,42 @@ fn a_drag_on_a_popover_over_a_view_replays_the_view() {
|
||||
assert!(runs.iter().all(Vec::is_empty), "the board replays in every drag frame: {runs:?}");
|
||||
}
|
||||
|
||||
/// A view inside an open popover: the popover's body is on its own layer.
|
||||
struct InPopover {
|
||||
/// Where the view's button was shown in the last frame.
|
||||
button: Option<Rect>,
|
||||
}
|
||||
|
||||
impl InPopover {
|
||||
fn frame(&mut self, frames: &mut Frames, events: Vec<egui::Event>) -> Vec<&'static str> {
|
||||
let button = &mut self.button;
|
||||
frames.frame(events, |ui| {
|
||||
Popover::new("Presets", Bind::given(true)).at_point(Pos2::new(80.0, 80.0)).show(ui, |ui, _| {
|
||||
*button = MemoView::new("presets", Title { title: "Inside".to_owned() }, title).show(ui);
|
||||
});
|
||||
});
|
||||
let ran = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran);
|
||||
ran.map(|(name, _, _)| short_name(name)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A memoized view inside an open popover replays while nothing changes, still painted, and runs when the pointer
|
||||
/// moves over it.
|
||||
#[trial]
|
||||
fn a_view_in_an_open_popover_replays_while_nothing_changes() {
|
||||
let mut scene = InPopover { button: None };
|
||||
let mut frames = Frames::new();
|
||||
for _ in 0..SETTLE {
|
||||
scene.frame(&mut frames, vec![]);
|
||||
}
|
||||
let idle: Vec<Vec<&str>> = (0..WARM).map(|_| scene.frame(&mut frames, vec![])).collect();
|
||||
assert!(idle.iter().all(Vec::is_empty), "the view in the popover ran in idle frames: {idle:?}");
|
||||
assert_eq!(runs_of(&frames, "Title"), [MemoRun::Replayed], "{:?}", last_pass_memo_runs(&frames.ctx));
|
||||
assert!(painted(&frames, "Inside"), "the replayed view is painted");
|
||||
let over = scene.button.expect("the popover shows the view").center();
|
||||
assert_eq!(scene.frame(&mut frames, vec![moved(over)]), ["Title"], "the pointer over the view runs it");
|
||||
}
|
||||
|
||||
#[derive(MemoProps)]
|
||||
struct Centred {
|
||||
label: String,
|
||||
|
||||
Reference in New Issue
Block a user