mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 03:17:43 +00:00
effects-w3: net change of 1 commits
- effects-w3: written from its sheet
This commit is contained in:
@@ -49,11 +49,11 @@ use craft_ui::dialog::{
|
||||
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
|
||||
FullWindowZoomBar, SideFooter, WorkspaceCx, WorkspacePass,
|
||||
};
|
||||
use craft_ui::patterns::form_dialogs::{FieldValue, set_param_field};
|
||||
use craft_ui::patterns::form_dialogs::FieldValue;
|
||||
use craft_ui::primitives::Checker;
|
||||
use craft_ui::primitives::textures::{ThumbnailOptions, Thumbnails};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::runtime::requests::{ColorRequest, PathRequest};
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use egui::{Context, Ui};
|
||||
@@ -109,6 +109,14 @@ pub enum FilterGalleryEvent {
|
||||
Select(usize),
|
||||
/// A colour parameter's swatch was pressed: the app opens its picker and answers with `set_color`.
|
||||
PickColor(ColorRequest),
|
||||
/// A Browse button was pressed on the layer `layer`: the app opens its file picker and answers with
|
||||
/// `set_layer_fields`, which follows the layer if it moved meanwhile.
|
||||
PickPath {
|
||||
/// The layer whose parameter asked.
|
||||
layer: LayerId,
|
||||
/// The parameter's key and what the picker offers.
|
||||
request: PathRequest,
|
||||
},
|
||||
}
|
||||
|
||||
/// The undo step name of every stack change: the workspace's name.
|
||||
@@ -212,6 +220,25 @@ impl FilterGalleryWorkspace {
|
||||
self.queued.push(FilterGalleryEvent::Stack(EffectChange::with_fields(index, fields)));
|
||||
}
|
||||
|
||||
/// The answer to a [`FilterGalleryEvent::PickPath`]: writes `entries` into the fields of the layer `layer` as one
|
||||
/// undo step. Returns `false`, changing nothing, once the layer is deleted.
|
||||
pub fn set_layer_fields(&mut self, layer: LayerId, entries: impl IntoIterator<Item = (String, FieldValue)>) -> bool {
|
||||
let Some(at) = self.session.position(layer) else { return false };
|
||||
let before = self.session.clone();
|
||||
let Some(effect) = self.session.effects.get_mut(at) else { return false };
|
||||
let mut fields = effect.fields.clone();
|
||||
let mut name = None;
|
||||
for (key, value) in entries {
|
||||
name.get_or_insert_with(|| Arc::<str>::from(key.as_str()));
|
||||
fields.set(key, value);
|
||||
}
|
||||
let Some(name) = name.filter(|_| fields != effect.fields) else { return true };
|
||||
effect.fields = fields.clone();
|
||||
self.record(before, &name);
|
||||
self.queued.push(FilterGalleryEvent::Stack(EffectChange::with_fields(at, fields)));
|
||||
true
|
||||
}
|
||||
|
||||
/// Undoes or redoes, keeping the selection on a layer that remains. The pass reports the selection as a `Select`
|
||||
/// event when it moved.
|
||||
fn step(&mut self, step: Step) {
|
||||
@@ -249,66 +276,21 @@ impl FilterGalleryWorkspace {
|
||||
|
||||
/// Sets the automation field `field` to `value` over `catalog`; `Err` says why it refused.
|
||||
fn set_field(&mut self, catalog: &dyn FilterCatalog, name: &Arc<str>, field: &str, value: Value) -> Result<(), String> {
|
||||
let rejects = |value: &Value| FieldRefusal::Rejects(value).message(field);
|
||||
let index = |value: &Value| value.as_u64().and_then(|at| usize::try_from(at).ok());
|
||||
let selected = self.clamped_selection();
|
||||
let change = match field {
|
||||
"effects" => {
|
||||
let effects: Vec<EffectLayer> = serde_json::from_value(value.clone()).map_err(|_| rejects(&value))?;
|
||||
if effects.is_empty() || effects.iter().any(|effect| catalog.filter(&effect.filter).is_none()) {
|
||||
return Err(rejects(&value));
|
||||
}
|
||||
EffectChange::Replace { effects }
|
||||
if field == "zoom" {
|
||||
match (value.as_str(), value.as_f64()) {
|
||||
(Some("fit"), _) => self.view.apply(ViewCommands::FitOnScreen),
|
||||
(_, Some(zoom)) if zoom.is_finite() && zoom > 0.0 => self.view.set_device_zoom(zoom),
|
||||
_ => return Err(FieldRefusal::Rejects(&value).message(field)),
|
||||
};
|
||||
return Ok(());
|
||||
}
|
||||
match self.session.field_change(catalog, self.clamped_selection(), field, &value)? {
|
||||
Some(SessionField::Select(at)) => self.selected = at,
|
||||
Some(SessionField::Change(change)) => {
|
||||
self.change(change, catalog, name);
|
||||
}
|
||||
"select" => {
|
||||
let at = index(&value).ok_or_else(|| rejects(&value))?;
|
||||
self.selected = at.min(self.session.effects.len().saturating_sub(1));
|
||||
return Ok(());
|
||||
}
|
||||
"zoom" => {
|
||||
match (value.as_str(), value.as_f64()) {
|
||||
(Some("fit"), _) => self.view.apply(ViewCommands::FitOnScreen),
|
||||
(_, Some(zoom)) if zoom.is_finite() && zoom > 0.0 => self.view.set_device_zoom(zoom),
|
||||
_ => return Err(rejects(&value)),
|
||||
};
|
||||
return Ok(());
|
||||
}
|
||||
"add" | "delete" => match value.as_bool() {
|
||||
Some(true) if field == "add" => EffectChange::Add,
|
||||
Some(true) => EffectChange::Delete,
|
||||
Some(false) => return Ok(()),
|
||||
None => return Err(rejects(&value)),
|
||||
},
|
||||
"toggle" => {
|
||||
let at = index(&value).ok_or_else(|| rejects(&value))?;
|
||||
let effect = self.session.effects.get(at).ok_or_else(|| rejects(&value))?;
|
||||
EffectChange::set_visible(at, !effect.visible)
|
||||
}
|
||||
"move" => {
|
||||
let count = self.session.effects.len();
|
||||
let (from, to) = (value.get("from").and_then(index), value.get("to").and_then(index));
|
||||
let (Some(from), Some(to)) = (from, to) else { return Err(rejects(&value)) };
|
||||
if from >= count || to >= count {
|
||||
return Err(rejects(&value));
|
||||
}
|
||||
EffectChange::move_to(from, to)
|
||||
}
|
||||
"filter" => {
|
||||
let key = value.as_str().filter(|key| catalog.filter(key).is_some()).ok_or_else(|| rejects(&value))?;
|
||||
EffectChange::set_filter(selected, key)
|
||||
}
|
||||
"params" => {
|
||||
let (Some(effect), Some(entries)) = (self.session.effects.get(selected), value.as_object()) else { return Err(rejects(&value)) };
|
||||
let filter = catalog.filter(&effect.filter).ok_or_else(|| FieldRefusal::Inactive.message(field))?;
|
||||
let mut fields = effect.fields.clone();
|
||||
for (key, entry) in entries {
|
||||
set_param_field(&filter.params, &mut fields, key, entry.clone())?;
|
||||
}
|
||||
EffectChange::with_fields(selected, fields)
|
||||
}
|
||||
_ => return Err(FieldRefusal::Unknown.message(field)),
|
||||
};
|
||||
self.change(change, catalog, name);
|
||||
None => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -356,11 +338,13 @@ impl FullWindowWorkspace for FilterGalleryWorkspace {
|
||||
let mut changes = Vec::new();
|
||||
let mut stack_pick = None;
|
||||
let mut pick_color = None;
|
||||
let mut pick_path = None;
|
||||
FullWindowSide::new(words.settings.clone()).headerless().show(ui, |ui, _| {
|
||||
if let Some(effect) = workspace.session.effects.get(current) {
|
||||
let parameters = EffectParameters::new(current, effect, &index).show(ui);
|
||||
changes.extend(parameters.change);
|
||||
pick_color = parameters.pick_color;
|
||||
pick_path = parameters.path;
|
||||
}
|
||||
let stack = EffectStack::new(&workspace.session.effects, current, &index).show(ui);
|
||||
stack_pick = stack.selected;
|
||||
@@ -370,6 +354,11 @@ impl FullWindowWorkspace for FilterGalleryWorkspace {
|
||||
if let Some(request) = pick_color {
|
||||
workspace.queued.push(FilterGalleryEvent::PickColor(request));
|
||||
}
|
||||
if let Some(request) = pick_path
|
||||
&& let Some(layer) = workspace.session.effects.get(current).map(|effect| effect.id)
|
||||
{
|
||||
workspace.queued.push(FilterGalleryEvent::PickPath { layer, request });
|
||||
}
|
||||
for change in changes {
|
||||
workspace.change(change, catalog, &history_name);
|
||||
}
|
||||
@@ -440,8 +429,11 @@ impl FullWindowWorkspace for FilterGalleryWorkspace {
|
||||
|
||||
fn json_fields(&self, _source: &Self::Source) -> Option<Value> {
|
||||
let zoom = if self.view.is_fit() { json!("fit") } else { json!(self.view.device_zoom()) };
|
||||
let effects = serde_json::to_value(&self.session.effects).unwrap_or_default();
|
||||
Some(json!({ "effects": effects, "select": self.clamped_selection(), "zoom": zoom }))
|
||||
let mut fields = self.session.json_fields(self.clamped_selection());
|
||||
if let Value::Object(map) = &mut fields {
|
||||
map.insert("zoom".to_owned(), zoom);
|
||||
}
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, source: &Self::Source, field: &str, value: Value) -> Result<(), String> {
|
||||
|
||||
@@ -66,6 +66,7 @@ impl<'a> EffectParameters<'a> {
|
||||
let filter = index.filter(&effect.filter);
|
||||
let mut change = None;
|
||||
let mut pick_color = None;
|
||||
let mut path = None;
|
||||
let stack = Stack::new().show(ui, |ui, _| {
|
||||
let picked = Select::new(words.filter.clone(), Bind::given(effect.filter.clone()), &entries).show(ui);
|
||||
if let Some(key) = picked.value().filter(|key| **key != effect.filter) {
|
||||
@@ -80,10 +81,11 @@ impl<'a> EffectParameters<'a> {
|
||||
change = Some(EffectChange::with_fields(at, fields));
|
||||
}
|
||||
pick_color = rows.pick_color;
|
||||
path = rows.path;
|
||||
if filter.uses_colors {
|
||||
Text::new(words.uses_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
});
|
||||
EffectParametersOutput { response: stack.output, change, pick_color, path: None }
|
||||
EffectParametersOutput { response: stack.output, change, pick_color, path }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
//! Filter Gallery's session: the effect-layer stack.
|
||||
|
||||
use craft_ui::patterns::form_dialogs::DialogFields;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_ui::dialog::FieldRefusal;
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, set_param_field};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::catalog::FilterCatalog;
|
||||
|
||||
/// The ids handed out so far. Outside the session so that its equality and the history snapshots never hold it: an
|
||||
/// undo restores old layers with their ids and never reissues one.
|
||||
static NEXT_LAYER: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The identity of an effect layer: it stays with the layer through every change but a deletion, so a host can follow
|
||||
/// a layer across edits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -12,13 +20,14 @@ pub struct LayerId(u64);
|
||||
impl LayerId {
|
||||
/// A new id, from the crate's counter.
|
||||
fn fresh() -> Self {
|
||||
todo!("ef.F17")
|
||||
Self(NEXT_LAYER.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
/// One effect layer: a filter, its fields (the catalog's parameters) and its eye. It serialises as
|
||||
/// `{filter, params, visible}`, with a choice by its option's name, as the engine's effects do.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
/// `{filter, params, visible}`, with a choice by its option's name, as the engine's effects do. Two layers are equal
|
||||
/// when their content is: the id is identity, not content.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct EffectLayer {
|
||||
@@ -34,12 +43,17 @@ pub struct EffectLayer {
|
||||
pub id: LayerId,
|
||||
}
|
||||
|
||||
impl PartialEq for EffectLayer {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.filter == other.filter && self.fields == other.fields && self.visible == other.visible
|
||||
}
|
||||
}
|
||||
|
||||
impl EffectLayer {
|
||||
/// A visible layer of `filter` with the catalog's defaults (none for a key the catalog lacks).
|
||||
/// A visible layer of `filter` with the catalog's defaults (none for a key the catalog lacks), under a fresh id.
|
||||
fn of(filter: &str, catalog: &dyn FilterCatalog) -> Self {
|
||||
let fields = catalog.filter(filter).map(|found| found.defaults()).unwrap_or_default();
|
||||
// P3(effects-w3): ef.F17
|
||||
Self { filter: filter.to_owned(), fields, visible: true, id: LayerId(0) }
|
||||
Self { filter: filter.to_owned(), fields, visible: true, id: LayerId::fresh() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,8 +156,7 @@ impl FilterGallerySession {
|
||||
|
||||
/// The index of the layer `id` now, or `None` once it is deleted.
|
||||
pub fn position(&self, id: LayerId) -> Option<usize> {
|
||||
let _ = id;
|
||||
todo!("ef.F17")
|
||||
self.effects.iter().position(|effect| effect.id == id)
|
||||
}
|
||||
|
||||
/// The change an automation `field` set to `value` makes, as `effects`, `select`, `add`, `delete`, `toggle`, `move`,
|
||||
@@ -156,14 +169,62 @@ impl FilterGallerySession {
|
||||
field: &str,
|
||||
value: &serde_json::Value,
|
||||
) -> Result<Option<SessionField>, String> {
|
||||
let _ = (catalog, selected, field, value);
|
||||
todo!("ef.F18")
|
||||
let rejects = || FieldRefusal::Rejects(value).message(field);
|
||||
let index = |value: &Value| value.as_u64().and_then(|at| usize::try_from(at).ok());
|
||||
let count = self.effects.len();
|
||||
let change = match field {
|
||||
"effects" => {
|
||||
let effects: Vec<EffectLayer> = serde_json::from_value(value.clone()).map_err(|_| rejects())?;
|
||||
if effects.is_empty() || effects.iter().any(|effect| catalog.filter(&effect.filter).is_none()) {
|
||||
return Err(rejects());
|
||||
}
|
||||
EffectChange::Replace { effects }
|
||||
}
|
||||
"select" => {
|
||||
let at = index(value).ok_or_else(rejects)?;
|
||||
return Ok(Some(SessionField::Select(at.min(count.saturating_sub(1)))));
|
||||
}
|
||||
"add" | "delete" => match value.as_bool() {
|
||||
Some(true) if field == "add" => EffectChange::Add,
|
||||
Some(true) => EffectChange::Delete,
|
||||
Some(false) => return Ok(None),
|
||||
None => return Err(rejects()),
|
||||
},
|
||||
"toggle" => {
|
||||
let at = index(value).ok_or_else(rejects)?;
|
||||
let effect = self.effects.get(at).ok_or_else(rejects)?;
|
||||
EffectChange::set_visible(at, !effect.visible)
|
||||
}
|
||||
"move" => {
|
||||
let (from, to) = (value.get("from").and_then(index), value.get("to").and_then(index));
|
||||
let (Some(from), Some(to)) = (from, to) else { return Err(rejects()) };
|
||||
if from >= count || to >= count {
|
||||
return Err(rejects());
|
||||
}
|
||||
EffectChange::move_to(from, to)
|
||||
}
|
||||
"filter" => {
|
||||
let key = value.as_str().filter(|key| catalog.filter(key).is_some()).ok_or_else(rejects)?;
|
||||
EffectChange::set_filter(selected, key)
|
||||
}
|
||||
"params" => {
|
||||
let (Some(effect), Some(entries)) = (self.effects.get(selected), value.as_object()) else { return Err(rejects()) };
|
||||
let filter = catalog.filter(&effect.filter).ok_or_else(|| FieldRefusal::Inactive.message(field))?;
|
||||
let mut fields = effect.fields.clone();
|
||||
for (key, entry) in entries {
|
||||
set_param_field(&filter.params, &mut fields, key, entry.clone())?;
|
||||
}
|
||||
EffectChange::with_fields(selected, fields)
|
||||
}
|
||||
_ => return Err(FieldRefusal::Unknown.message(field)),
|
||||
};
|
||||
Ok(Some(SessionField::Change(change)))
|
||||
}
|
||||
|
||||
/// The automation fields of the session: `effects` and `select`.
|
||||
pub fn json_fields(&self, selected: usize) -> serde_json::Value {
|
||||
let _ = selected;
|
||||
todo!("ef.F18")
|
||||
pub fn json_fields(&self, selected: usize) -> Value {
|
||||
let effects = serde_json::to_value(&self.effects).unwrap_or_default();
|
||||
json!({ "effects": effects, "select": selected })
|
||||
}
|
||||
|
||||
/// Applies `change`, keeping `selected` on the layer it named (a new or moved layer is
|
||||
@@ -177,7 +238,7 @@ impl FilterGallerySession {
|
||||
let changed = match change {
|
||||
EffectChange::SetFilter { index, filter } => match self.effects.get_mut(index) {
|
||||
Some(effect) if effect.filter != filter && catalog.filter(&filter).is_some() => {
|
||||
*effect = EffectLayer { visible: effect.visible, ..EffectLayer::of(&filter, catalog) };
|
||||
*effect = EffectLayer { visible: effect.visible, id: effect.id, ..EffectLayer::of(&filter, catalog) };
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
@@ -190,12 +251,16 @@ impl FilterGallerySession {
|
||||
_ => false,
|
||||
},
|
||||
// The stack never empties: a gallery always has one layer to show.
|
||||
EffectChange::Replace { effects } if !effects.is_empty() && effects != self.effects => {
|
||||
EffectChange::Replace { mut effects } if !effects.is_empty() && effects != self.effects => {
|
||||
for effect in &mut effects {
|
||||
effect.id = LayerId::fresh();
|
||||
}
|
||||
self.effects = effects;
|
||||
true
|
||||
}
|
||||
EffectChange::Add => {
|
||||
let copy = self.effects[current].clone();
|
||||
let mut copy = self.effects[current].clone();
|
||||
copy.id = LayerId::fresh();
|
||||
self.effects.insert(current + 1, copy);
|
||||
*selected = current + 1;
|
||||
true
|
||||
|
||||
@@ -18,7 +18,7 @@ use egui::Ui;
|
||||
|
||||
use super::{
|
||||
EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen,
|
||||
FilterGallerySession, FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, GalleryFilter, GalleryThumb,
|
||||
FilterGallerySession, FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, FilterTreeLayout, GalleryFilter, GalleryThumb,
|
||||
};
|
||||
use crate::ui::mock_image::MockImage;
|
||||
use crate::ui::wide_angle::PreviewDone;
|
||||
@@ -181,6 +181,13 @@ fn filter_tree(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
FilterTree::new(&index, "sponge", &thumbs, &FakeThumbSource::<GalleryThumb>::new()).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(FilterTree<'static>, covers = [], drive = Drive::Never)]
|
||||
fn filter_tree_lists(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let index = FilterIndex::of(&MockGallery);
|
||||
let thumbs = Thumbnails::<GalleryThumb>::in_context(ui.ctx(), "gallery-story-tree-lists-thumbs", ThumbnailOptions::default());
|
||||
FilterTree::new(&index, "sponge", &thumbs, &FakeThumbSource::<GalleryThumb>::new()).layout(FilterTreeLayout::Lists).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(EffectStack<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn effect_stack(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let index = FilterIndex::of(&MockGallery);
|
||||
|
||||
@@ -6,14 +6,17 @@ use craft_behavior::{DisplayOrder, ItemSource, Selection};
|
||||
use craft_ui::contract::{
|
||||
ActivateOn, Bind, CollectionEvent, NoValue, Outcome, Props as _, SaveKey, SelectMode, ShowCollection as _, ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::list::{List, ListRow, ThumbAspect, ThumbSize};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::primitives::textures::{Priority, ThumbFit, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::sections::Section;
|
||||
use craft_ui::tile_grid::{Tile, TileGrid};
|
||||
use egui::{Response, Ui};
|
||||
use egui::{Rect, Response, Ui};
|
||||
|
||||
use super::catalog::{FilterIndex, GalleryThumb};
|
||||
use super::catalog::{FilterCategory, FilterIndex, GalleryThumb};
|
||||
use super::words::FilterGalleryWords;
|
||||
|
||||
/// A filter thumbnail's shape: PhotoCraft's 80 by 56.
|
||||
const THUMB_ASPECT: (u16, u16) = (10, 7);
|
||||
@@ -50,6 +53,51 @@ impl DisplayOrder<String> for Folder<'_> {
|
||||
|
||||
impl ItemSource<String> for Folder<'_> {}
|
||||
|
||||
/// The categories that hold filters, in menu order; a key is the category's.
|
||||
struct Categories<'a> {
|
||||
listed: Vec<&'a FilterCategory>,
|
||||
}
|
||||
|
||||
impl Categories<'_> {
|
||||
fn get(&self, key: &str) -> Option<&FilterCategory> {
|
||||
self.listed.iter().copied().find(|category| category.key == key)
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayOrder<String> for Categories<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.listed.len()
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> String {
|
||||
self.listed[at].key.clone()
|
||||
}
|
||||
|
||||
fn index_of(&self, key: &String) -> Option<usize> {
|
||||
self.listed.iter().position(|category| category.key == *key)
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
Some(Cow::Borrowed(self.listed[at].label.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemSource<String> for Categories<'_> {}
|
||||
|
||||
/// Paints the thumbnail of `filter` from the cache, covering the cell: the one painter of the tile and of the list row.
|
||||
fn thumb_painter<'a>(
|
||||
thumbs: &'a Thumbnails<GalleryThumb>,
|
||||
source: &'a dyn ThumbSource<GalleryThumb>,
|
||||
filter: GalleryThumb,
|
||||
) -> impl FnOnce(&ContentPainterCx, Rect) + 'a {
|
||||
move |cx, rect| {
|
||||
let ctx = cx.painter.ctx();
|
||||
let request = ThumbRequest::for_cell(rect.width(), ctx.pixels_per_point());
|
||||
let state = thumbs.state(ctx, source, &filter, &request, Priority::VISIBLE);
|
||||
thumbs.paint(cx, rect, &state, &ThumbPaint::default().fit(ThumbFit::Cover).checker(false));
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`FilterTree::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -94,25 +142,90 @@ pub struct FilterTree<'a> {
|
||||
selected: &'a str,
|
||||
thumbs: &'a Thumbnails<GalleryThumb>,
|
||||
source: &'a dyn ThumbSource<GalleryThumb>,
|
||||
layout: FilterTreeLayout,
|
||||
}
|
||||
|
||||
impl<'a> FilterTree<'a> {
|
||||
/// The folders of `index`, with the filter `selected` current; `source` renders the pictures `thumbs`
|
||||
/// asks for.
|
||||
pub fn new(index: &'a FilterIndex, selected: &'a str, thumbs: &'a Thumbnails<GalleryThumb>, source: &'a dyn ThumbSource<GalleryThumb>) -> Self {
|
||||
Self { index, selected, thumbs, source }
|
||||
Self { index, selected, thumbs, source, layout: FilterTreeLayout::default() }
|
||||
}
|
||||
|
||||
/// How the categories and filters are laid out; the folders by default.
|
||||
#[must_use]
|
||||
pub fn layout(self, layout: FilterTreeLayout) -> Self {
|
||||
let _ = layout;
|
||||
todo!("ef.F15")
|
||||
pub fn layout(mut self, layout: FilterTreeLayout) -> Self {
|
||||
self.layout = layout;
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws the category folders and filter thumbnails and reports the filter picked.
|
||||
/// Draws the categories and filters in the chosen layout and reports the filter picked.
|
||||
pub fn show(self, ui: &mut Ui) -> FilterTreeOutput {
|
||||
let Self { index, selected, thumbs, source } = self;
|
||||
match self.layout {
|
||||
FilterTreeLayout::Folders => self.show_folders(ui),
|
||||
FilterTreeLayout::Lists => self.show_lists(ui),
|
||||
}
|
||||
}
|
||||
|
||||
/// A categories list beside a filters list of the current filter's category. A category press picks its first
|
||||
/// filter, except for the current category, whose press changes nothing.
|
||||
fn show_lists(self, ui: &mut Ui) -> FilterTreeOutput {
|
||||
let Self { index, selected, thumbs, source, .. } = self;
|
||||
let words = Env::of(ui).words::<FilterGalleryWords>();
|
||||
let categories = Categories { listed: index.categories().iter().filter(|category| !category.filters.is_empty()).collect() };
|
||||
let current = categories
|
||||
.listed
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|category| category.filters.iter().any(|key| key == selected))
|
||||
.or_else(|| categories.listed.first().copied());
|
||||
let mut picked = None;
|
||||
let row = Row::new().show(ui, |ui, _| {
|
||||
let Some(current) = current else { return };
|
||||
let mut chosen = Selection::single(current.key.clone());
|
||||
let out = List::<String>::new(words.categories.clone())
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.natural_height(true)
|
||||
.selection(Bind::bound(&mut chosen))
|
||||
.show_items(ui, &categories, &mut |key, _| {
|
||||
ListRow::new(categories.get(key).map_or_else(|| Label::from(key.clone()), |category| category.label.clone()))
|
||||
});
|
||||
for event in out.events {
|
||||
if let CollectionEvent::Activate(key) = event
|
||||
&& key != current.key
|
||||
{
|
||||
picked = categories.get(&key).and_then(|category| category.filters.first().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
let folder = Folder { keys: ¤t.filters, index };
|
||||
let mut chosen = if current.filters.iter().any(|key| key == selected) { Selection::single(selected.to_owned()) } else { Selection::default() };
|
||||
let (wide, high) = THUMB_ASPECT;
|
||||
let out = List::<String>::new(words.filters.clone())
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.natural_height(true)
|
||||
.selection(Bind::bound(&mut chosen))
|
||||
.show_items(ui, &folder, &mut |key, _| {
|
||||
ListRow::new(index.label(key)).thumb_aspect(
|
||||
ThumbSize::Large,
|
||||
ThumbAspect::new(wide, high),
|
||||
thumb_painter(thumbs, source, GalleryThumb::new(key.clone())),
|
||||
)
|
||||
});
|
||||
for event in out.events {
|
||||
if let CollectionEvent::Activate(key) = event {
|
||||
picked = Some(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
FilterTreeOutput { response: row.output, picked }
|
||||
}
|
||||
|
||||
/// The category folders of tile grids.
|
||||
fn show_folders(self, ui: &mut Ui) -> FilterTreeOutput {
|
||||
let Self { index, selected, thumbs, source, .. } = self;
|
||||
let mut picked = None;
|
||||
let stack = Stack::new().show(ui, |ui, _| {
|
||||
for category in index.categories() {
|
||||
@@ -133,12 +246,7 @@ impl<'a> FilterTree<'a> {
|
||||
.show_items(ui, &folder, &mut |key, _| {
|
||||
let filter = GalleryThumb::new(key.clone());
|
||||
let (wide, high) = THUMB_ASPECT;
|
||||
Tile::new(index.label(key)).thumb(ThumbAspect::new(wide, high), move |cx, rect| {
|
||||
let ctx = cx.painter.ctx();
|
||||
let request = ThumbRequest::for_cell(rect.width(), ctx.pixels_per_point());
|
||||
let state = thumbs.state(ctx, source, &filter, &request, Priority::VISIBLE);
|
||||
thumbs.paint(cx, rect, &state, &ThumbPaint::default().fit(ThumbFit::Cover).checker(false));
|
||||
})
|
||||
Tile::new(index.label(key)).thumb(ThumbAspect::new(wide, high), thumb_painter(thumbs, source, filter))
|
||||
});
|
||||
for event in out.response.events {
|
||||
if let CollectionEvent::Activate(key) = event {
|
||||
|
||||
@@ -9,8 +9,8 @@ use std::time::Duration;
|
||||
use craft_behavior::PixelSize;
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_imaging::ui::filter_gallery::{
|
||||
EffectChange, EffectLayer, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, FilterGallerySession, FilterGallerySource,
|
||||
FilterGalleryWorkspace, GalleryFilter, GalleryThumb,
|
||||
EffectChange, EffectLayer, EffectParameters, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, FilterGallerySession,
|
||||
FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, FilterTreeLayout, GalleryFilter, GalleryThumb, SessionField,
|
||||
};
|
||||
use craft_imaging::ui::wide_angle::PreviewDone;
|
||||
use craft_ui::canvas::{PixelRect, RasterSource};
|
||||
@@ -18,7 +18,8 @@ use craft_ui::contract::{Bind, Job};
|
||||
use craft_ui::dialog::{FullWindowWorkspace as _, WorkspaceCx};
|
||||
use craft_ui::patterns::form_dialogs::{Param, ParamKind};
|
||||
use craft_ui::primitives::Revision;
|
||||
use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource};
|
||||
use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use craft_ui::runtime::requests::{PathKind, PathRequest};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::value_drag::SliderScale;
|
||||
use egui::{Color32, ColorImage, Key, Modifiers, Vec2};
|
||||
@@ -30,17 +31,21 @@ struct Catalog;
|
||||
|
||||
impl Catalog {
|
||||
fn all() -> Vec<GalleryFilter> {
|
||||
let filter =
|
||||
|key: &str, params: Vec<Param>, uses_colors: bool| GalleryFilter::new(key, key.to_owned(), "artistic", params).uses_colors(uses_colors);
|
||||
let filter = |key: &str, category: &str, params: Vec<Param>, uses_colors: bool| {
|
||||
GalleryFilter::new(key, key.to_owned(), category, params).uses_colors(uses_colors)
|
||||
};
|
||||
vec![
|
||||
filter("cutout", Param::parse_list(r#"{"levels":2..8=6,"mode":"soft|hard","edges":bool}"#), false),
|
||||
filter("sponge", Param::parse_list(r#"{"size":0..40=2}"#), true),
|
||||
filter("cutout", "artistic", Param::parse_list(r#"{"levels":2..8=6,"mode":"soft|hard","edges":bool}"#), false),
|
||||
filter("sponge", "artistic", Param::parse_list(r#"{"size":0..40=2}"#), true),
|
||||
filter("chalk", "sketch", Param::parse_list(r#"{"detail":0..20=1}"#), false),
|
||||
filter(
|
||||
"neon",
|
||||
"artistic",
|
||||
vec![
|
||||
Param::new("glowSize", "Glow Size", ParamKind::range(-24.0, 24.0, 5.0, SliderScale::default())),
|
||||
Param::new("glowColor", "Glow Color", ParamKind::color(Some([1.0, 0.0, 0.5]))),
|
||||
Param::new("note", "Note", ParamKind::text("x")),
|
||||
Param::new("texturePath", "Texture", ParamKind::text("")).browse(PathKind::Folder),
|
||||
],
|
||||
false,
|
||||
),
|
||||
@@ -50,7 +55,12 @@ impl Catalog {
|
||||
|
||||
impl FilterCatalog for Catalog {
|
||||
fn categories(&self) -> Vec<FilterCategory> {
|
||||
vec![FilterCategory::new("artistic", "Artistic", Self::all().into_iter().map(|filter| filter.key).collect())]
|
||||
let keys = |keys: &[&str]| keys.iter().map(|key| (*key).to_owned()).collect();
|
||||
vec![
|
||||
FilterCategory::new("artistic", "Artistic", keys(&["cutout", "sponge", "neon"])),
|
||||
FilterCategory::new("sketch", "Sketch", keys(&["chalk"])),
|
||||
FilterCategory::new("empty", "Empty", Vec::new()),
|
||||
]
|
||||
}
|
||||
|
||||
fn filter(&self, key: &str) -> Option<GalleryFilter> {
|
||||
@@ -197,5 +207,151 @@ fn gallery_undo_by_key_clamps_the_selection_and_reports_select_once() {
|
||||
|
||||
// The app answers a color request by key and `Srgba`: the selected effect's field takes it as one undo step.
|
||||
|
||||
fn host() -> Arc<Host> {
|
||||
Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).build())
|
||||
}
|
||||
|
||||
// A Browse press is reported in the pass it happens, once, with the row's key.
|
||||
#[trial]
|
||||
fn a_browse_press_in_the_settings_is_reported_once() {
|
||||
let layer = FilterGallerySession::new("neon", &Catalog).effects[0].clone();
|
||||
let requests: Rc<RefCell<Vec<PathRequest>>> = Rc::new(RefCell::new(Vec::new()));
|
||||
let sink = requests.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let index = FilterIndex::of(&Catalog);
|
||||
sink.borrow_mut().extend(EffectParameters::new(0, &layer, &index).show(ui).path);
|
||||
});
|
||||
fixture.host(host());
|
||||
fixture.room(Vec2::new(400.0, 500.0)).settle();
|
||||
assert!(requests.borrow().is_empty());
|
||||
let browse = fixture.by_label("Browse…").expect("the Browse button");
|
||||
fixture.click(&browse).settle();
|
||||
assert_eq!(requests.borrow().iter().map(|request| request.key.as_str()).collect::<Vec<_>>(), ["texturePath"]);
|
||||
fixture.idle(3);
|
||||
assert_eq!(requests.borrow().len(), 1, "no later pass reports the press again");
|
||||
}
|
||||
|
||||
// Undo restores snapshots with their ids, so an id is never issued twice; moves and edits keep a layer's id, a copy gets
|
||||
// its own, and equality ignores ids.
|
||||
#[trial]
|
||||
fn layer_ids_survive_moves_and_a_copy_gets_its_own() {
|
||||
let mut session = FilterGallerySession::new("cutout", &Catalog);
|
||||
let mut selected = 0;
|
||||
let first = session.effects[0].id;
|
||||
assert!(session.apply(EffectChange::Add, &Catalog, &mut selected));
|
||||
let copy = session.effects[1].id;
|
||||
assert_ne!(first, copy);
|
||||
assert!(session.apply(EffectChange::set_filter(1, "sponge"), &Catalog, &mut selected));
|
||||
assert_eq!(session.position(copy), Some(1), "a new filter keeps the layer");
|
||||
let neon = Catalog.filter("neon").expect("neon").defaults();
|
||||
assert!(session.apply(EffectChange::with_fields(1, neon), &Catalog, &mut selected));
|
||||
assert!(session.apply(EffectChange::set_visible(1, false), &Catalog, &mut selected));
|
||||
assert_eq!(session.position(copy), Some(1), "fields and the eye keep the layer");
|
||||
assert!(session.apply(EffectChange::move_to(1, 0), &Catalog, &mut selected));
|
||||
assert_eq!((session.position(copy), session.position(first)), (Some(0), Some(1)));
|
||||
assert!(session.apply(EffectChange::Delete, &Catalog, &mut selected));
|
||||
assert_eq!((session.position(copy), session.position(first)), (None, Some(0)), "a deleted layer has no place");
|
||||
|
||||
let incoming = FilterGallerySession::new("neon", &Catalog);
|
||||
assert!(session.apply(EffectChange::Replace { effects: incoming.effects.clone() }, &Catalog, &mut selected));
|
||||
assert_ne!(session.effects[0].id, incoming.effects[0].id, "a replacement gets fresh ids");
|
||||
let (one, two) = (FilterGallerySession::new("cutout", &Catalog), FilterGallerySession::new("cutout", &Catalog));
|
||||
assert_ne!(one.effects[0].id, two.effects[0].id);
|
||||
assert_eq!(one, two, "equality is by content");
|
||||
|
||||
let mut rig = rig(FilterGallerySession::new("cutout", &Catalog), true);
|
||||
let add = rig.fixture.by_label("New effect layer").expect("the stack offers New");
|
||||
rig.fixture.click(&add).settle();
|
||||
let undone = rig.workspace.borrow().session().effects[1].id;
|
||||
rig.fixture.key(Key::Z, Modifiers::COMMAND).settle();
|
||||
assert_eq!(rig.workspace.borrow().session().effects.len(), 1);
|
||||
rig.fixture.click(&add).settle();
|
||||
assert_ne!(rig.workspace.borrow().session().effects[1].id, undone, "an undone layer's id is not reissued");
|
||||
}
|
||||
|
||||
// The lists layout: a press on a category picks its first filter (the current category's press changes nothing), a
|
||||
// press or Enter on a filter row picks it, and a category without filters is not listed.
|
||||
#[trial]
|
||||
fn the_lists_layout_picks_a_categorys_first_filter() {
|
||||
let current = Rc::new(RefCell::new("sponge".to_owned()));
|
||||
let picks: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
|
||||
let (now, sink) = (current.clone(), picks.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let index = FilterIndex::of(&Catalog);
|
||||
let thumbs = Thumbnails::<GalleryThumb>::in_context(ui.ctx(), "trial-tree-thumbs", ThumbnailOptions::default());
|
||||
let selected = now.borrow().clone();
|
||||
let picked = FilterTree::new(&index, &selected, &thumbs, &FakeThumbSource::<GalleryThumb>::new()).layout(FilterTreeLayout::Lists).show(ui).picked;
|
||||
if let Some(filter) = picked {
|
||||
*now.borrow_mut() = filter.clone();
|
||||
sink.borrow_mut().push(filter);
|
||||
}
|
||||
});
|
||||
fixture.host(host());
|
||||
fixture.room(Vec2::new(500.0, 400.0)).settle();
|
||||
assert!(fixture.by_label("Empty").is_none(), "a category without filters is not listed");
|
||||
|
||||
let artistic = fixture.by_label("Artistic").expect("the first category");
|
||||
fixture.click(&artistic).settle();
|
||||
assert!(picks.borrow().is_empty(), "the current filter's category is already selected");
|
||||
|
||||
let neon = fixture.by_label("neon").expect("a filter row");
|
||||
fixture.click(&neon).settle();
|
||||
assert_eq!(*picks.borrow(), ["neon"]);
|
||||
picks.borrow_mut().clear();
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(*picks.borrow(), ["neon"], "Enter picks the focused filter row");
|
||||
picks.borrow_mut().clear();
|
||||
|
||||
let sketch = fixture.by_label("Sketch").expect("the second category");
|
||||
fixture.click(&sketch).settle();
|
||||
assert_eq!(*picks.borrow(), ["chalk"], "a category press picks its first filter");
|
||||
picks.borrow_mut().clear();
|
||||
let artistic = fixture.by_label("Artistic").expect("the first category");
|
||||
fixture.click(&artistic).settle();
|
||||
assert_eq!(*picks.borrow(), ["cutout"]);
|
||||
}
|
||||
|
||||
// The automation vocabulary: each field's change, the selection clamp, `false` as nothing, and the refusals.
|
||||
#[trial]
|
||||
fn session_field_change_maps_each_automation_field_and_refuses_the_rest() {
|
||||
let mut session = FilterGallerySession::new("cutout", &Catalog);
|
||||
let mut selected = 0;
|
||||
session.apply(EffectChange::Add, &Catalog, &mut selected);
|
||||
session.apply(EffectChange::set_filter(1, "neon"), &Catalog, &mut selected);
|
||||
let run = |field: &str, value: serde_json::Value| session.field_change(&Catalog, 1, field, &value);
|
||||
let change = |change: EffectChange| Ok(Some(SessionField::Change(change)));
|
||||
|
||||
assert_eq!(run("select", serde_json::json!(9)), Ok(Some(SessionField::Select(1))));
|
||||
assert_eq!(run("add", serde_json::json!(true)), change(EffectChange::Add));
|
||||
assert_eq!(run("add", serde_json::json!(false)), Ok(None));
|
||||
assert_eq!(run("delete", serde_json::json!(true)), change(EffectChange::Delete));
|
||||
assert_eq!(run("delete", serde_json::json!(false)), Ok(None));
|
||||
assert_eq!(run("toggle", serde_json::json!(1)), change(EffectChange::set_visible(1, false)));
|
||||
assert_eq!(run("move", serde_json::json!({"from": 0, "to": 1})), change(EffectChange::move_to(0, 1)));
|
||||
assert_eq!(run("filter", serde_json::json!("sponge")), change(EffectChange::set_filter(1, "sponge")));
|
||||
assert!(matches!(
|
||||
run("params", serde_json::json!({"glowSize": 3.0})),
|
||||
Ok(Some(SessionField::Change(EffectChange::Fields { index: 1, .. })))
|
||||
));
|
||||
let layers = serde_json::to_value(&session.effects).expect("layers serialise");
|
||||
assert!(matches!(run("effects", layers.clone()), Ok(Some(SessionField::Change(EffectChange::Replace { .. })))));
|
||||
|
||||
let mut unknown_filter = layers;
|
||||
unknown_filter[0]["filter"] = serde_json::json!("nope");
|
||||
for (field, value) in [
|
||||
("bogus", serde_json::json!(1)),
|
||||
("toggle", serde_json::json!(7)),
|
||||
("move", serde_json::json!({"from": 0, "to": 5})),
|
||||
("filter", serde_json::json!("nope")),
|
||||
("add", serde_json::json!("yes")),
|
||||
("select", serde_json::json!("last")),
|
||||
("params", serde_json::json!({"glowSize": "wide"})),
|
||||
("effects", serde_json::json!([])),
|
||||
("effects", unknown_filter),
|
||||
] {
|
||||
assert!(run(field, value.clone()).is_err(), "{field} = {value} is refused");
|
||||
}
|
||||
}
|
||||
|
||||
// OK and Cancel sit at the top of the settings column, in the platform's order, over the Filter select and the
|
||||
// stack.
|
||||
|
||||
Reference in New Issue
Block a user