mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 15:44:26 +00:00
ui-patterns: hosted parameter dialogs open their values at open; custom rows declare companions and an opening value
This commit is contained in:
@@ -741,7 +741,7 @@ type Build = dyn for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send;
|
||||
/// [`answer_ok`](HostedParamDialog::answer_ok).
|
||||
///
|
||||
/// ```ignore
|
||||
/// host.open(HostedParamDialog::new("radial-blur", DialogFields::new(), |fields| {
|
||||
/// host.open(HostedParamDialog::new(ctx, "radial-blur", DialogFields::new(), |fields| {
|
||||
/// ParamDialog::new("radial-blur", "Radial Blur", params.clone()).values(Bind::bound(fields))
|
||||
/// }));
|
||||
/// // each pass: if dialog.is_previewing() { dialog.set_preview(Some(render(dialog.fields()))) }
|
||||
@@ -751,8 +751,6 @@ pub struct HostedParamDialog {
|
||||
key: String,
|
||||
instance: Option<DialogId>,
|
||||
fields: DialogFields,
|
||||
/// The values were opened (remembered values and defaults loaded) by the first show, OK or set.
|
||||
opened: bool,
|
||||
build: Box<Build>,
|
||||
requests: HostRequests,
|
||||
/// Whether the dialog is open: bound to the dialog's `opened` prop, so the dialog's own open state, kept under
|
||||
@@ -799,20 +797,26 @@ struct Refused {
|
||||
}
|
||||
|
||||
impl HostedParamDialog {
|
||||
/// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values.
|
||||
/// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values. The
|
||||
/// values open now, as a `ParamDialog`'s first pass opens its own: the remembered values `ctx` keeps over
|
||||
/// `fields`, then the defaults of the keys still missing. Automation reads and sets these values before any pass.
|
||||
pub fn new(
|
||||
ctx: &Context,
|
||||
key: impl Into<String>,
|
||||
fields: DialogFields,
|
||||
mut fields: DialogFields,
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
) -> Self {
|
||||
let key = key.into();
|
||||
let ParamDialog { params, remember, patterns, .. } = build(&mut fields);
|
||||
let (params, patterns) = (params.into_owned(), patterns.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);
|
||||
HostedParamDialog {
|
||||
id: dialog_id(key.as_str()),
|
||||
key,
|
||||
instance: None,
|
||||
opening: fields.clone(),
|
||||
fields,
|
||||
opened: false,
|
||||
opening: DialogFields::default(),
|
||||
build: Box::new(build),
|
||||
requests: HostRequests::new(),
|
||||
open: true,
|
||||
@@ -828,11 +832,12 @@ impl HostedParamDialog {
|
||||
/// A hosted command form: the same as [`new`](HostedParamDialog::new), with `build` making a
|
||||
/// [`ParamDialog::command`].
|
||||
pub fn command(
|
||||
ctx: &Context,
|
||||
key: impl Into<String>,
|
||||
fields: DialogFields,
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
) -> Self {
|
||||
Self::new(key, fields, build)
|
||||
Self::new(ctx, key, fields, build)
|
||||
}
|
||||
|
||||
/// Names this dialog among others made with the same key (one per document, say), so they keep separate state.
|
||||
@@ -989,32 +994,23 @@ impl HostedParamDialog {
|
||||
pub fn cancel_requests(&mut self) {
|
||||
self.requests.cancel();
|
||||
}
|
||||
|
||||
/// Opens the values once, as a `ParamDialog`'s first pass does, before the first show, OK or set reads them.
|
||||
fn open(&mut self, ctx: &Context) {
|
||||
if std::mem::replace(&mut self.opened, true) {
|
||||
return;
|
||||
}
|
||||
let ParamDialog { params, remember, patterns, .. } = (self.build)(&mut self.fields);
|
||||
let (params, patterns) = (params.into_owned(), patterns.into_owned());
|
||||
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
|
||||
ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut self.fields);
|
||||
self.opening = self.fields.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `value` against the row `field` of `params` and sets it in `fields`, as the user editing the row would; `Err`
|
||||
/// says why the row refused (`FieldRefusal`). The field is a row's key or its unit key; a Files row takes a
|
||||
/// `{files, folder, useFolder}` object and sets its two companion keys with it. Every dialog built on `Param`s sets
|
||||
/// its fields through this one rule.
|
||||
/// says why the row refused (`FieldRefusal`). The field is a row's key, its unit key or a custom row's companion key
|
||||
/// ([`Param::companions`]); a Files row takes a `{files, folder, useFolder}` object and sets its two companion keys with
|
||||
/// it. Every dialog built on `Param`s sets its fields through this one rule.
|
||||
pub fn set_param_field(params: &[Param], fields: &mut DialogFields, field: &str, value: Value) -> Result<(), String> {
|
||||
let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field)) else {
|
||||
let companion = |param: &Param| matches!(¶m.kind, ParamKind::Custom(row) if row.has_companion(field));
|
||||
let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field) || companion(param)) else {
|
||||
return Err(FieldRefusal::Unknown.message(field));
|
||||
};
|
||||
if !param.visible(fields) || !param.enabled(fields) {
|
||||
return Err(FieldRefusal::Inactive.message(field));
|
||||
}
|
||||
let writes = if param.key != field {
|
||||
let writes = if companion(param) {
|
||||
Some(vec![(field.to_owned(), Some(FieldValue::Json(value.clone())).filter(|_| !value.is_null()))])
|
||||
} else if param.key != field {
|
||||
value.as_str().map(|unit| vec![(field.to_owned(), Some(FieldValue::Text(unit.to_owned())))])
|
||||
} else if matches!(param.kind, ParamKind::Files { .. }) {
|
||||
read_files(param, &value)
|
||||
@@ -1081,7 +1077,6 @@ impl StackDialog for HostedParamDialog {
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ParamResult>> {
|
||||
let measuring = crate::runtime::measure::active(ui.ctx());
|
||||
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
|
||||
self.open(ui.ctx());
|
||||
let finish = self.held.as_ref().is_some_and(|held| held.accepted);
|
||||
// A measuring run keeps the centre: the real run of the pass takes it.
|
||||
let centre = if measuring { self.centre } else { self.centre.take() };
|
||||
@@ -1152,8 +1147,7 @@ impl StackDialog for HostedParamDialog {
|
||||
/// Answers OK as the button does: none while OK is disabled. The result keeps what a remembering dialog saves. A
|
||||
/// held dialog files the answer for the host, as its button does, and answers none; once the host accepted the
|
||||
/// held answer, it answers that.
|
||||
fn confirm(&mut self, ctx: &Context) -> Option<ParamResult> {
|
||||
self.open(ctx);
|
||||
fn confirm(&mut self, _: &Context) -> Option<ParamResult> {
|
||||
if self.held.as_ref().is_some_and(|held| held.accepted) {
|
||||
return self.held.take().map(|held| held.result);
|
||||
}
|
||||
@@ -1181,8 +1175,7 @@ impl StackDialog for HostedParamDialog {
|
||||
|
||||
/// Keeps `value` when the row `field` names (a parameter or its unit choice) is shown, takes input, and takes
|
||||
/// the value ([`set_param_field`]).
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
self.open(ctx);
|
||||
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
let params = (self.build)(&mut self.fields).params.into_owned();
|
||||
let before = self.fields.clone();
|
||||
set_param_field(¶ms, &mut self.fields, field, value)?;
|
||||
|
||||
@@ -85,7 +85,7 @@ const REFUSAL: &str = "The radius is too large for this layer.";
|
||||
fn hosted_param_dialog_with_a_refused_ok(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let ctx = ui.ctx().clone();
|
||||
let open = move || {
|
||||
let mut dialog = HostedParamDialog::new("blur", DialogFields::new(), |fields| {
|
||||
let mut dialog = HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| {
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).values(Bind::bound(fields))
|
||||
})
|
||||
.held_ok();
|
||||
|
||||
@@ -719,14 +719,15 @@ fn jpeg_params(words: &FormatOptionsWords, options: JpegOptions) -> Vec<Param> {
|
||||
vec![
|
||||
Param::section(words.image_options.clone()),
|
||||
Param::custom(QUALITY, words.quality.clone(), move |ui, fields, _| quality_rows(ui, fields, &quality_name, &preset_name, &presets, start))
|
||||
.opens_with(FieldValue::Int(i64::from(start)))
|
||||
.full_width(),
|
||||
Param::new(FORMAT, words.format_options.clone(), ParamKind::radio(formats, Some(options.format.id().to_owned()))),
|
||||
]
|
||||
}
|
||||
|
||||
/// The quality in `fields`, else `start`, the quality the dialog opened with.
|
||||
/// The quality in `fields`, in whatever form it was set, else `start`, the quality the dialog opened with.
|
||||
fn quality_of(fields: &DialogFields, start: u8) -> u8 {
|
||||
fields.int(QUALITY).map_or(start, |quality| quality.clamp(0, i64::from(MAX_QUALITY)) as u8)
|
||||
fields.number(QUALITY).filter(|quality| quality.is_finite()).map_or(start, |quality| quality.round().clamp(0.0, f64::from(MAX_QUALITY)) as u8)
|
||||
}
|
||||
|
||||
/// The quality rows: the field named `name` and the preset list on one line, the slider across the form under them.
|
||||
|
||||
@@ -129,10 +129,14 @@ impl DialogFields {
|
||||
self.values.contains_key(key)
|
||||
}
|
||||
|
||||
// The scalar readers also read the `Json` form of their value, which automation stores for a custom row's keys
|
||||
// (`Param::custom`): one read whatever form the value was set in.
|
||||
|
||||
/// `Bool`, else `None`.
|
||||
pub fn bool(&self, key: &str) -> Option<bool> {
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Bool(b) => Some(*b),
|
||||
FieldValue::Json(value) => value.as_bool(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -142,15 +146,18 @@ impl DialogFields {
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Number(n) => Some(*n),
|
||||
FieldValue::Int(i) => Some(*i as f64),
|
||||
FieldValue::Json(value) => value.as_f64(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Int`, or a whole `Number`.
|
||||
pub fn int(&self, key: &str) -> Option<i64> {
|
||||
let whole = |n: f64| (n.fract() == 0.0 && n.abs() < 9.0e15).then_some(n as i64);
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Int(i) => Some(*i),
|
||||
FieldValue::Number(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Some(*n as i64),
|
||||
FieldValue::Number(n) => whole(*n),
|
||||
FieldValue::Json(value) => value.as_i64().or_else(|| value.as_f64().and_then(whole)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -159,6 +166,7 @@ impl DialogFields {
|
||||
pub fn text(&self, key: &str) -> Option<&str> {
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Text(s) => Some(s),
|
||||
FieldValue::Json(value) => value.as_str(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -188,14 +196,18 @@ impl DialogFields {
|
||||
}
|
||||
|
||||
/// A `List`, or a `Grid`, `Point` or `Color` as the list of its numbers (the shapes an
|
||||
/// untagged read gives a stored list of numbers, and an empty list). The key may have no
|
||||
/// parameter row: a host keeps its own data under it (a key without a row is not remembered).
|
||||
/// untagged read gives a stored list of numbers, and an empty list), or a `Json` array read as
|
||||
/// those values. The key may have no parameter row: a host keeps its own data under it (a key
|
||||
/// without a row is not remembered).
|
||||
pub fn list(&self, key: &str) -> Option<Cow<'_, [FieldValue]>> {
|
||||
Some(match self.values.get(key)? {
|
||||
FieldValue::List(items) => Cow::Borrowed(items.as_slice()),
|
||||
FieldValue::Grid(cells) => Cow::Owned(cells.iter().map(|c| FieldValue::Int(*c)).collect()),
|
||||
FieldValue::Point(p) => Cow::Owned(p.iter().map(|n| FieldValue::Number(*n)).collect()),
|
||||
FieldValue::Color(c) => Cow::Owned(c.iter().map(|n| FieldValue::Number(f64::from(*n))).collect()),
|
||||
FieldValue::Json(serde_json::Value::Array(items)) => {
|
||||
Cow::Owned(items.iter().map(|item| serde_json::from_value(item.clone())).collect::<Result<_, _>>().ok()?)
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ pub enum ParamKind {
|
||||
/// The text shown; line breaks start new lines.
|
||||
text: Label,
|
||||
},
|
||||
/// A row the host draws: see [`Param::custom`]. It has no value of its own.
|
||||
/// A row the host draws: see [`Param::custom`]. Its value and its companions' are what `draw` keeps.
|
||||
Custom(CustomRow),
|
||||
/// A select of blend modes, each with the Shift+Alt key that picks it.
|
||||
#[non_exhaustive]
|
||||
@@ -288,7 +288,8 @@ impl ParamKind {
|
||||
}
|
||||
ParamKind::Pattern { default } => FieldValue::Text(default.clone()?),
|
||||
ParamKind::Files { open_files, .. } => path_list(open_files),
|
||||
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
|
||||
ParamKind::Custom(row) => row.opens_with.clone()?,
|
||||
ParamKind::ReadOnlyText { .. } | ParamKind::Section => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -316,7 +317,8 @@ impl ParamKind {
|
||||
(ParamKind::Channel { names, .. }, FieldValue::Int(i)) => usize::try_from(*i).is_ok_and(|i| i < names.len()),
|
||||
(ParamKind::Text { .. }, FieldValue::Text(_)) => true,
|
||||
(ParamKind::OptionalNumber { min, max, .. }, v) => number(v).is_some_and(|n| n.is_finite() && n >= *min && n <= *max),
|
||||
(ParamKind::Custom(_), FieldValue::Json(_)) => true,
|
||||
// A custom row keeps whatever its `draw` writes.
|
||||
(ParamKind::Custom(_), _) => true,
|
||||
(ParamKind::Blend { modes, .. }, FieldValue::Text(id)) => modes.iter().any(|(entry, _)| entry.key == *id),
|
||||
(ParamKind::Pattern { .. }, FieldValue::Text(_)) => true,
|
||||
(ParamKind::Files { .. }, v) => is_path_list(v),
|
||||
@@ -328,31 +330,43 @@ impl ParamKind {
|
||||
type CustomDraw = dyn Fn(&mut Ui, &mut DialogFields, &mut CustomContext) -> Response + Send + Sync;
|
||||
|
||||
/// What draws a [`ParamKind::Custom`] row: it gets the row's control cell, the form's values and the row's
|
||||
/// [`CustomContext`], and returns the response the row label names. Equal only to itself.
|
||||
/// [`CustomContext`], and returns the response the row label names. Besides the row's own key, `draw` may keep values
|
||||
/// under its companion keys ([`Param::companions`]). Equal only to a clone of itself with the same value and companions.
|
||||
#[derive(Clone)]
|
||||
pub struct CustomRow(Arc<CustomDraw>);
|
||||
pub struct CustomRow {
|
||||
draw: Arc<CustomDraw>,
|
||||
/// The value the row's key opens with ([`Param::opens_with`]).
|
||||
opens_with: Option<FieldValue>,
|
||||
/// The other keys `draw` keeps values under.
|
||||
companions: Vec<String>,
|
||||
}
|
||||
|
||||
impl CustomRow {
|
||||
/// Wraps `draw`, which draws the row and edits the values it owns through the [`DialogFields`].
|
||||
pub fn new(draw: impl Fn(&mut Ui, &mut DialogFields, &mut CustomContext) -> Response + Send + Sync + 'static) -> Self {
|
||||
Self(Arc::new(draw))
|
||||
Self { draw: Arc::new(draw), opens_with: None, companions: Vec::new() }
|
||||
}
|
||||
|
||||
/// Draws the row.
|
||||
pub(crate) fn draw(&self, ui: &mut Ui, fields: &mut DialogFields, context: &mut CustomContext) -> Response {
|
||||
(self.0)(ui, fields, context)
|
||||
(self.draw)(ui, fields, context)
|
||||
}
|
||||
|
||||
/// Whether `key` is one of the row's companion keys.
|
||||
pub(crate) fn has_companion(&self, key: &str) -> bool {
|
||||
self.companions.iter().any(|companion| companion == key)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CustomRow {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("CustomRow")
|
||||
f.debug_struct("CustomRow").field("opens_with", &self.opens_with).field("companions", &self.companions).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CustomRow {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.0, &other.0)
|
||||
Arc::ptr_eq(&self.draw, &other.draw) && self.opens_with == other.opens_with && self.companions == other.companions
|
||||
}
|
||||
}
|
||||
|
||||
@@ -591,8 +605,10 @@ impl Param {
|
||||
}
|
||||
|
||||
/// A row the host draws. `draw` gets the control cell, the form's values and the row's [`CustomContext`] (to ask
|
||||
/// for the host's colour picker); the row label names the response it returns. The row has no default and
|
||||
/// nothing remembered; `draw` reads and writes [`DialogFields`] under whatever keys it likes.
|
||||
/// for the host's colour picker); the row label names the response it returns. Nothing of the row is remembered;
|
||||
/// it opens with no value unless [`opens_with`](Param::opens_with) gives one. `draw` reads and writes the
|
||||
/// [`DialogFields`] under its key and the keys [`companions`](Param::companions) declares; automation
|
||||
/// (`set_json_field`) sets any of those keys to a JSON value, kept as [`FieldValue::Json`] (`null` removes it).
|
||||
pub fn custom(
|
||||
key: impl Into<String>,
|
||||
label: impl Into<Label>,
|
||||
@@ -601,6 +617,25 @@ impl Param {
|
||||
Self::new(key, label, ParamKind::Custom(CustomRow::new(draw)))
|
||||
}
|
||||
|
||||
/// The value a [`Param::custom`] row's key opens with, as another row opens with its default. Other rows ignore it.
|
||||
#[must_use]
|
||||
pub fn opens_with(mut self, value: impl Into<FieldValue>) -> Self {
|
||||
if let ParamKind::Custom(row) = &mut self.kind {
|
||||
row.opens_with = Some(value.into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The other keys a [`Param::custom`] row keeps values under (Color Lookup's `file` beside its `lut`), so automation
|
||||
/// sets them as it sets the row's own key. Other rows ignore it.
|
||||
#[must_use]
|
||||
pub fn companions(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
|
||||
if let ParamKind::Custom(row) = &mut self.kind {
|
||||
row.companions.extend(keys.into_iter().map(Into::into));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// A row of read-only `text` beside the label, wrapped to the form's width: the user can select and copy it, and
|
||||
/// Tab passes over it. It has no value, so nothing is remembered or in the result. With
|
||||
/// [`full_width`](Param::full_width) it has no label and spans the form (a note over the rows).
|
||||
@@ -792,12 +827,15 @@ impl Param {
|
||||
!self.option().not_remembered
|
||||
}
|
||||
|
||||
/// Whether `value` is one the field `key` of this row can hold: the row's own value, or the unit id of a row with
|
||||
/// units.
|
||||
/// Whether `value` is one the field `key` of this row can hold: the row's own value, the unit id of a row with
|
||||
/// units, a Files row's companions, or a custom row's companion.
|
||||
pub fn accepts(&self, key: &str, value: &FieldValue) -> bool {
|
||||
if self.key == key {
|
||||
return self.kind.fits(value) && self.option_allowed(value);
|
||||
}
|
||||
if let ParamKind::Custom(row) = &self.kind {
|
||||
return row.has_companion(key);
|
||||
}
|
||||
if matches!(self.kind, ParamKind::Files { .. }) {
|
||||
return match value {
|
||||
FieldValue::Text(_) => key == self.folder_key(),
|
||||
|
||||
Reference in New Issue
Block a user