mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
menus-w20: net change of 1 commits
- menus-w20: written by an agent
This commit is contained in:
@@ -1,181 +1,256 @@
|
||||
//! Actions panel menu › Batch…: play the selected action on every file in a
|
||||
//! folder, or on every data set of the open document (`action.batch`).
|
||||
//!
|
||||
//! Fields: `set` and `action` (the action's place), `actionName`, `source` (`folder` or
|
||||
//! `datasets`), `datasetFileNaming`, `folder`, `includeSubdirs`, `destination` (`none`,
|
||||
//! `saveAndClose` or `folder`), `destinationFolder`, `overrideOpen`, `overrideSave`,
|
||||
//! `overrideExport` and `stopOnError`. OK plays the action; a source or destination folder left
|
||||
//! empty, or Data Sets without a document, is an error and the dialog stays open.
|
||||
|
||||
use std::hash::Hash;
|
||||
|
||||
use craft::automation::actions::Action;
|
||||
use craft::host::PickRequest;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::patterns::form_dialogs::PathRow;
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::actions::{ActionDialog, Form, label, merged, set_index};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::file_asks::{self, Owner};
|
||||
use crate::panels::actions::{has_stop, is_ui_step, model};
|
||||
// PLAN: assumed `playback::included_commands(&Action) -> Vec<Value>` (menus-w15) is reachable from here (`pub(crate) mod playback` or a re-export).
|
||||
use crate::panels::actions::playback::included_commands;
|
||||
|
||||
pub const KIND: &str = "actionBatch";
|
||||
const LABEL: f32 = 130.0;
|
||||
/// The key the dialog answers for.
|
||||
const KEY: &str = "actionBatch";
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Batch").into(), body, confirm, ok: Some("OK"), min_width: 420.0, max_width: Some(460.0), ..DialogSpec::FORM };
|
||||
/// What Batch plays on.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum BatchSource {
|
||||
/// Every file of a folder.
|
||||
#[default]
|
||||
#[serde(rename = "folder")]
|
||||
Folder,
|
||||
/// Every data set of the open document.
|
||||
#[serde(rename = "datasets")]
|
||||
DataSets,
|
||||
}
|
||||
|
||||
/// Open the Batch dialog for the selected action (`set`, `action` indexes into `action_sets`).
|
||||
/// What Batch does with each file or data set when the action is done.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BatchDestination {
|
||||
/// Leaves it open.
|
||||
None,
|
||||
/// Saves it and closes it.
|
||||
SaveAndClose,
|
||||
/// Saves a copy in a folder.
|
||||
#[default]
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// How the files of a data set batch into a folder are named.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DatasetNaming {
|
||||
/// The document's name and a number.
|
||||
#[default]
|
||||
FileNumber,
|
||||
/// The document's name and the data set's.
|
||||
FileDataSetName,
|
||||
/// The data set's name.
|
||||
DataSetName,
|
||||
}
|
||||
|
||||
/// What Batch edits.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BatchFields {
|
||||
/// What the action plays on.
|
||||
pub source: BatchSource,
|
||||
/// The names of the files a data set batch saves into a folder.
|
||||
pub dataset_file_naming: DatasetNaming,
|
||||
/// The source folder.
|
||||
pub folder: String,
|
||||
/// Whether the source folder's subfolders play too.
|
||||
pub include_subdirs: bool,
|
||||
/// What happens to each file or data set afterwards.
|
||||
pub destination: BatchDestination,
|
||||
/// The destination folder.
|
||||
pub destination_folder: String,
|
||||
/// Whether the action's Open steps open the batch's file instead of their own.
|
||||
pub override_open: bool,
|
||||
/// Whether the action's Save steps save into the destination folder.
|
||||
pub override_save: bool,
|
||||
/// Whether the action's Export steps export into the destination folder.
|
||||
pub override_export: bool,
|
||||
/// Whether an error ends the batch.
|
||||
pub stop_on_error: bool,
|
||||
}
|
||||
|
||||
impl Default for BatchFields {
|
||||
fn default() -> Self {
|
||||
BatchFields {
|
||||
source: BatchSource::default(),
|
||||
dataset_file_naming: DatasetNaming::default(),
|
||||
folder: String::new(),
|
||||
include_subdirs: false,
|
||||
destination: BatchDestination::default(),
|
||||
destination_folder: String::new(),
|
||||
override_open: true,
|
||||
override_save: true,
|
||||
override_export: true,
|
||||
stop_on_error: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch asks for no check of its own: its refusals come with OK, from the command.
|
||||
fn check(_: &BatchFields) -> Option<Label> {
|
||||
None
|
||||
}
|
||||
|
||||
/// A folder row of the dialog.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Folder {
|
||||
/// The source folder.
|
||||
Source,
|
||||
/// The destination folder.
|
||||
Destination,
|
||||
}
|
||||
|
||||
/// The Batch dialog on the dialog host.
|
||||
pub struct BatchDialog {
|
||||
id: DialogId,
|
||||
/// The index of the action's set.
|
||||
pub set: usize,
|
||||
/// The index of the action in its set.
|
||||
pub action: usize,
|
||||
action_name: String,
|
||||
form: Form<BatchFields>,
|
||||
/// Whether the batch would save every data set over the same file; the pump reads the action's
|
||||
/// steps and gives the answer.
|
||||
pub(crate) warn: bool,
|
||||
/// The Browse presses the pump has not filed yet.
|
||||
asked: Vec<Folder>,
|
||||
}
|
||||
|
||||
impl BatchDialog {
|
||||
/// The values the controls edit.
|
||||
pub(crate) fn fields(&self) -> &BatchFields {
|
||||
&self.form.values
|
||||
}
|
||||
|
||||
/// The Browse presses since the last call.
|
||||
pub(crate) fn take_asked(&mut self) -> Vec<Folder> {
|
||||
std::mem::take(&mut self.asked)
|
||||
}
|
||||
|
||||
/// Writes the folder the picker answered into its row.
|
||||
pub(crate) fn set_folder(&mut self, which: Folder, path: String) {
|
||||
match which {
|
||||
Folder::Source => self.form.values.folder = path,
|
||||
Folder::Destination => self.form.values.destination_folder = path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the Batch dialog for the selected action (`set`, `action` index the sets and the set's actions).
|
||||
pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result<Value, String> {
|
||||
let a = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)).ok_or("no such action")?;
|
||||
let a = model::flat(&app.ui.actions, set, action).and_then(|flat| app.ui.actions.action(flat)).ok_or("no such action")?;
|
||||
if a.steps.is_empty() {
|
||||
return Err("the action has no steps".into());
|
||||
}
|
||||
if a.steps.iter().enumerate().all(|(i, _)| a.excluded_steps.contains(&i)) {
|
||||
if a.enabled_steps().next().is_none() {
|
||||
return Err("the action has no included steps".into());
|
||||
}
|
||||
refuse_steps(&a.included_commands())?;
|
||||
let name = a.name.clone();
|
||||
app.ui.dialog = Some(Dialog::new(KIND, initial_fields(set, action, &name)));
|
||||
refuse_steps(&included_commands(a))?;
|
||||
let dialog = BatchDialog {
|
||||
id: dialog_id(KEY),
|
||||
set,
|
||||
action,
|
||||
action_name: a.name.clone(),
|
||||
form: Form::new(BatchFields::default(), check),
|
||||
warn: false,
|
||||
asked: Vec::new(),
|
||||
};
|
||||
super::actions::open(app, dialog)?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Err when the included steps `commands` hold a step that Batch does not play: a stop, or a View
|
||||
/// menu step, which acts on a document window ([`crate::panels::actions::is_ui_step`]).
|
||||
/// menu step, which acts on a document window ([`is_ui_step`]).
|
||||
fn refuse_steps(commands: &[Value]) -> Result<(), String> {
|
||||
if crate::panels::actions::has_stop(commands) {
|
||||
if has_stop(commands) {
|
||||
return Err("Batch cannot play an action with a stop".into());
|
||||
}
|
||||
if commands.iter().any(crate::panels::actions::is_ui_step) {
|
||||
if commands.iter().any(is_ui_step) {
|
||||
return Err("Batch cannot play an action with a View menu step".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn initial_fields(set: usize, action: usize, name: &str) -> Value {
|
||||
json!({
|
||||
"set": set,
|
||||
"action": action,
|
||||
"actionName": name,
|
||||
"source": "folder",
|
||||
"datasetFileNaming": "fileNumber",
|
||||
"folder": "",
|
||||
"includeSubdirs": false,
|
||||
"destination": "folder",
|
||||
"destinationFolder": "",
|
||||
"overrideOpen": true,
|
||||
"overrideSave": true,
|
||||
"overrideExport": true,
|
||||
"stopOnError": true,
|
||||
})
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.label(egui::RichText::new(d.str("actionName")).color(t.text_strong));
|
||||
ui.add_space(8.0);
|
||||
|
||||
form::choice(ui, d, "source", "Play:", (LABEL, 200.0), &[("folder", "Folder"), ("datasets", "Data Sets")]);
|
||||
let source = d.str("source");
|
||||
if source == "folder" {
|
||||
widgets::label_row(ui, tl!("Source Folder:"), LABEL, |ui| {
|
||||
form::text(ui, d, "folder", 200.0);
|
||||
if app.services.pick_folder.is_some() && ui.button(tl!("Choose…")).clicked() {
|
||||
crate::picks::folder_field(app, d, "folder");
|
||||
}
|
||||
});
|
||||
form::check(ui, d, "includeSubdirs", "Include All Subdirectories");
|
||||
} else {
|
||||
ui.label(egui::RichText::new(tl!("Uses every data set of the open document.")).size(11.5).color(t.text_dim));
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
|
||||
form::choice(ui, d, "destination", "Destination:", (LABEL, 200.0), &[("none", "None"), ("saveAndClose", "Save and Close"), ("folder", "Folder")]);
|
||||
if d.str("destination") == "folder" {
|
||||
widgets::label_row(ui, tl!("Destination Folder:"), LABEL, |ui| {
|
||||
form::text(ui, d, "destinationFolder", 200.0);
|
||||
if app.services.pick_folder.is_some() && ui.button(tl!("Choose…")).clicked() {
|
||||
crate::picks::folder_field(app, d, "destinationFolder");
|
||||
}
|
||||
});
|
||||
}
|
||||
if names_data_set_files(d) {
|
||||
form::choice(
|
||||
ui,
|
||||
d,
|
||||
"datasetFileNaming",
|
||||
"File Name:",
|
||||
(LABEL, 200.0),
|
||||
&[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")],
|
||||
);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
widgets::subheader(ui, tl!("Overrides"));
|
||||
form::check(ui, d, "overrideOpen", "Override Action \"Open\" Commands");
|
||||
form::check(ui, d, "overrideSave", "Override Action \"Save\" Commands");
|
||||
form::check(ui, d, "overrideExport", "Override Action \"Export\" Commands");
|
||||
form::check(ui, d, "stopOnError", "Stop on Errors");
|
||||
if overwrites_one_file(app, d) {
|
||||
ui.add_space(6.0);
|
||||
ui.label(egui::RichText::new(tl!("Each data set saves over the same file, which keeps only the last data set.")).size(11.5).color(t.warning));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the batch the dialog would run saves every data set over the same file
|
||||
/// ([`vectorcraft_engine::cmd::fileio::batch_overwrites_one_file`]).
|
||||
fn overwrites_one_file(app: &VectorcraftApp, d: &Dialog) -> bool {
|
||||
let set = d.fields.get("set").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let action = d.fields.get("action").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let steps = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)).map_or(&[][..], |a| &a.steps[..]);
|
||||
let commands = steps.iter().map(|(c, p)| json!({"command": c, "params": p})).collect();
|
||||
vectorcraft_engine::cmd::fileio::batch_overwrites_one_file(&app.session, ¶ms(d, "", commands))
|
||||
pub(crate) fn overwrites_one_file(app: &VectorcraftApp, set: usize, action: usize, fields: &BatchFields) -> bool {
|
||||
let steps = model::flat(&app.ui.actions, set, action).and_then(|flat| app.ui.actions.action(flat)).map_or(&[][..], |a| a.steps.as_slice());
|
||||
let commands = steps.iter().map(|step| json!({"command": step.command, "params": step.params})).collect();
|
||||
vectorcraft_engine::cmd::fileio::batch_overwrites_one_file(&app.session, ¶ms(fields, "", commands))
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let set = d.fields.get("set").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let action = d.fields.get("action").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let a = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)).ok_or("no such action")?.clone();
|
||||
let commands = a.included_commands();
|
||||
if commands.is_empty() {
|
||||
return Err("the action has no included steps".into());
|
||||
}
|
||||
refuse_steps(&commands)?;
|
||||
let source = d.str("source");
|
||||
if source == "folder" && d.str("folder").trim().is_empty() {
|
||||
return Err("choose a source folder".into());
|
||||
}
|
||||
let destination = d.str("destination");
|
||||
if destination == "folder" && d.str("destinationFolder").trim().is_empty() {
|
||||
return Err("choose a destination folder".into());
|
||||
}
|
||||
if source == "datasets" && app.session.active().is_none() {
|
||||
return Err("open a document with data sets".into());
|
||||
}
|
||||
let params = params(d, &a.name, commands);
|
||||
let r = app.replay("action.batch", params)?;
|
||||
app.ui.dialog = None;
|
||||
let count = r["count"].as_u64().unwrap_or(0);
|
||||
let failed = r["failed"].as_u64().unwrap_or(0);
|
||||
if failed > 0 {
|
||||
app.status(format!("Batch: {count} processed, {failed} failed"));
|
||||
} else {
|
||||
app.status(format!("Batch: {count} processed"));
|
||||
}
|
||||
Ok(r)
|
||||
/// Files the request for the folder behind `which`; the answer goes into the open dialog's row.
|
||||
// PLAN: PathRow shows Browse whether or not the host offers pickers; `file_asks::ask` says so when it cannot ask.
|
||||
pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) {
|
||||
let title = match which {
|
||||
Folder::Source => crate::i18n::t("Source Folder"),
|
||||
Folder::Destination => crate::i18n::t("Destination Folder"),
|
||||
};
|
||||
file_asks::ask(app, PickRequest::folder("batch").title(title), Owner::Free, move |app, picked| {
|
||||
if let Some(path) = picked.paths().first()
|
||||
&& let Some(dialogs) = app.dialogs()
|
||||
{
|
||||
let path = path.to_string_lossy().into_owned();
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<BatchDialog>() {
|
||||
dialog.set_folder(which, path);
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(Value::Null)
|
||||
});
|
||||
}
|
||||
|
||||
fn params(d: &Dialog, action_name: &str, commands: Vec<Value>) -> Value {
|
||||
let source = d.str("source");
|
||||
let destination = d.str("destination");
|
||||
/// The params of `action.batch` for the choices made: the folder, the file naming and the
|
||||
/// destination folder only where the choices use them.
|
||||
fn params(fields: &BatchFields, action_name: &str, commands: Vec<Value>) -> Value {
|
||||
let mut params = json!({
|
||||
"commands": commands,
|
||||
"label": action_name,
|
||||
"source": source,
|
||||
"destination": destination,
|
||||
"overrideOpen": d.bool("overrideOpen"),
|
||||
"overrideSave": d.bool("overrideSave"),
|
||||
"overrideExport": d.bool("overrideExport"),
|
||||
"stopOnError": d.bool("stopOnError"),
|
||||
"includeSubdirs": d.bool("includeSubdirs"),
|
||||
"source": fields.source,
|
||||
"destination": fields.destination,
|
||||
"overrideOpen": fields.override_open,
|
||||
"overrideSave": fields.override_save,
|
||||
"overrideExport": fields.override_export,
|
||||
"stopOnError": fields.stop_on_error,
|
||||
"includeSubdirs": fields.include_subdirs,
|
||||
});
|
||||
if source == "folder" {
|
||||
params["folder"] = json!(d.str("folder"));
|
||||
if fields.source == BatchSource::Folder {
|
||||
params["folder"] = json!(fields.folder);
|
||||
}
|
||||
if names_data_set_files(d) {
|
||||
params["datasetFileNaming"] = json!(d.str("datasetFileNaming"));
|
||||
if names_data_set_files(fields) {
|
||||
params["datasetFileNaming"] = json!(fields.dataset_file_naming);
|
||||
}
|
||||
if destination == "folder" {
|
||||
params["destinationFolder"] = json!(d.str("destinationFolder"));
|
||||
if fields.destination == BatchDestination::Folder {
|
||||
params["destinationFolder"] = json!(fields.destination_folder);
|
||||
}
|
||||
params
|
||||
}
|
||||
@@ -183,148 +258,240 @@ fn params(d: &Dialog, action_name: &str, commands: Vec<Value>) -> Value {
|
||||
/// Whether the File Name choice names the batch's output: a Data Sets source with a
|
||||
/// destination folder. With None or Save and Close the dialog sends no folder, so no file
|
||||
/// takes the data set's name.
|
||||
fn names_data_set_files(d: &Dialog) -> bool {
|
||||
d.str("source") == "datasets" && d.str("destination") == "folder"
|
||||
fn names_data_set_files(fields: &BatchFields) -> bool {
|
||||
fields.source == BatchSource::DataSets && fields.destination == BatchDestination::Folder
|
||||
}
|
||||
|
||||
impl ActionDialog for BatchDialog {
|
||||
type Answer = (usize, usize, BatchFields);
|
||||
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.form.take().map(|fields| (self.set, self.action, fields))
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, (set, action, fields): Self::Answer) -> Result<(), String> {
|
||||
let a: Action = model::flat(&app.ui.actions, set, action).and_then(|flat| app.ui.actions.action(flat)).ok_or("no such action")?.clone();
|
||||
let commands = included_commands(&a);
|
||||
if commands.is_empty() {
|
||||
return Err("the action has no included steps".into());
|
||||
}
|
||||
refuse_steps(&commands)?;
|
||||
if fields.source == BatchSource::Folder && fields.folder.trim().is_empty() {
|
||||
return Err("choose a source folder".into());
|
||||
}
|
||||
if fields.destination == BatchDestination::Folder && fields.destination_folder.trim().is_empty() {
|
||||
return Err("choose a destination folder".into());
|
||||
}
|
||||
if fields.source == BatchSource::DataSets && app.session.active().is_none() {
|
||||
return Err("open a document with data sets".into());
|
||||
}
|
||||
let result = app.replay("action.batch", params(&fields, &a.name, commands))?;
|
||||
let count = result["count"].as_u64().unwrap_or(0);
|
||||
let failed = result["failed"].as_u64().unwrap_or(0);
|
||||
if failed > 0 {
|
||||
app.status(format!("Batch: {count} processed, {failed} failed"));
|
||||
} else {
|
||||
app.status(format!("Batch: {count} processed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A row that picks one of `entries` for `value`.
|
||||
fn select_row<T: Copy + Eq + Hash + std::fmt::Debug + Send + Sync + 'static>(ui: &mut Ui, name: &str, value: &mut T, entries: &[Entry<T>]) {
|
||||
Field::new(label(name)).show(ui, |ui, _| {
|
||||
if let Some(picked) = Select::new(label(name), Bind::given(*value), entries).show(ui).value().copied() {
|
||||
*value = picked;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A row with a path field and its Browse button; `asked` takes the press.
|
||||
fn folder_row(ui: &mut Ui, name: &str, value: &mut String, which: Folder, asked: &mut Vec<Folder>) {
|
||||
Field::new(label(name)).show(ui, |ui, _| {
|
||||
if PathRow::new(label(name), Bind::bound(value)).show(ui).browse {
|
||||
asked.push(which);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
impl StackDialog for BatchDialog {
|
||||
type Result = BatchFields;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<BatchFields>> {
|
||||
let sources = [Entry::new(BatchSource::Folder, label("Folder")), Entry::new(BatchSource::DataSets, label("Data Sets"))];
|
||||
let destinations = [
|
||||
Entry::new(BatchDestination::None, label("None")),
|
||||
Entry::new(BatchDestination::SaveAndClose, label("Save and Close")),
|
||||
Entry::new(BatchDestination::Folder, label("Folder")),
|
||||
];
|
||||
let namings = [
|
||||
Entry::new(DatasetNaming::FileNumber, label("File + Number")),
|
||||
Entry::new(DatasetNaming::FileDataSetName, label("File + Data Set Name")),
|
||||
Entry::new(DatasetNaming::DataSetName, label("Data Set Name")),
|
||||
];
|
||||
let (name, warn) = (&self.action_name, self.warn);
|
||||
let mut asked = Vec::new();
|
||||
let shown = self.form.show(ui, label("Batch"), None, |ui, fields| {
|
||||
FieldGroup::new(label("Batch")).show(ui, |ui, _| {
|
||||
Text::new(Label::from(name.clone())).show(ui);
|
||||
select_row(ui, "Play:", &mut fields.source, &sources);
|
||||
if fields.source == BatchSource::Folder {
|
||||
folder_row(ui, "Source Folder:", &mut fields.folder, Folder::Source, &mut asked);
|
||||
Checkbox::new(Bind::bound(&mut fields.include_subdirs)).label(label("Include All Subdirectories")).show(ui);
|
||||
} else {
|
||||
Text::new(label("Uses every data set of the open document.")).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
select_row(ui, "Destination:", &mut fields.destination, &destinations);
|
||||
if fields.destination == BatchDestination::Folder {
|
||||
folder_row(ui, "Destination Folder:", &mut fields.destination_folder, Folder::Destination, &mut asked);
|
||||
}
|
||||
if names_data_set_files(fields) {
|
||||
select_row(ui, "File Name:", &mut fields.dataset_file_naming, &namings);
|
||||
}
|
||||
});
|
||||
FieldGroup::new(label("Overrides")).show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut fields.override_open)).label(label("Override Action \"Open\" Commands")).show(ui);
|
||||
Checkbox::new(Bind::bound(&mut fields.override_save)).label(label("Override Action \"Save\" Commands")).show(ui);
|
||||
Checkbox::new(Bind::bound(&mut fields.override_export)).label(label("Override Action \"Export\" Commands")).show(ui);
|
||||
Checkbox::new(Bind::bound(&mut fields.stop_on_error)).label(label("Stop on Errors")).show(ui);
|
||||
});
|
||||
if warn {
|
||||
Text::new(label("Each data set saves over the same file, which keeps only the last data set.")).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
self.asked.extend(asked);
|
||||
shown
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<BatchFields> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
Some(merged(self.form.json_fields()?, json!({"set": self.set, "action": self.action, "actionName": self.action_name})))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
let rejected = || FieldRefusal::Rejects(&value).message(field);
|
||||
match field {
|
||||
"set" | "action" => {
|
||||
let mut index = None;
|
||||
set_index(&mut index, field, &value)?;
|
||||
let index = index.ok_or_else(rejected)?;
|
||||
if field == "set" { self.set = index } else { self.action = index }
|
||||
Ok(())
|
||||
}
|
||||
"actionName" => {
|
||||
self.action_name = value.as_str().ok_or_else(rejected)?.to_owned();
|
||||
Ok(())
|
||||
}
|
||||
_ => self.form.set_field(ctx, field, value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft::automation::actions::{Action, ActionStep};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn shown(source: &str, destination: &str) -> Vec<String> {
|
||||
let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test"));
|
||||
d.fields["source"] = json!(source);
|
||||
d.fields["destination"] = json!(destination);
|
||||
render(&mut d)
|
||||
use super::*;
|
||||
use crate::dialogs::actions::pump;
|
||||
|
||||
/// An app with one set holding `steps` as the action "Draw", and a window to show dialogs in.
|
||||
fn app_with(steps: Vec<ActionStep>) -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(crate::testing::ui_context());
|
||||
app.ui.actions = Default::default();
|
||||
app.ui.actions.push(Action { set: Some("Test".into()), ..Action::new("Draw", steps) }).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// Draws `d` once and returns the texts it shows.
|
||||
fn render(d: &mut Dialog) -> Vec<String> {
|
||||
render_in(&mut VectorcraftApp::new(Session::new(), Default::default()), d)
|
||||
}
|
||||
|
||||
/// Draws `d` once over `app` and returns the texts it shows.
|
||||
fn render_in(app: &mut VectorcraftApp, d: &mut Dialog) -> Vec<String> {
|
||||
fn collect(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)),
|
||||
_ => {}
|
||||
/// Sets the open dialog's fields as `ui.dialog.set` does.
|
||||
fn set_fields(app: &VectorcraftApp, fields: &[(&str, Value)]) {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
for (field, value) in fields {
|
||||
host.get_mut::<BatchDialog>().unwrap().set_json_field(&ctx, field, value.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut frame = ctx.run_ui(Default::default(), |ui| {
|
||||
body(app, ui, d);
|
||||
});
|
||||
frame.textures_delta.clear();
|
||||
let mut labels = vec![];
|
||||
frame.shapes.iter().for_each(|shape| collect(&shape.shape, &mut labels));
|
||||
labels
|
||||
}
|
||||
|
||||
/// The File Name row's caption and its selected choice (the dropdown shows only that one).
|
||||
const NAMING: [&str; 2] = ["File Name:", "File + Number"];
|
||||
|
||||
#[test]
|
||||
fn file_name_choice_shows_only_for_data_sets_into_a_folder() {
|
||||
for source in ["folder", "datasets"] {
|
||||
for destination in ["none", "saveAndClose", "folder"] {
|
||||
let labels = shown(source, destination);
|
||||
let expected = source == "datasets" && destination == "folder";
|
||||
for text in NAMING {
|
||||
assert_eq!(labels.iter().any(|label| label == text), expected, "{source} to {destination}, {text}: {labels:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_name_choice_comes_back_after_another_destination() {
|
||||
let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test"));
|
||||
d.fields["source"] = json!("datasets");
|
||||
d.fields["datasetFileNaming"] = json!("dataSetName");
|
||||
for (destination, shown) in [("folder", true), ("none", false), ("saveAndClose", false), ("folder", true)] {
|
||||
d.fields["destination"] = json!(destination);
|
||||
let labels = render(&mut d);
|
||||
assert_eq!(labels.iter().any(|label| label == "File Name:"), shown, "{destination}: {labels:?}");
|
||||
assert_eq!(labels.iter().any(|label| label == "Data Set Name"), shown, "{destination}: {labels:?}");
|
||||
assert_eq!(d.str("datasetFileNaming"), "dataSetName", "{destination}");
|
||||
}
|
||||
assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], "dataSetName");
|
||||
}
|
||||
|
||||
/// Batch plays an action recorded with a key its command no longer reads, as Play does.
|
||||
#[test]
|
||||
fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() {
|
||||
use crate::panels::actions::{Action, ActionSet};
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let old = json!({"x": 10, "y": 10, "width": 20, "height": 20, "cornerStyle": "round"});
|
||||
let mut app = app_with(vec![ActionStep::new("shape.rectangle", old.clone())]);
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.run("dataset.new", json!({"name": "a"})).unwrap();
|
||||
let old = json!({"x": 10, "y": 10, "width": 20, "height": 20, "cornerStyle": "round"});
|
||||
assert!(app.run("shape.rectangle", old.clone()).is_err());
|
||||
app.ui.action_sets = vec![ActionSet::new("Test", vec![Action::new("Draw", vec![("shape.rectangle".into(), old)])])];
|
||||
let mut d = Dialog::new(KIND, initial_fields(0, 0, "Draw"));
|
||||
d.fields["source"] = json!("datasets");
|
||||
d.fields["destination"] = json!("none");
|
||||
let r = confirm(&mut app, &d).unwrap();
|
||||
assert_eq!((r["count"].clone(), r["failed"].clone()), (json!(1), json!(0)), "{r}");
|
||||
assert!(app.run("shape.rectangle", old).is_err());
|
||||
open(&mut app, 0, 0).unwrap();
|
||||
set_fields(&app, &[("source", json!("datasets")), ("destination", json!("none"))]);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// OK files the choices, the pump answers them, and the next OK closes the dialog with them.
|
||||
assert!(!app.dialogs().unwrap().with(|host| host.confirm::<BatchDialog>(&ctx)));
|
||||
pump(&mut app, &ctx);
|
||||
assert!(app.dialogs().unwrap().with(|host| host.confirm::<BatchDialog>(&ctx)));
|
||||
assert!(!app.dialogs().unwrap().with(|host| host.is_open::<BatchDialog>()));
|
||||
assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1);
|
||||
assert!(!app.session.replaying());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_set_naming_params_follow_dialog_choice() {
|
||||
let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test"));
|
||||
assert_eq!(d.str("datasetFileNaming"), "fileNumber");
|
||||
d.fields["source"] = json!("datasets");
|
||||
for choice in ["fileNumber", "fileDataSetName", "dataSetName"] {
|
||||
d.fields["datasetFileNaming"] = json!(choice);
|
||||
assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], choice);
|
||||
let mut fields = BatchFields::default();
|
||||
assert_eq!(fields.dataset_file_naming, DatasetNaming::FileNumber);
|
||||
fields.source = BatchSource::DataSets;
|
||||
for (choice, name) in [
|
||||
(DatasetNaming::FileNumber, "fileNumber"),
|
||||
(DatasetNaming::FileDataSetName, "fileDataSetName"),
|
||||
(DatasetNaming::DataSetName, "dataSetName"),
|
||||
] {
|
||||
fields.dataset_file_naming = choice;
|
||||
assert_eq!(params(&fields, "Test", vec![])["datasetFileNaming"], name);
|
||||
}
|
||||
d.fields["datasetFileNaming"] = json!("dataSetName");
|
||||
for destination in ["none", "saveAndClose"] {
|
||||
d.fields["destination"] = json!(destination);
|
||||
let p = params(&d, "Test", vec![]);
|
||||
assert!(p.get("datasetFileNaming").is_none(), "{destination}: {p}");
|
||||
assert!(p.get("destinationFolder").is_none(), "{destination}: {p}");
|
||||
fields.dataset_file_naming = DatasetNaming::DataSetName;
|
||||
for destination in [BatchDestination::None, BatchDestination::SaveAndClose] {
|
||||
fields.destination = destination;
|
||||
let p = params(&fields, "Test", vec![]);
|
||||
assert!(p.get("datasetFileNaming").is_none(), "{destination:?}: {p}");
|
||||
assert!(p.get("destinationFolder").is_none(), "{destination:?}: {p}");
|
||||
}
|
||||
d.fields["destination"] = json!("folder");
|
||||
d.fields["source"] = json!("folder");
|
||||
assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none());
|
||||
}
|
||||
|
||||
const ONE_FILE: &str = "Each data set saves over the same file, which keeps only the last data set.";
|
||||
|
||||
#[test]
|
||||
fn data_sets_offer_save_and_close_with_a_warning() {
|
||||
let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test"));
|
||||
d.fields["destination"] = json!("saveAndClose");
|
||||
let labels = render(&mut d);
|
||||
assert!(labels.iter().any(|label| label == "Save and Close"), "{labels:?}");
|
||||
assert!(!labels.iter().any(|label| label == ONE_FILE), "a folder source opens a file per pass: {labels:?}");
|
||||
d.fields["source"] = json!("datasets");
|
||||
let labels = render(&mut d);
|
||||
assert!(labels.iter().any(|label| label == "Save and Close"), "{labels:?}");
|
||||
assert!(labels.iter().any(|label| label == ONE_FILE), "{labels:?}");
|
||||
assert_eq!(params(&d, "Test", vec![])["destination"], "saveAndClose");
|
||||
d.fields["destination"] = json!("folder");
|
||||
assert!(!render(&mut d).iter().any(|label| label == ONE_FILE));
|
||||
fields.destination = BatchDestination::Folder;
|
||||
fields.source = BatchSource::Folder;
|
||||
assert!(params(&fields, "Test", vec![]).get("datasetFileNaming").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_sets_warn_about_a_recorded_save_left_in_place() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui.action_sets[0].actions[0].steps.push(("document.save".into(), json!({"path": "/x/a.vectorcraft"})));
|
||||
let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test"));
|
||||
d.fields["source"] = json!("datasets");
|
||||
d.fields["destinationFolder"] = json!("/out");
|
||||
assert!(!render_in(&mut app, &mut d).iter().any(|label| label == ONE_FILE), "Override Save points the save into the folder");
|
||||
d.fields["overrideSave"] = json!(false);
|
||||
assert!(render_in(&mut app, &mut d).iter().any(|label| label == ONE_FILE));
|
||||
d.fields["overrideSave"] = json!(true);
|
||||
d.fields["destination"] = json!("none");
|
||||
assert!(render_in(&mut app, &mut d).iter().any(|label| label == ONE_FILE));
|
||||
let save = ActionStep::new("document.save", json!({"path": "/x/a.vectorcraft"}));
|
||||
let app = app_with(vec![save]);
|
||||
let warns = |source, destination, override_save| {
|
||||
let fields = BatchFields { source, destination, override_save, destination_folder: "/out".into(), ..BatchFields::default() };
|
||||
overwrites_one_file(&app, 0, 0, &fields)
|
||||
};
|
||||
let (folder, data_sets) = (BatchSource::Folder, BatchSource::DataSets);
|
||||
assert!(!warns(folder, BatchDestination::None, true), "a folder source opens a file per pass");
|
||||
assert!(warns(data_sets, BatchDestination::None, true));
|
||||
assert!(warns(data_sets, BatchDestination::SaveAndClose, true));
|
||||
assert!(!warns(data_sets, BatchDestination::Folder, true), "Override Save points the save into the folder");
|
||||
assert!(warns(data_sets, BatchDestination::Folder, false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,96 +7,106 @@
|
||||
//! progress). Picking an item runs nothing. OK inserts it; an invalid place is an error, and the
|
||||
//! dialog stays open.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use craft::behavior::{DisplayOrder, ItemSource, Selection};
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::layout_components::Row as Line;
|
||||
use craft::ui::list::{List, ListRow};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::DialogSpec;
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, menus, widgets};
|
||||
use super::actions::{ActionDialog, Form, Target, label, merged, open_or_say};
|
||||
use crate::i18n::{Lang, LangExt};
|
||||
use crate::panels::actions::INSERT_MENU_ITEM;
|
||||
use crate::{VectorcraftApp, menus};
|
||||
|
||||
/// The dialog kind of Insert Menu Item.
|
||||
pub const KIND: &str = "actionInsertMenuItem";
|
||||
/// The key the dialog answers for.
|
||||
const KEY: &str = "actionInsertMenuItem";
|
||||
|
||||
/// The most rows the list shows at once; Find narrows it.
|
||||
const MAX_LISTED: usize = 200;
|
||||
|
||||
/// The width of the Menu Item label.
|
||||
const LABEL_W: f32 = 80.0;
|
||||
/// Why Find picked nothing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum FindNote {
|
||||
/// Nothing to say.
|
||||
#[default]
|
||||
#[serde(rename = "")]
|
||||
Clear,
|
||||
/// No menu item matches.
|
||||
#[serde(rename = "none")]
|
||||
NoMatch,
|
||||
/// Several match: the user picks one from the list.
|
||||
#[serde(rename = "several")]
|
||||
Several,
|
||||
}
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Insert Menu Item").into(),
|
||||
body,
|
||||
confirm,
|
||||
ok_enabled: Some(|_, d| !d.str("command").is_empty()),
|
||||
min_width: 460.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
/// What Insert Menu Item edits.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InsertMenuItemFields {
|
||||
/// The words the list is narrowed to.
|
||||
pub find: String,
|
||||
/// The command of the item picked; empty until one is.
|
||||
pub command: String,
|
||||
/// The params of the item picked.
|
||||
pub params: Value,
|
||||
/// Why the last Find picked nothing.
|
||||
pub note: FindNote,
|
||||
}
|
||||
|
||||
/// Opens Insert Menu Item for action `target` as (set, action), after `step`, else for the recording
|
||||
/// in progress.
|
||||
pub fn open(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option<usize>) {
|
||||
let mut fields = json!({"find": "", "command": "", "params": {}, "note": ""});
|
||||
if let Some((set, action)) = target {
|
||||
fields["set"] = json!(set);
|
||||
fields["action"] = json!(action);
|
||||
if let Some(step) = step {
|
||||
fields["step"] = json!(step);
|
||||
}
|
||||
impl Default for InsertMenuItemFields {
|
||||
fn default() -> Self {
|
||||
InsertMenuItemFields { find: String::new(), command: String::new(), params: json!({}), note: FindNote::Clear }
|
||||
}
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
}
|
||||
|
||||
/// Why OK is off: no item picked.
|
||||
fn check(fields: &InsertMenuItemFields) -> Option<Label> {
|
||||
fields.command.is_empty().then(|| label("Pick a menu item"))
|
||||
}
|
||||
|
||||
/// A row of the list: an item of [`menus::insertable_items`], with what it shows and what Find
|
||||
/// matches worked out once.
|
||||
pub(crate) struct Row {
|
||||
command: &'static str,
|
||||
params: Value,
|
||||
pub struct Row {
|
||||
/// The item's command.
|
||||
pub command: String,
|
||||
/// The item's params.
|
||||
pub params: Value,
|
||||
/// The menu path and label in the UI language (`Object › Group`).
|
||||
shown: String,
|
||||
pub shown: String,
|
||||
/// The English path and label, the shown one and the command id, lowercased, one per line.
|
||||
haystack: String,
|
||||
}
|
||||
|
||||
/// The rows in `lang`, for menus that name fonts in English when `english_names` is set.
|
||||
fn build(lang: crate::i18n::Lang, english_names: bool) -> Vec<Row> {
|
||||
pub(crate) fn build(lang: Lang, english_names: bool) -> Vec<Row> {
|
||||
menus::insertable_items(english_names)
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let parts = || item.path.iter().chain(std::iter::once(&item.label)).copied();
|
||||
let english = parts().collect::<Vec<_>>().join(" › ");
|
||||
let english = item.path.iter().chain(std::iter::once(&item.label)).map(String::as_str).collect::<Vec<_>>().join(" › ");
|
||||
// A saved proof setup keeps its file's name.
|
||||
let own_name = item.command == crate::dialogs::proof_setup::LOAD;
|
||||
let path = item.path.iter().map(|s| crate::i18n::tr(lang, s));
|
||||
let label = if own_name { item.label } else { crate::i18n::tr(lang, item.label) };
|
||||
let shown = path.chain(std::iter::once(label)).collect::<Vec<_>>().join(" › ");
|
||||
let name = if own_name { item.label.as_str() } else { crate::i18n::tr(lang, &item.label) };
|
||||
let shown = path.chain(std::iter::once(name)).collect::<Vec<_>>().join(" › ");
|
||||
let haystack = format!("{}\n{}\n{}", english.to_lowercase(), shown.to_lowercase(), item.command.to_lowercase());
|
||||
Row { command: item.command, params: item.params, shown, haystack }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The rows, built again only when the language, the installed plug-ins, the font name setting,
|
||||
/// the loaded fonts or the saved proof setups change, not on every frame.
|
||||
fn rows(app: &VectorcraftApp, ctx: &egui::Context) -> Arc<Vec<Row>> {
|
||||
type Key = (&'static str, u64, bool, u64, bool, u64);
|
||||
let lang = crate::i18n::current();
|
||||
let english_names = app.session.prefs.font_names_in_english;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Read before building, as the Font menu does: fonts that load meanwhile build the rows again.
|
||||
let (cataloged, generation) = (db.installed_fonts_ready(), db.generation());
|
||||
let key: Key = (lang.code(), menus::plugin_revision(), english_names, generation, cataloged, crate::dialogs::proof_setup::saved_revision());
|
||||
let id = egui::Id::unique("action-insert-menu-item-rows");
|
||||
if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, Arc<Vec<Row>>)>(id))
|
||||
&& k == key
|
||||
{
|
||||
return v;
|
||||
}
|
||||
let built = Arc::new(build(lang, english_names));
|
||||
ctx.data_mut(|d| d.insert_temp::<(Key, Arc<Vec<Row>>)>(id, (key, built.clone())));
|
||||
built
|
||||
}
|
||||
/// What the rows were built from: the language, the installed plug-ins, the font name setting, the
|
||||
/// loaded fonts, whether the installed fonts are cataloged and the saved proof setups.
|
||||
pub(crate) type RowsKey = (&'static str, u64, bool, u64, bool, u64);
|
||||
|
||||
/// The rows that every word of `find` matches, in menu order.
|
||||
fn matches<'a>(rows: &'a [Row], find: &str) -> impl Iterator<Item = &'a Row> {
|
||||
@@ -104,111 +114,239 @@ fn matches<'a>(rows: &'a [Row], find: &str) -> impl Iterator<Item = &'a Row> {
|
||||
rows.iter().filter(move |r| words.iter().all(|w| r.haystack.contains(w.as_str())))
|
||||
}
|
||||
|
||||
/// Picks `row` in `d`.
|
||||
fn pick(d: &mut Dialog, row: &Row) {
|
||||
d.fields.insert("command".into(), json!(row.command));
|
||||
d.fields.insert("params".into(), row.params.clone());
|
||||
d.fields.insert("note".into(), json!(""));
|
||||
/// Picks `row`.
|
||||
fn pick(fields: &mut InsertMenuItemFields, row: &Row) {
|
||||
fields.command.clone_from(&row.command);
|
||||
fields.params.clone_from(&row.params);
|
||||
fields.note = FindNote::Clear;
|
||||
}
|
||||
|
||||
/// Find: picks the one row that `find` matches; with none or several, picks nothing and notes it.
|
||||
fn find(rows: &[Row], d: &mut Dialog) {
|
||||
let found: Vec<&Row> = matches(rows, &d.str("find")).take(2).collect();
|
||||
fn find(rows: &[Row], fields: &mut InsertMenuItemFields) {
|
||||
let found: Vec<&Row> = matches(rows, &fields.find).take(2).collect();
|
||||
match found[..] {
|
||||
[row] => pick(d, row),
|
||||
[] => {
|
||||
d.fields.insert("note".into(), json!("none"));
|
||||
}
|
||||
_ => {
|
||||
d.fields.insert("note".into(), json!("several"));
|
||||
}
|
||||
[row] => pick(fields, row),
|
||||
[] => fields.note = FindNote::NoMatch,
|
||||
_ => fields.note = FindNote::Several,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `row` is the item picked in `d`.
|
||||
fn picked(d: &Dialog, row: &Row) -> bool {
|
||||
d.fields.get("command").and_then(Value::as_str) == Some(row.command) && d.fields.get("params") == Some(&row.params)
|
||||
/// Whether `row` is the item picked.
|
||||
fn picked(fields: &InsertMenuItemFields, row: &Row) -> bool {
|
||||
fields.command == row.command && fields.params == row.params
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let rows = rows(app, ui.ctx());
|
||||
let dim = Tokens::get(ui.ctx()).text_dim;
|
||||
let mut find_now = false;
|
||||
ui.horizontal(|ui| {
|
||||
if super::form::text_named(ui, d, "find", tl!("Find"), 300.0) {
|
||||
d.fields.insert("note".into(), json!(""));
|
||||
}
|
||||
find_now = widgets::secondary_button(ui, tl!("Find")).clicked();
|
||||
});
|
||||
if find_now {
|
||||
find(&rows, d);
|
||||
/// The texts of the list's rows as a collection source.
|
||||
struct Listed<'a>(&'a [String]);
|
||||
|
||||
impl DisplayOrder<usize> for Listed<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
match d.str("note").as_str() {
|
||||
"none" => {
|
||||
ui.label(egui::RichText::new(tl!("No menu item matches.")).color(dim));
|
||||
}
|
||||
"several" => {
|
||||
ui.label(egui::RichText::new(tl!("Several menu items match. Choose one from the list.")).color(dim));
|
||||
}
|
||||
_ => {}
|
||||
|
||||
fn key(&self, at: usize) -> usize {
|
||||
at
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let mut chosen: Option<usize> = None;
|
||||
let query = d.str("find");
|
||||
egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
for (i, row) in matches(&rows, &query).enumerate().take(MAX_LISTED) {
|
||||
if ui.selectable_label(picked(d, row), row.shown.as_str()).clicked() {
|
||||
chosen = Some(i);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(row) = chosen.and_then(|i| matches(&rows, &query).nth(i)) {
|
||||
pick(d, row);
|
||||
|
||||
fn index_of(&self, key: &usize) -> Option<usize> {
|
||||
(*key < self.0.len()).then_some(*key)
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
self.0.get(at).map(|text| Cow::Borrowed(text.as_str()))
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let shown = rows.iter().find(|r| picked(d, r)).map_or_else(
|
||||
|| {
|
||||
let command = d.str("command");
|
||||
if command.is_empty() { tl!("None").to_string() } else { command }
|
||||
},
|
||||
|r| r.shown.clone(),
|
||||
);
|
||||
widgets::label_row(ui, "Menu Item:", LABEL_W, |ui| {
|
||||
ui.label(shown);
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("Items that open a dialog, and File, Window and Help menu items, are not listed.")).color(dim));
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut params = json!({"command": d.str("command"), "params": d.fields.get("params").cloned().unwrap_or_else(|| json!({}))});
|
||||
for key in ["set", "action", "step"] {
|
||||
if let Some(value) = d.fields.get(key) {
|
||||
params[key] = value.clone();
|
||||
impl ItemSource<usize> for Listed<'_> {}
|
||||
|
||||
/// The Insert Menu Item dialog on the dialog host.
|
||||
pub struct InsertMenuItemDialog {
|
||||
id: DialogId,
|
||||
/// Where the step goes.
|
||||
pub target: Target,
|
||||
form: Form<InsertMenuItemFields>,
|
||||
rows: Vec<Row>,
|
||||
/// What `rows` were built from; the pump builds them again when it changes.
|
||||
key: Option<RowsKey>,
|
||||
}
|
||||
|
||||
impl InsertMenuItemDialog {
|
||||
/// What the rows would be built from now.
|
||||
pub(crate) fn rows_key(app: &VectorcraftApp) -> RowsKey {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Read before building, as the Font menu does: fonts that load meanwhile build the rows again.
|
||||
let (cataloged, generation) = (db.installed_fonts_ready(), db.generation());
|
||||
(
|
||||
crate::i18n::current().code(),
|
||||
menus::plugin_revision(),
|
||||
app.session.prefs.font_names_in_english,
|
||||
generation,
|
||||
cataloged,
|
||||
crate::dialogs::proof_setup::saved_revision(),
|
||||
)
|
||||
}
|
||||
|
||||
/// What the rows were built from.
|
||||
pub(crate) fn built_from(&self) -> Option<RowsKey> {
|
||||
self.key
|
||||
}
|
||||
|
||||
/// Replaces the rows with `rows`, built from `key`.
|
||||
pub(crate) fn set_rows(&mut self, key: RowsKey, rows: Vec<Row>) {
|
||||
self.key = Some(key);
|
||||
self.rows = rows;
|
||||
}
|
||||
|
||||
/// The items the list offers before Find narrows them.
|
||||
pub fn rows(&self) -> &[Row] {
|
||||
&self.rows
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens Insert Menu Item for action `target` as (set, action), after `step`, else for the recording
|
||||
/// in progress.
|
||||
pub fn open(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option<usize>) {
|
||||
let key = InsertMenuItemDialog::rows_key(app);
|
||||
let rows = build(crate::i18n::current(), app.session.prefs.font_names_in_english);
|
||||
let dialog = InsertMenuItemDialog {
|
||||
id: dialog_id(KEY),
|
||||
target: Target::new(target, step),
|
||||
form: Form::new(InsertMenuItemFields::default(), check),
|
||||
rows,
|
||||
key: Some(key),
|
||||
};
|
||||
open_or_say(app, dialog);
|
||||
}
|
||||
|
||||
impl ActionDialog for InsertMenuItemDialog {
|
||||
type Answer = (Target, InsertMenuItemFields);
|
||||
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.form.take().map(|fields| (self.target, fields))
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, (target, fields): Self::Answer) -> Result<(), String> {
|
||||
let mut params = json!({"command": fields.command, "params": fields.params});
|
||||
target.add_to(&mut params);
|
||||
app.run(INSERT_MENU_ITEM, params).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for InsertMenuItemDialog {
|
||||
type Result = InsertMenuItemFields;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<InsertMenuItemFields>> {
|
||||
let rows = &self.rows;
|
||||
self.form.show(ui, label("Insert Menu Item"), None, |ui, fields| {
|
||||
FieldGroup::new(label("Insert Menu Item")).show(ui, |ui, _| {
|
||||
let before = fields.find.clone();
|
||||
let mut find_now = false;
|
||||
Field::new(label("Find:")).show(ui, |ui, _| {
|
||||
Line::new().show(ui, |ui, _| {
|
||||
TextField::search(label("Find"), Bind::bound(&mut fields.find)).show(ui);
|
||||
find_now = clicked(&Button::new(label("Find")).id_salt("find").show(ui));
|
||||
});
|
||||
});
|
||||
if fields.find != before {
|
||||
fields.note = FindNote::Clear;
|
||||
}
|
||||
if find_now {
|
||||
find(rows, fields);
|
||||
}
|
||||
let note = match fields.note {
|
||||
FindNote::Clear => None,
|
||||
FindNote::NoMatch => Some("No menu item matches."),
|
||||
FindNote::Several => Some("Several menu items match. Choose one from the list."),
|
||||
};
|
||||
if let Some(note) = note {
|
||||
Text::new(label(note)).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
let listed: Vec<&Row> = matches(rows, &fields.find).take(MAX_LISTED).collect();
|
||||
let texts: Vec<String> = listed.iter().map(|row| row.shown.clone()).collect();
|
||||
let lead = listed.iter().position(|row| picked(fields, row));
|
||||
let mut selection = lead.map_or_else(Selection::default, Selection::single);
|
||||
List::<usize>::new(label("Menu Items")).select(SelectMode::Single).selection(Bind::bound(&mut selection)).sizing(Sizing::Content).max_rows(8).show_items(
|
||||
ui,
|
||||
&Listed(&texts),
|
||||
&mut |key, _| ListRow::new(texts.get(*key).cloned().unwrap_or_default()),
|
||||
);
|
||||
if selection.lead != lead
|
||||
&& let Some(row) = selection.lead.and_then(|at| listed.get(at))
|
||||
{
|
||||
pick(fields, row);
|
||||
}
|
||||
let current = rows.iter().find(|row| picked(fields, row)).map_or_else(
|
||||
|| if fields.command.is_empty() { crate::i18n::t("None").to_owned() } else { fields.command.clone() },
|
||||
|row| row.shown.clone(),
|
||||
);
|
||||
Field::new(label("Menu Item:")).show(ui, |ui, _| {
|
||||
Text::new(Label::from(current)).show(ui);
|
||||
});
|
||||
Text::new(label("Items that open a dialog, and File, Window and Help menu items, are not listed.")).shade(Shade::Muted).show(ui);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<InsertMenuItemFields> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
/// The fields and the place; the params of an item the request may not read are left out.
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
let mut fields = self.form.json_fields()?;
|
||||
if let Some(Value::Object(params)) = fields.get_mut("params") {
|
||||
crate::control::leave_out_unreadable_step(&self.form.values.command, params);
|
||||
}
|
||||
Some(merged(fields, self.target.json()))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
match self.target.set_field(field, &value) {
|
||||
Some(done) => done,
|
||||
None => self.form.set_field(ctx, field, value),
|
||||
}
|
||||
}
|
||||
let r = app.run(crate::panels::actions::INSERT_MENU_ITEM, params)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::menu::Node;
|
||||
|
||||
use super::*;
|
||||
use crate::i18n::Lang;
|
||||
use crate::dialogs::actions::pump;
|
||||
|
||||
fn fields(find: &str, command: &str) -> InsertMenuItemFields {
|
||||
InsertMenuItemFields { find: find.into(), command: command.into(), ..InsertMenuItemFields::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_picks_the_one_match_and_notes_none_or_several() {
|
||||
let rows = build(Lang::EN, true);
|
||||
let mut d = Dialog::new(KIND, json!({"find": "object group", "command": "", "params": {}, "note": ""}));
|
||||
find(&rows, &mut d);
|
||||
assert_eq!((d.str("note"), d.str("command")), ("several".to_string(), String::new()), "Group and Ungroup both match");
|
||||
d.fields.insert("find".into(), json!("OBJECT.UNGROUP"));
|
||||
find(&rows, &mut d);
|
||||
assert_eq!((d.str("command"), d.fields["params"].clone(), d.str("note")), ("object.ungroup".to_string(), json!({}), String::new()));
|
||||
d.fields.insert("find".into(), json!("no such menu item here"));
|
||||
find(&rows, &mut d);
|
||||
assert_eq!((d.str("note"), d.str("command")), ("none".to_string(), "object.ungroup".to_string()), "a failed Find keeps the pick");
|
||||
let mut f = fields("object group", "");
|
||||
find(&rows, &mut f);
|
||||
assert_eq!((f.note, f.command.as_str()), (FindNote::Several, ""), "Group and Ungroup both match");
|
||||
f.find = "OBJECT.UNGROUP".into();
|
||||
find(&rows, &mut f);
|
||||
assert_eq!((f.command.as_str(), f.params.clone(), f.note), ("object.ungroup", json!({}), FindNote::Clear));
|
||||
f.find = "no such menu item here".into();
|
||||
find(&rows, &mut f);
|
||||
assert_eq!((f.note, f.command.as_str()), (FindNote::NoMatch, "object.ungroup"), "a failed Find keeps the pick");
|
||||
}
|
||||
|
||||
/// The list holds the menu items that run an engine command, and the View menu items that the
|
||||
@@ -220,11 +358,11 @@ mod tests {
|
||||
let items = menus::insertable_items(true);
|
||||
assert!(items.len() > 100, "only {} items", items.len());
|
||||
for item in &items {
|
||||
let in_app = menus::plays_in_app(item.command);
|
||||
assert!(vectorcraft_engine::find_command(item.command).is_some() != in_app, "{item:?}");
|
||||
let in_app = menus::plays_in_app(&item.command);
|
||||
assert!(vectorcraft_engine::find_command(&item.command).is_some() != in_app, "{item:?}");
|
||||
assert!(!in_app || item.path[0] == "View", "{item:?}");
|
||||
assert!(!item.label.ends_with('…'), "{item:?}");
|
||||
assert!(!["VectorCraft", "File", "Window", "Help"].contains(&item.path[0]), "{item:?}");
|
||||
assert!(!["VectorCraft", "File", "Window", "Help"].contains(&item.path[0].as_str()), "{item:?}");
|
||||
assert!(item.params.is_object(), "{item:?}");
|
||||
}
|
||||
let has = |command: &str| items.iter().any(|i| i.command == command);
|
||||
@@ -271,12 +409,12 @@ mod tests {
|
||||
#[test]
|
||||
fn every_view_item_the_app_runs_is_listed() {
|
||||
let items = menus::insertable_items(true);
|
||||
let view = menus::menu_tree_named(true).into_iter().find(|(title, _)| *title == "View").map(|(_, items)| items).unwrap();
|
||||
fn walk(items: &[menus::Item], out: &mut Vec<(&'static str, &'static str)>) {
|
||||
for it in items {
|
||||
match it {
|
||||
menus::Item::Cmd(label, id, _) => out.push((label, id)),
|
||||
menus::Item::Sub(_, children) => walk(children, out),
|
||||
let view = menus::menu_tree_named(true).into_iter().find(|(title, _)| *title == "View").map(|(_, nodes)| nodes).unwrap();
|
||||
fn walk<'a>(nodes: &'a [Node], out: &mut Vec<(&'a str, &'a str)>) {
|
||||
for node in nodes {
|
||||
match node {
|
||||
Node::Item(item) => out.push((item.label.as_str(), item.command.id.as_str())),
|
||||
Node::Submenu { children, .. } => walk(children, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -307,26 +445,33 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A proof setup saved while the dialog is open is listed at once, by its file's name in every
|
||||
/// UI language.
|
||||
/// UI language: the pump builds the rows again when what they were built from changes.
|
||||
#[test]
|
||||
fn a_proof_setup_saved_meanwhile_is_listed_by_its_name() {
|
||||
use crate::dialogs::proof_setup;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.ui_ctx = Some(ctx.clone());
|
||||
let dir = vectorcraft_testkit::TempDir::new("insert-menu-item-proof-setups");
|
||||
app.session.attach_proof_setups(dir.join("Proof Setups"));
|
||||
proof_setup::refresh_saved(&app, None);
|
||||
proof_setup::wait();
|
||||
let de = Lang::from_code("de").unwrap();
|
||||
crate::i18n::set_current(de);
|
||||
let listed =
|
||||
|app: &VectorcraftApp| rows(app, &ctx).iter().filter(|r| r.command == proof_setup::LOAD).map(|r| r.shown.clone()).collect::<Vec<_>>();
|
||||
// The installed fonts' scan, which builds the rows again when it ends, is over first.
|
||||
vectorcraft_text::FontDb::global().menu_family_list();
|
||||
open(&mut app, None, None);
|
||||
let listed = |app: &VectorcraftApp| {
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
let dialog = host.get::<InsertMenuItemDialog>().unwrap();
|
||||
dialog.rows().iter().filter(|r| r.command == proof_setup::LOAD).map(|r| r.shown.clone()).collect::<Vec<_>>()
|
||||
})
|
||||
};
|
||||
let before = listed(&app);
|
||||
app.run("view.proofSetup.save", json!({"name": "Group", "target": "workingCmyk"})).unwrap();
|
||||
proof_setup::refresh_saved(&app, None);
|
||||
proof_setup::wait();
|
||||
pump(&mut app, &ctx);
|
||||
let after = listed(&app);
|
||||
crate::i18n::set_current(Lang::EN);
|
||||
assert!(before.is_empty(), "{before:?}");
|
||||
|
||||
@@ -2,132 +2,160 @@
|
||||
//! of a new action. Record adds the action and starts recording into it (`ui.action.new`).
|
||||
//!
|
||||
//! Fields: `set` (the index of the set the action goes into), `name`, `key` (0 for none, 1 to 15
|
||||
//! for F1 to F15), `cmd` (Ctrl, Command on macOS), `shift`, `color` (a value of
|
||||
//! [`crate::panels::actions::COLORS`], `""` for none). An invalid set or function key is an error:
|
||||
//! Record then adds nothing and the dialog stays open. `automaticAlignTo` (false) chooses the live
|
||||
//! selection's reference for Align at playback while keeping recorded step targets.
|
||||
//! for F1 to F15), `cmd` (Ctrl, Command on macOS), `shift`, `color` (the file name of an
|
||||
//! [`ActionColor`](craft::automation::actions::ActionColor), `""` for none) and `automaticAlignTo`,
|
||||
//! which chooses the live selection's reference for Align at playback while keeping recorded step
|
||||
//! targets. An invalid set or function key is an error: Record then adds nothing and the dialog
|
||||
//! stays open.
|
||||
|
||||
use craft::automation::actions::ActionList;
|
||||
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::DialogSpec;
|
||||
use crate::panels::actions::{COLORS, FUNCTION_KEYS, FunctionKey};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::actions::{ActionDialog, ActionOptions, Form, automatic_align_options, key_and_color, key_and_color_params, key_reason, label};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::actions::{NEW_ACTION, model};
|
||||
|
||||
/// The dialog kind of New Action.
|
||||
pub const KIND: &str = "actionNew";
|
||||
/// The key the dialog answers for.
|
||||
const KEY: &str = "actionNew";
|
||||
|
||||
/// The width of the label column.
|
||||
const LABEL_W: f32 = 90.0;
|
||||
/// What New Action edits.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NewActionFields {
|
||||
/// The index of the set the action goes into.
|
||||
pub set: usize,
|
||||
/// The action's name.
|
||||
pub name: String,
|
||||
/// The function key, color and Align choice.
|
||||
#[serde(flatten)]
|
||||
pub options: ActionOptions,
|
||||
}
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("New Action").into(),
|
||||
body,
|
||||
confirm,
|
||||
ok: Some("Record"),
|
||||
ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()),
|
||||
min_width: 340.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
/// Why OK is off: no name, or a function key the system keeps.
|
||||
fn check(fields: &NewActionFields) -> Option<Label> {
|
||||
if fields.name.trim().is_empty() {
|
||||
return Some(label("Enter a name for the action"));
|
||||
}
|
||||
key_reason(&fields.options)
|
||||
}
|
||||
|
||||
/// The New Action dialog on the dialog host.
|
||||
pub struct NewActionDialog {
|
||||
id: DialogId,
|
||||
form: Form<NewActionFields>,
|
||||
/// The names of the sets the Action Set row offers, as the app lists them.
|
||||
sets: Vec<String>,
|
||||
}
|
||||
|
||||
impl NewActionDialog {
|
||||
fn new(fields: NewActionFields, sets: Vec<String>) -> Self {
|
||||
NewActionDialog { id: dialog_id(KEY), form: Form::new(fields, check), sets }
|
||||
}
|
||||
|
||||
/// Gives the Action Set row the app's set names.
|
||||
pub(crate) fn set_sets(&mut self, sets: &[String]) {
|
||||
if self.sets != sets {
|
||||
self.sets = sets.to_vec();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether New Action can open: there is a set to put the action in and nothing is recording.
|
||||
pub fn can_open(app: &VectorcraftApp) -> bool {
|
||||
!app.ui.action_sets.is_empty() && app.ui.recording.is_none()
|
||||
!app.ui.actions.sets().is_empty() && app.ui.recording.is_none()
|
||||
}
|
||||
|
||||
/// Opens New Action for the current set, else the first set, named "Action N" with the first
|
||||
/// number from the set's action count plus one that no action of the set uses, with no function
|
||||
/// key and no color.
|
||||
/// "Action N" with the first number from the set's action count plus one that no action of the
|
||||
/// list uses: action names are unique in the whole list.
|
||||
fn free_name(list: &ActionList, set: &str) -> String {
|
||||
let taken = |n: usize| list.actions().iter().any(|action| action.name == format!("Action {n}"));
|
||||
let n = (model::members(list, set).len() + 1..).find(|&n| !taken(n)).unwrap_or(1);
|
||||
format!("Action {n}")
|
||||
}
|
||||
|
||||
/// Opens New Action for the current set, else the first set, named by [`free_name`], with no
|
||||
/// function key and no color.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
if app.ui.recording.is_some() {
|
||||
return Err("an action is already recording".into());
|
||||
}
|
||||
let len = app.ui.action_sets.len();
|
||||
let set = app.ui.action_set.filter(|&s| s < len).unwrap_or(0);
|
||||
let Some(s) = app.ui.action_sets.get(set) else { return Err("no such action set".into()) };
|
||||
let taken = |n: usize| s.actions.iter().any(|a| a.name == format!("Action {n}"));
|
||||
let n = (s.actions.len() + 1..).find(|&n| !taken(n)).unwrap_or(1);
|
||||
let fields = json!({"set": set, "name": format!("Action {n}"), "key": 0, "cmd": false, "shift": false, "color": "", "automaticAlignTo": false});
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
Ok(())
|
||||
let sets: Vec<String> = app.ui.actions.sets().into_iter().map(str::to_owned).collect();
|
||||
// PLAN: assumed `app.ui.action_set` is the current set's name (menus-w13 `deserialize_current_set`).
|
||||
let set = app.ui.action_set.as_deref().and_then(|current| sets.iter().position(|s| s == current)).unwrap_or(0);
|
||||
let name = sets.get(set).map(|set| free_name(&app.ui.actions, set)).ok_or("no such action set")?;
|
||||
let fields = NewActionFields { set, name, options: ActionOptions::default() };
|
||||
super::actions::open(app, NewActionDialog::new(fields, sets))
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
widgets::label_row(ui, "Name:", LABEL_W, |ui| {
|
||||
super::form::text(ui, d, "name", 200.0);
|
||||
});
|
||||
let names: Vec<&str> = app.ui.action_sets.iter().map(|s| s.name.as_str()).collect();
|
||||
let set = d.fields.get("set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
let shown = set.and_then(|s| names.get(s)).copied().unwrap_or_default();
|
||||
widgets::label_row(ui, "Action Set:", LABEL_W, |ui| {
|
||||
if let Some(i) = widgets::dropdown_names(ui, "action-new-set", shown, &names, 200.0) {
|
||||
d.fields.insert("set".into(), json!(i));
|
||||
}
|
||||
});
|
||||
key_and_color(ui, d);
|
||||
automatic_align_options(ui, d);
|
||||
false
|
||||
}
|
||||
impl ActionDialog for NewActionDialog {
|
||||
type Answer = NewActionFields;
|
||||
|
||||
/// The Function Key and Color rows of New Action and Action Options show errors for invalid keys.
|
||||
pub(super) fn key_and_color(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let key = d.fields.get("key").and_then(Value::as_u64).unwrap_or(0);
|
||||
let none = tl!("None");
|
||||
let keys: Vec<String> = std::iter::once(none.to_string()).chain((1..=FUNCTION_KEYS).map(|n| format!("F{n}"))).collect();
|
||||
let labels: Vec<&str> = keys.iter().map(String::as_str).collect();
|
||||
let shown = usize::try_from(key).ok().and_then(|k| labels.get(k)).copied().unwrap_or(none);
|
||||
let modifier = if crate::keymap::platform() == craft_keymap::Platform::Mac { "⌘" } else { "Ctrl" };
|
||||
widgets::label_row(ui, "Function Key:", LABEL_W, |ui| {
|
||||
if let Some(i) = widgets::dropdown_names(ui, "action-key", shown, &labels, 70.0) {
|
||||
d.fields.insert("key".into(), json!(i));
|
||||
}
|
||||
super::form::check(ui, d, "cmd", modifier);
|
||||
super::form::check(ui, d, "shift", "Shift");
|
||||
});
|
||||
let picked = FunctionKey::from_params(&json!({"key": key, "cmd": d.bool("cmd"), "shift": d.bool("shift")}));
|
||||
if let Ok(Some(k)) = picked
|
||||
&& let Some(message) = crate::panels::actions::key_error(k)
|
||||
{
|
||||
widgets::label_row(ui, "", LABEL_W, |ui| {
|
||||
ui.label(crate::i18n::msg(&message));
|
||||
});
|
||||
fn take_ok(&mut self) -> Option<NewActionFields> {
|
||||
self.form.take()
|
||||
}
|
||||
let colors: Vec<(&str, &str)> = std::iter::once(("", "None")).chain(COLORS).collect();
|
||||
super::form::choice(ui, d, "color", "Color:", (LABEL_W, 120.0), &colors);
|
||||
}
|
||||
|
||||
/// The Align playback option shared by New Action and Action Options.
|
||||
pub(super) fn automatic_align_options(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
super::form::check(ui, d, "automaticAlignTo", "Choose Align To at playback");
|
||||
widgets::dim_label(ui, "Align steps use the key object, key anchor or key guide when one is set.");
|
||||
widgets::dim_label(ui, "With one whole object selected and no key, they use the artboard.");
|
||||
widgets::dim_label(ui, "Otherwise they use the selection.");
|
||||
}
|
||||
|
||||
/// The function key and color params the dialog's fields give, as `ui.action.new` and
|
||||
/// `ui.action.options` take them.
|
||||
pub(super) fn key_and_color_params(d: &Dialog) -> Value {
|
||||
json!({
|
||||
"key": d.fields.get("key").and_then(Value::as_u64).unwrap_or(0),
|
||||
"cmd": d.bool("cmd"),
|
||||
"shift": d.bool("shift"),
|
||||
"color": d.str("color"),
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let name = d.str("name").trim().to_string();
|
||||
// Record is disabled without a name; `ui.dialog.confirm` keeps the dialog open the same way.
|
||||
if name.is_empty() {
|
||||
return Ok(Value::Null);
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
let mut p = key_and_color_params(d);
|
||||
p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null);
|
||||
p["name"] = json!(name);
|
||||
if let Some(value) = d.fields.get("automaticAlignTo") {
|
||||
p["automaticAlignTo"] = value.clone();
|
||||
|
||||
fn run(app: &mut VectorcraftApp, fields: NewActionFields) -> Result<(), String> {
|
||||
let mut params = key_and_color_params(&fields.options);
|
||||
params["set"] = json!(fields.set);
|
||||
params["name"] = json!(fields.name.trim());
|
||||
app.run(NEW_ACTION, params).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for NewActionDialog {
|
||||
type Result = NewActionFields;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<NewActionFields>> {
|
||||
let sets: Vec<Entry<usize>> = self.sets.iter().enumerate().map(|(i, set)| Entry::new(i, Label::from(set.clone()))).collect();
|
||||
self.form.show(ui, label("New Action"), Some(label("Record")), |ui, fields| {
|
||||
FieldGroup::new(label("New Action")).show(ui, |ui, _| {
|
||||
Field::new(label("Name:")).show(ui, |ui, _| {
|
||||
TextField::new(label("Name:"), Bind::bound(&mut fields.name)).show(ui);
|
||||
});
|
||||
Field::new(label("Action Set:")).show(ui, |ui, _| {
|
||||
if let Some(set) = Select::new(label("Action Set:"), Bind::given(fields.set), &sets).show(ui).value().copied() {
|
||||
fields.set = set;
|
||||
}
|
||||
});
|
||||
key_and_color(ui, &mut fields.options);
|
||||
automatic_align_options(ui, &mut fields.options);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<NewActionFields> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
self.form.json_fields()
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
self.form.set_field(ctx, field, value)
|
||||
}
|
||||
app.run(crate::panels::actions::NEW_ACTION, p)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -3,46 +3,123 @@
|
||||
//! Fields: `speed` (`accelerated`, `step` or `pause`) and `seconds`, the pause between steps with
|
||||
//! `pause`. OK sets them; an invalid value is an error, and the dialog stays open.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use craft::behavior::NumberCodec;
|
||||
use craft::ui::choice::{Radio, RadioGroup};
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::FieldGroup;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::runtime::env::{Env, Label};
|
||||
use craft::ui::text::NumberField;
|
||||
use egui::{Context, Ui};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::DialogSpec;
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::actions::{ActionDialog, Form, label, open_or_say};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::actions::{PAUSE_SECONDS, PLAYBACK_OPTIONS, PlaybackOptions, PlaybackSpeed};
|
||||
|
||||
/// The dialog kind of Playback Options.
|
||||
pub const KIND: &str = "actionPlayback";
|
||||
/// The key the dialog answers for.
|
||||
const KEY: &str = "actionPlayback";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Playback Options").into(), body, confirm, min_width: 260.0, ..DialogSpec::FORM };
|
||||
/// The speeds, with the id their radio button has.
|
||||
// PLAN: assumed `PlaybackSpeed` is re-exported from `panels::actions` beside `PlaybackOptions` (menus-w15).
|
||||
const SPEEDS: [(PlaybackSpeed, &str); 3] =
|
||||
[(PlaybackSpeed::Accelerated, "accelerated"), (PlaybackSpeed::Step, "step"), (PlaybackSpeed::Pause, "pause")];
|
||||
|
||||
/// OK is always on; the command refuses a pause outside its range.
|
||||
fn check(_: &PlaybackOptions) -> Option<Label> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The Playback Options dialog on the dialog host.
|
||||
pub struct PlaybackDialog {
|
||||
id: DialogId,
|
||||
form: Form<PlaybackOptions>,
|
||||
}
|
||||
|
||||
/// Open Playback Options with the speed and pause actions play with now.
|
||||
pub fn open(app: &mut VectorcraftApp) {
|
||||
let o = app.ui.action_playback;
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!({"speed": o.speed, "seconds": o.seconds})));
|
||||
let dialog = PlaybackDialog { id: dialog_id(KEY), form: Form::new(app.ui.action_playback, check) };
|
||||
open_or_say(app, dialog);
|
||||
}
|
||||
|
||||
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let speed = d.str("speed");
|
||||
for (value, label) in [("accelerated", tl!("Accelerated")), ("step", tl!("Step by Step"))] {
|
||||
if widgets::radio(ui, label, speed == value, true) {
|
||||
d.fields.insert("speed".into(), json!(value));
|
||||
}
|
||||
impl ActionDialog for PlaybackDialog {
|
||||
type Answer = PlaybackOptions;
|
||||
|
||||
fn take_ok(&mut self) -> Option<PlaybackOptions> {
|
||||
self.form.take()
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, options: PlaybackOptions) -> Result<(), String> {
|
||||
let params = serde_json::to_value(options).map_err(|e| e.to_string())?;
|
||||
app.run(PLAYBACK_OPTIONS, params).map(|_| ())
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let pause = tl!("Pause For");
|
||||
if widgets::radio(ui, pause, speed == "pause", true) {
|
||||
d.fields.insert("speed".into(), json!("pause"));
|
||||
}
|
||||
let range = f64::from(*crate::panels::actions::PAUSE_SECONDS.start())..=f64::from(*crate::panels::actions::PAUSE_SECONDS.end());
|
||||
if let Some(n) = widgets::range_field_named(ui, "action-pause-seconds", Some(pause), d.f64("seconds", *range.start()), range, "s", 0, 50.0) {
|
||||
d.fields.insert("seconds".into(), json!(n as u64));
|
||||
}
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let params = json!({"speed": d.str("speed"), "seconds": d.fields.get("seconds").cloned().unwrap_or(Value::Null)});
|
||||
let r = app.run(crate::panels::actions::PLAYBACK_OPTIONS, params)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(r)
|
||||
impl StackDialog for PlaybackDialog {
|
||||
type Result = PlaybackOptions;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<PlaybackOptions>> {
|
||||
let units = Env::of(ui).units();
|
||||
let range = f64::from(*PAUSE_SECONDS.start())..=f64::from(*PAUSE_SECONDS.end());
|
||||
self.form.show(ui, label("Playback Options"), None, |ui, options| {
|
||||
FieldGroup::new(label("Playback Options")).show(ui, |ui, _| {
|
||||
let chosen = SPEEDS.iter().find(|(speed, _)| *speed == options.speed).map_or("accelerated", |(_, id)| *id);
|
||||
let group = RadioGroup::new(label("Speed"), Bind::given(chosen.to_owned())).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Radio::new("accelerated".to_owned()).label(label("Accelerated")).show(ui);
|
||||
Radio::new("step".to_owned()).label(label("Step by Step")).show(ui);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Radio::new("pause".to_owned()).label(label("Pause For")).show(ui);
|
||||
let seconds = NumberField::new(label("Pause For"), Bind::given(Some(f64::from(options.seconds))))
|
||||
.codec(NumberCodec::new(units.reader(None), 0))
|
||||
.range(range.clone())
|
||||
.id_salt("seconds")
|
||||
.show(ui)
|
||||
.edit
|
||||
.value()
|
||||
.copied()
|
||||
.flatten();
|
||||
if let Some(seconds) = seconds.filter(|seconds| seconds.is_finite()) {
|
||||
options.seconds = seconds.round().clamp(f64::from(*PAUSE_SECONDS.start()), f64::from(*PAUSE_SECONDS.end())) as u32;
|
||||
}
|
||||
Text::new("s").show(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
if let Some((speed, _)) = group.output.value().and_then(|id| SPEEDS.iter().find(|(_, listed)| *listed == id.as_str())) {
|
||||
options.speed = *speed;
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<PlaybackOptions> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
self.form.json_fields()
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
self.form.set_field(ctx, field, value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,61 +3,114 @@
|
||||
//!
|
||||
//! Its fields: `note`, `caseSensitive`, `wholeWord`, and `set`, `action` and `step`, the place of the
|
||||
//! new step (no `set` and `action`: the recording in progress). OK is off while the note is empty.
|
||||
//! An invalid note or place is an error, and the dialog stays open.
|
||||
//! An invalid place is an error, and the dialog stays open.
|
||||
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::DialogSpec;
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::actions::{ActionDialog, Form, Target, label, merged, open_or_say};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::actions::INSERT_SELECT_OBJECT;
|
||||
|
||||
/// The dialog kind of Set Selection.
|
||||
pub const KIND: &str = "actionSelectObject";
|
||||
/// The key the dialog answers for.
|
||||
const KEY: &str = "actionSelectObject";
|
||||
|
||||
/// The width of the Note label column.
|
||||
const LABEL_W: f32 = 70.0;
|
||||
/// What Set Selection edits.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SelectObjectFields {
|
||||
/// The words the objects' Attributes notes are searched for.
|
||||
pub note: String,
|
||||
/// Whether the search tells upper and lower case apart.
|
||||
pub case_sensitive: bool,
|
||||
/// Whether a match must be a whole word.
|
||||
pub whole_word: bool,
|
||||
}
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Set Selection").into(),
|
||||
body,
|
||||
confirm,
|
||||
ok_enabled: Some(|_, d| !d.str("note").trim().is_empty()),
|
||||
min_width: 340.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
/// Why OK is off: nothing to search for.
|
||||
fn check(fields: &SelectObjectFields) -> Option<Label> {
|
||||
fields.note.trim().is_empty().then(|| label("Enter the note to select by"))
|
||||
}
|
||||
|
||||
/// The Set Selection dialog on the dialog host.
|
||||
pub struct SelectObjectDialog {
|
||||
id: DialogId,
|
||||
/// Where the step goes.
|
||||
pub target: Target,
|
||||
form: Form<SelectObjectFields>,
|
||||
}
|
||||
|
||||
/// Opens Set Selection for action `target` as (set, action), after `step`, else for the recording
|
||||
/// in progress.
|
||||
pub fn open(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option<usize>) {
|
||||
let mut fields = json!({"note": "", "caseSensitive": false, "wholeWord": false});
|
||||
if let Some((set, action)) = target {
|
||||
fields["set"] = json!(set);
|
||||
fields["action"] = json!(action);
|
||||
if let Some(step) = step {
|
||||
fields["step"] = json!(step);
|
||||
}
|
||||
}
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
let dialog = SelectObjectDialog { id: dialog_id(KEY), target: Target::new(target, step), form: Form::new(SelectObjectFields::default(), check) };
|
||||
open_or_say(app, dialog);
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
widgets::label_row(ui, "Note:", LABEL_W, |ui| {
|
||||
super::form::text(ui, d, "note", 240.0);
|
||||
});
|
||||
super::form::check(ui, d, "caseSensitive", "Case Sensitive");
|
||||
super::form::check(ui, d, "wholeWord", "Whole Word");
|
||||
false
|
||||
impl ActionDialog for SelectObjectDialog {
|
||||
type Answer = (Target, SelectObjectFields);
|
||||
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.form.take().map(|fields| (self.target, fields))
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, (target, fields): Self::Answer) -> Result<(), String> {
|
||||
let mut params = json!({"note": fields.note, "caseSensitive": fields.case_sensitive, "wholeWord": fields.whole_word});
|
||||
target.add_to(&mut params);
|
||||
app.run(INSERT_SELECT_OBJECT, params).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
// The fields go as they are, so a field of another type is an error rather than a default.
|
||||
let mut params = json!({});
|
||||
for key in ["note", "caseSensitive", "wholeWord", "set", "action", "step"] {
|
||||
if let Some(value) = d.fields.get(key) {
|
||||
params[key] = value.clone();
|
||||
impl StackDialog for SelectObjectDialog {
|
||||
type Result = SelectObjectFields;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<SelectObjectFields>> {
|
||||
self.form.show(ui, label("Set Selection"), None, |ui, fields| {
|
||||
FieldGroup::new(label("Set Selection")).show(ui, |ui, _| {
|
||||
Field::new(label("Note:")).show(ui, |ui, _| {
|
||||
TextField::new(label("Note:"), Bind::bound(&mut fields.note)).show(ui);
|
||||
});
|
||||
Checkbox::new(Bind::bound(&mut fields.case_sensitive)).label(label("Case Sensitive")).show(ui);
|
||||
Checkbox::new(Bind::bound(&mut fields.whole_word)).label(label("Whole Word")).show(ui);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<SelectObjectFields> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
Some(merged(self.form.json_fields()?, self.target.json()))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
match self.target.set_field(field, &value) {
|
||||
Some(done) => done,
|
||||
None => self.form.set_field(ctx, field, value),
|
||||
}
|
||||
}
|
||||
let r = app.run(crate::panels::actions::INSERT_SELECT_OBJECT, params)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -1,121 +1,208 @@
|
||||
//! Actions panel › Create New Set (and ≡ › New Set…), ≡ › Set Options… and ≡ › Action Options…:
|
||||
//! the name of a new action set, of the current one, or of the selected action.
|
||||
//!
|
||||
//! Fields: `set` (the index of the set renamed, or of the action's set; none for a new set),
|
||||
//! `action` (the index of the action renamed, in `set`; none for a set) and `name`. Action Options
|
||||
//! also holds the action's function key and color, as New Action does (`key`, `cmd`, `shift`,
|
||||
//! `color`, see [`super::action_new`]). OK adds the set and makes it the current
|
||||
//! one, renames the set, or changes the action's name, function key and color
|
||||
//! (`ui.action.options`). An invalid `set`, `action` or function key is an error, and so is a name
|
||||
//! that would give the set a file that Load Actions… refuses (larger than 8 MiB). OK then changes no
|
||||
//! set or action, and the dialog stays open. `automaticAlignTo` enables the live-selection Align
|
||||
//! reference at playback without changing recorded targets.
|
||||
//! Fields: `set` (the index of the set renamed, or of the action's set; not for a new set),
|
||||
//! `action` (the index of the action renamed, in `set`; only for Action Options) and `name`. Action
|
||||
//! Options also holds the action's function key and color (`key`, `cmd`, `shift`, `color`,
|
||||
//! `automaticAlignTo`, see [`ActionOptions`]). OK adds the set and makes it the current one,
|
||||
//! renames the set, or changes the action's name, function key and color (`ui.action.options`).
|
||||
//! An invalid `set`, `action` or function key is an error, and so is a name the list refuses. OK
|
||||
//! then changes no set or action, and the dialog stays open.
|
||||
|
||||
use craft::ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::DialogSpec;
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::actions::{
|
||||
ActionDialog, ActionOptions, Form, OPTION_KEYS, automatic_align_options, key_and_color, key_and_color_params, key_reason, label, merged,
|
||||
open_or_say, set_index,
|
||||
};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::actions::{ACTION_OPTIONS, edits, model};
|
||||
|
||||
/// The dialog kind of New Set, Set Options and Action Options.
|
||||
pub const KIND: &str = "actionSetOptions";
|
||||
/// The key the dialog answers for.
|
||||
const KEY: &str = "actionSetOptions";
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading, body, confirm, ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()), min_width: 300.0, ..DialogSpec::FORM };
|
||||
/// What the dialog is for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SetOptionsKind {
|
||||
/// A set to add.
|
||||
NewSet,
|
||||
/// The name of a set.
|
||||
Set,
|
||||
/// The name, function key and color of an action.
|
||||
Action,
|
||||
}
|
||||
|
||||
fn heading(d: &Dialog) -> String {
|
||||
if d.fields.contains_key("action") {
|
||||
tl!("Action Options").into()
|
||||
} else if d.fields.contains_key("set") {
|
||||
tl!("Set Options").into()
|
||||
} else {
|
||||
tl!("New Set").into()
|
||||
/// What the dialog edits.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SetOptionsFields {
|
||||
/// The set's or the action's name.
|
||||
pub name: String,
|
||||
/// The function key, color and Align choice; only an action has them.
|
||||
#[serde(flatten)]
|
||||
pub options: ActionOptions,
|
||||
}
|
||||
|
||||
/// Why OK is off: no name, or a function key the system keeps.
|
||||
fn check(fields: &SetOptionsFields) -> Option<Label> {
|
||||
if fields.name.trim().is_empty() {
|
||||
return Some(label("Enter a name"));
|
||||
}
|
||||
key_reason(&fields.options)
|
||||
}
|
||||
|
||||
/// The New Set, Set Options and Action Options dialog on the dialog host.
|
||||
pub struct SetOptionsDialog {
|
||||
id: DialogId,
|
||||
/// What the dialog is for.
|
||||
pub kind: SetOptionsKind,
|
||||
/// The index of the set: of the one renamed, or of the action's; none for a new set.
|
||||
pub set: Option<usize>,
|
||||
/// The index of the action in its set; only for Action Options.
|
||||
pub action: Option<usize>,
|
||||
form: Form<SetOptionsFields>,
|
||||
}
|
||||
|
||||
impl SetOptionsDialog {
|
||||
fn new(kind: SetOptionsKind, set: Option<usize>, action: Option<usize>, fields: SetOptionsFields) -> Self {
|
||||
SetOptionsDialog { id: dialog_id(KEY), kind, set, action, form: Form::new(fields, check) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Open New Set, named "Set N" with the first number no set uses.
|
||||
pub fn open_new(app: &mut VectorcraftApp) {
|
||||
let taken = |n: usize| app.ui.action_sets.iter().any(|s| s.name == format!("Set {n}"));
|
||||
let n = (1..).find(|&n| !taken(n)).unwrap_or(1);
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!({"name": format!("Set {n}")})));
|
||||
let sets = app.ui.actions.sets();
|
||||
let n = (1..).find(|n| !sets.contains(&format!("Set {n}").as_str())).unwrap_or(1);
|
||||
let fields = SetOptionsFields { name: format!("Set {n}"), ..SetOptionsFields::default() };
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, fields));
|
||||
}
|
||||
|
||||
/// Open Set Options for the set at `set`, if there is one.
|
||||
pub fn open(app: &mut VectorcraftApp, set: usize) {
|
||||
if let Some(s) = app.ui.action_sets.get(set) {
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!({"set": set, "name": s.name})));
|
||||
if let Some(name) = model::set_name(&app.ui.actions, set) {
|
||||
let fields = SetOptionsFields { name: name.to_owned(), ..SetOptionsFields::default() };
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, fields));
|
||||
}
|
||||
}
|
||||
|
||||
/// Open Action Options for the action at `action` in set `set`, if there is one, with its name,
|
||||
/// function key and color.
|
||||
pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) {
|
||||
if let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)) {
|
||||
let (key, cmd, shift) = a.key.map_or((0, false, false), |k| (k.key, k.cmd, k.shift));
|
||||
let color = a.color.clone().unwrap_or_default();
|
||||
let fields = json!({"set": set, "action": action, "name": a.name, "key": key, "cmd": cmd, "shift": shift, "color": color, "automaticAlignTo": a.automatic_align_to});
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
}
|
||||
let Some(a) = model::flat(&app.ui.actions, set, action).and_then(|flat| app.ui.actions.action(flat)) else { return };
|
||||
let key = model::function_key(a);
|
||||
let options = ActionOptions {
|
||||
key: key.map_or(0, |k| k.key),
|
||||
cmd: key.is_some_and(|k| k.cmd),
|
||||
shift: key.is_some_and(|k| k.shift),
|
||||
color: a.color,
|
||||
automatic_align_to: model::automatic_align_to(a),
|
||||
};
|
||||
let fields = SetOptionsFields { name: a.name.clone(), options };
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), fields));
|
||||
}
|
||||
|
||||
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
// Action Options lines its rows up with the Function Key and Color rows.
|
||||
let action = d.fields.contains_key("action") && d.fields.contains_key("key");
|
||||
widgets::label_row(ui, "Name:", if action { 90.0 } else { 50.0 }, |ui| {
|
||||
super::form::text(ui, d, "name", 200.0);
|
||||
});
|
||||
if action {
|
||||
super::action_new::key_and_color(ui, d);
|
||||
super::action_new::automatic_align_options(ui, d);
|
||||
}
|
||||
false
|
||||
}
|
||||
impl ActionDialog for SetOptionsDialog {
|
||||
/// What OK files, with the kind and place the dialog had.
|
||||
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, SetOptionsFields);
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let name = d.str("name").trim().to_string();
|
||||
// OK is disabled without a name; `ui.dialog.confirm` keeps the dialog open the same way.
|
||||
if name.is_empty() {
|
||||
return Ok(Value::Null);
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.form.take().map(|fields| (self.kind, self.set, self.action, fields))
|
||||
}
|
||||
// The fields the dialog holds choose what OK does, as they choose its heading.
|
||||
if d.fields.contains_key("action") {
|
||||
// A dialog without the key fields (made by `ui.dialog.set`) keeps the key and color.
|
||||
let mut p = if d.fields.contains_key("key") { super::action_new::key_and_color_params(d) } else { json!({}) };
|
||||
p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null);
|
||||
p["action"] = d.fields.get("action").cloned().unwrap_or(Value::Null);
|
||||
p["name"] = json!(name);
|
||||
if let Some(value) = d.fields.get("automaticAlignTo") {
|
||||
p["automaticAlignTo"] = value.clone();
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, (kind, set, action, fields): Self::Answer) -> Result<(), String> {
|
||||
match kind {
|
||||
SetOptionsKind::NewSet => edits::new_set(app, &fields.name),
|
||||
SetOptionsKind::Set => {
|
||||
let current = set.and_then(|set| model::set_name(&app.ui.actions, set)).ok_or("no such action set")?.to_owned();
|
||||
edits::rename_set(app, ¤t, &fields.name)
|
||||
}
|
||||
SetOptionsKind::Action => {
|
||||
let mut params = key_and_color_params(&fields.options);
|
||||
params["set"] = json!(set);
|
||||
params["action"] = json!(action);
|
||||
params["name"] = json!(fields.name.trim());
|
||||
app.run(ACTION_OPTIONS, params).map(|_| ())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for SetOptionsDialog {
|
||||
type Result = SetOptionsFields;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<SetOptionsFields>> {
|
||||
let kind = self.kind;
|
||||
let title = match kind {
|
||||
SetOptionsKind::Action => label("Action Options"),
|
||||
SetOptionsKind::Set => label("Set Options"),
|
||||
SetOptionsKind::NewSet => label("New Set"),
|
||||
};
|
||||
self.form.show(ui, title.clone(), None, |ui, fields| {
|
||||
FieldGroup::new(title.clone()).show(ui, |ui, _| {
|
||||
Field::new(label("Name:")).show(ui, |ui, _| {
|
||||
TextField::new(label("Name:"), Bind::bound(&mut fields.name)).show(ui);
|
||||
});
|
||||
if kind == SetOptionsKind::Action {
|
||||
key_and_color(ui, &mut fields.options);
|
||||
automatic_align_options(ui, &mut fields.options);
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<SetOptionsFields> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
/// The fields the kind has: the place and name, and the action's options for Action Options.
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
let mut fields = self.form.json_fields()?;
|
||||
if self.kind != SetOptionsKind::Action
|
||||
&& let Some(map) = fields.as_object_mut()
|
||||
{
|
||||
for key in OPTION_KEYS {
|
||||
map.remove(key);
|
||||
}
|
||||
}
|
||||
let mut place = serde_json::Map::new();
|
||||
if self.kind != SetOptionsKind::NewSet {
|
||||
place.insert("set".into(), json!(self.set));
|
||||
}
|
||||
if self.kind == SetOptionsKind::Action {
|
||||
place.insert("action".into(), json!(self.action));
|
||||
}
|
||||
Some(merged(fields, Value::Object(place)))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
match field {
|
||||
"set" if self.kind != SetOptionsKind::NewSet => set_index(&mut self.set, field, &value),
|
||||
"action" if self.kind == SetOptionsKind::Action => set_index(&mut self.action, field, &value),
|
||||
_ if OPTION_KEYS.contains(&field) && self.kind != SetOptionsKind::Action => Err(FieldRefusal::Inactive.message(field)),
|
||||
_ => self.form.set_field(ctx, field, value),
|
||||
}
|
||||
app.run(crate::panels::actions::ACTION_OPTIONS, p)?;
|
||||
} else if let Some(set) = d.fields.get("set") {
|
||||
let i = set.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < app.ui.action_sets.len()).ok_or("no such action set")?;
|
||||
let mut edited = app.ui.action_sets[i].clone();
|
||||
edited.name = name;
|
||||
crate::panels::actions::edit_keeps_set_loadable(app, Some(i), &edited)?;
|
||||
app.ui.action_sets[i] = edited;
|
||||
// A recording into the set measures its file again.
|
||||
app.ui.recording_base = None;
|
||||
} else {
|
||||
let set = crate::panels::actions::ActionSet::new(name, vec![]);
|
||||
crate::panels::actions::edit_keeps_set_loadable(app, None, &set)?;
|
||||
app.ui.action_sets.push(set);
|
||||
app.ui.action_set = Some(app.ui.action_sets.len() - 1);
|
||||
}
|
||||
app.ui.dialog = None;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The heading names the dialog by what it holds: an action, a set, or neither.
|
||||
#[test]
|
||||
fn the_heading_names_action_options_set_options_or_new_set() {
|
||||
let heading_of = |fields: Value| heading(&Dialog::new(KIND, fields));
|
||||
assert_eq!(heading_of(json!({"set": 1, "action": 0, "name": "Nudge"})), "Action Options");
|
||||
assert_eq!(heading_of(json!({"set": 1, "name": "Mine"})), "Set Options");
|
||||
assert_eq!(heading_of(json!({"name": "Set 1"})), "New Set");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,103 +5,151 @@
|
||||
//! new stop (no `set` and `action`: the recording in progress). An invalid place is an error, and
|
||||
//! the dialog stays open.
|
||||
//!
|
||||
//! The message box's fields: `action` (the action's name, shown as the heading), `message` and
|
||||
//! `allowContinue`. Stop or Cancel closes it, and the playback keeps waiting for Play Current
|
||||
//! Selection or Stop Playing/Recording. With `allowContinue`, Continue or `ui.dialog.confirm` plays
|
||||
//! on; without it, `ui.dialog.confirm` presses Stop.
|
||||
//! The message box is a standard prompt titled with the action's name. Stop or Cancel closes it, and
|
||||
//! the playback keeps waiting for Play Current Selection or Stop Playing/Recording. With
|
||||
//! `allowContinue`, Continue plays on.
|
||||
|
||||
use craft::ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldOk, PromptChoice, StandardPrompt, StackDialog, dialog_id};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{DialogAction, DialogSpec};
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::actions::{ActionDialog, Form, Target, label, merged, open_or_say};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::actions::INSERT_STOP;
|
||||
|
||||
/// The dialog kind of Record Stop.
|
||||
pub const RECORD_KIND: &str = "actionStopRecord";
|
||||
|
||||
/// The dialog kind of a stop's message box.
|
||||
/// The key of a stop's message box.
|
||||
pub const MESSAGE_KIND: &str = "actionStopMessage";
|
||||
|
||||
/// The width of Record Stop's label column.
|
||||
const LABEL_W: f32 = 70.0;
|
||||
/// The key Record Stop answers for.
|
||||
const KEY: &str = "actionStopRecord";
|
||||
|
||||
pub(super) const RECORD_SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Record Stop").into(), body: record_body, confirm: record_confirm, min_width: 340.0, ..DialogSpec::FORM };
|
||||
/// A stop's message box on the dialog host. The wrapper keeps its answer apart from the app's other
|
||||
/// prompts, which take the bare [`StandardPrompt`]'s.
|
||||
pub(crate) struct StopMessage(pub(crate) StandardPrompt);
|
||||
|
||||
pub(super) const MESSAGE_SPEC: DialogSpec = DialogSpec {
|
||||
heading: |d| d.str("action"),
|
||||
body_with_actions: Some(message_body),
|
||||
confirm: message_confirm,
|
||||
ok: None,
|
||||
min_width: 300.0,
|
||||
max_width: Some(460.0),
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
// PLAN: assumed `wrapped_dialog!(Type, KEY)` makes `Type` a `StackDialog` over its inner prompt with the prompt's `Result` (`PromptAnswer`).
|
||||
crate::dialogs::confirm::wrapped_dialog!(StopMessage, MESSAGE_KIND);
|
||||
|
||||
/// What Record Stop edits.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RecordStopFields {
|
||||
/// The text playback shows at the stop.
|
||||
pub message: String,
|
||||
/// Whether the message box offers Continue.
|
||||
pub allow_continue: bool,
|
||||
}
|
||||
|
||||
/// OK is always on: a stop may have no message.
|
||||
fn check(_: &RecordStopFields) -> Option<Label> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The Record Stop dialog on the dialog host.
|
||||
pub struct RecordStopDialog {
|
||||
id: DialogId,
|
||||
/// Where the stop goes.
|
||||
// PLAN: menus-w18 reads the place as `d.set`, `d.action`, `d.step` (usize); the dialog keeps it as a `Target` (options) because no place means the recording.
|
||||
pub target: Target,
|
||||
form: Form<RecordStopFields>,
|
||||
}
|
||||
|
||||
/// Opens Record Stop for action `target` as (set, action), after `step`, else for the recording in
|
||||
/// progress.
|
||||
pub fn open_record(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option<usize>) {
|
||||
let mut fields = json!({"message": "", "allowContinue": false});
|
||||
if let Some((set, action)) = target {
|
||||
fields["set"] = json!(set);
|
||||
fields["action"] = json!(action);
|
||||
if let Some(step) = step {
|
||||
fields["step"] = json!(step);
|
||||
}
|
||||
}
|
||||
app.ui.dialog = Some(Dialog::new(RECORD_KIND, fields));
|
||||
let dialog = RecordStopDialog { id: dialog_id(KEY), target: Target::new(target, step), form: Form::new(RecordStopFields::default(), check) };
|
||||
open_or_say(app, dialog);
|
||||
}
|
||||
|
||||
fn record_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
widgets::label_row(ui, "Message:", LABEL_W, |ui| {
|
||||
super::form::text(ui, d, "message", 240.0);
|
||||
});
|
||||
super::form::check(ui, d, "allowContinue", "Allow Continue");
|
||||
false
|
||||
impl ActionDialog for RecordStopDialog {
|
||||
type Answer = (Target, RecordStopFields);
|
||||
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.form.take().map(|fields| (self.target, fields))
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, (target, fields): Self::Answer) -> Result<(), String> {
|
||||
let mut params = json!({"message": fields.message, "allowContinue": fields.allow_continue});
|
||||
target.add_to(&mut params);
|
||||
app.run(INSERT_STOP, params).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
fn record_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut params = json!({"message": d.str("message"), "allowContinue": d.bool("allowContinue")});
|
||||
for key in ["set", "action", "step"] {
|
||||
if let Some(value) = d.fields.get(key) {
|
||||
params[key] = value.clone();
|
||||
impl StackDialog for RecordStopDialog {
|
||||
type Result = RecordStopFields;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<RecordStopFields>> {
|
||||
self.form.show(ui, label("Record Stop"), None, |ui, fields| {
|
||||
FieldGroup::new(label("Record Stop")).show(ui, |ui, _| {
|
||||
Field::new(label("Message:")).show(ui, |ui, _| {
|
||||
TextField::new(label("Message:"), Bind::bound(&mut fields.message)).show(ui);
|
||||
});
|
||||
Checkbox::new(Bind::bound(&mut fields.allow_continue)).label(label("Allow Continue")).show(ui);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<RecordStopFields> {
|
||||
self.form.confirm()
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.form.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
Some(merged(self.form.json_fields()?, self.target.json()))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
match self.target.set_field(field, &value) {
|
||||
Some(done) => done,
|
||||
None => self.form.set_field(ctx, field, value),
|
||||
}
|
||||
}
|
||||
let r = app.run(crate::panels::actions::INSERT_STOP, params)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Shows the message box of a stop in the action named `action`.
|
||||
pub(crate) fn open_message(app: &mut VectorcraftApp, action: &str, message: &str, allow_continue: bool) {
|
||||
app.ui.dialog = Some(Dialog::new(MESSAGE_KIND, json!({"action": action, "message": message, "allowContinue": allow_continue})));
|
||||
let mut prompt = StandardPrompt::custom(Label::from(message.to_owned()))
|
||||
.title(Label::from(action.to_owned()))
|
||||
.paragraph(label("Press Play Current Selection in the Actions panel to go on."));
|
||||
if allow_continue {
|
||||
prompt = prompt.button(PromptChoice::Proceed, label("Continue"));
|
||||
}
|
||||
open_or_say(app, StopMessage(prompt.button(PromptChoice::Cancel, label("Stop"))));
|
||||
}
|
||||
|
||||
fn message_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction {
|
||||
let message = d.str("message");
|
||||
if !message.is_empty() {
|
||||
ui.label(message);
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
ui.label(egui::RichText::new(tl!("Press Play Current Selection in the Actions panel to go on.")).color(Tokens::get(ui.ctx()).text_dim));
|
||||
ui.add_space(16.0);
|
||||
let mut action = DialogAction::None;
|
||||
ui.horizontal(|ui| {
|
||||
if d.bool("allowContinue") && widgets::primary_button_enabled(ui, tl!("Continue"), true).clicked() {
|
||||
action = DialogAction::Confirm;
|
||||
}
|
||||
if widgets::secondary_button(ui, tl!("Stop")).clicked() {
|
||||
action = DialogAction::Cancel;
|
||||
/// Whether a stop's message box is open.
|
||||
pub(crate) fn message_open(app: &VectorcraftApp) -> bool {
|
||||
app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.is_open::<StopMessage>()))
|
||||
}
|
||||
|
||||
/// Closes a stop's message box as Stop does; the playback keeps waiting. The closer consumes the
|
||||
/// Cancel it caused, so the pump does not read it as an answer.
|
||||
pub(crate) fn close_message(app: &VectorcraftApp) {
|
||||
let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) else { return };
|
||||
dialogs.with(|host| {
|
||||
if host.cancel::<StopMessage>(&ctx) {
|
||||
let _ = host.take::<StopMessage>();
|
||||
}
|
||||
});
|
||||
action
|
||||
}
|
||||
|
||||
fn message_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
if d.bool("allowContinue") {
|
||||
return app.run(crate::panels::actions::CONTINUE_PLAYBACK, json!({}));
|
||||
}
|
||||
app.ui.dialog = None;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
//! What the Actions panel's dialogs share: the form loop with its held OK, the place a step dialog
|
||||
//! writes into, the rows Action Options and New Action have in common, and the pump that answers
|
||||
//! every OK of the area.
|
||||
//!
|
||||
//! OK of an action dialog files its values and keeps the dialog open. [`pump`] runs the command the
|
||||
//! values stand for once a frame; the dialog closes when the command accepts them and shows the
|
||||
//! reason under its rows when the command refuses them.
|
||||
|
||||
use craft::automation::actions::ActionColor;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogResult, FieldRefusal, HeldAnswer, HeldOk, PromptChoice, StackDialog, serde_fields, set_serde_field};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{ListWords, label_color_label};
|
||||
use craft::ui::patterns::form_dialogs::FormDialog;
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::{Env, Label};
|
||||
use craft::ui::runtime::overlay::CloseReason;
|
||||
use egui::{Context, Ui};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::action_batch::BatchDialog;
|
||||
use super::action_insert_menu_item::InsertMenuItemDialog;
|
||||
use super::action_new::NewActionDialog;
|
||||
use super::action_select_object::SelectObjectDialog;
|
||||
use super::action_set_options::SetOptionsDialog;
|
||||
use super::action_stop::{RecordStopDialog, StopMessage};
|
||||
use crate::VectorcraftApp;
|
||||
// PLAN: `edits` and `playback` are private modules of `panels::actions` (menus-w13); the sheet calls `edits::take_answers`, `new_set` and `rename_set`, and menus-w15's `playback::included_commands`, from here, so both need `pub(crate) mod`.
|
||||
use crate::panels::actions::{CONTINUE_PLAYBACK, FUNCTION_KEYS, FunctionKey, edits, key_error};
|
||||
|
||||
/// The translated text of `english` as a label, without the colon a field label ends with: the form
|
||||
/// puts its own beside the control.
|
||||
pub(crate) fn label(english: &str) -> Label {
|
||||
Label::from(crate::i18n::t(english).trim_end_matches([':', ':']).trim_end().to_owned())
|
||||
}
|
||||
|
||||
/// What an action dialog's controls edit: a value the form can keep, compare, show as JSON and read
|
||||
/// back from it.
|
||||
pub(crate) trait Fields: Clone + PartialEq + Default + Send + Sync + Serialize + DeserializeOwned + 'static {}
|
||||
|
||||
impl<T> Fields for T where T: Clone + PartialEq + Default + Send + Sync + Serialize + DeserializeOwned + 'static {}
|
||||
|
||||
/// The form loop every action dialog runs: the values, the values it opened with (Reset), the
|
||||
/// held OK and the check that keeps OK off.
|
||||
pub(crate) struct Form<V: Fields> {
|
||||
/// What the dialog's controls edit.
|
||||
pub(crate) values: V,
|
||||
opening: V,
|
||||
held: HeldAnswer<V>,
|
||||
/// Why OK is off for these values; `None` when they can be accepted.
|
||||
check: fn(&V) -> Option<Label>,
|
||||
}
|
||||
|
||||
impl<V: Fields> Form<V> {
|
||||
/// A form opening on `values`, whose OK is off while `check` gives a reason.
|
||||
pub(crate) fn new(values: V, check: fn(&V) -> Option<Label>) -> Self {
|
||||
Form { opening: values.clone(), values, held: HeldAnswer::new(), check }
|
||||
}
|
||||
|
||||
/// Shows one pass. `ok` names the accepting button when it is not OK; `body` draws the rows and
|
||||
/// edits the values. OK files the values for [`pump`]; the pass after the app accepted them
|
||||
/// closes the dialog with them, and a refusal shows under the rows until a value changes.
|
||||
pub(crate) fn show(&mut self, ui: &mut Ui, title: Label, ok: Option<Label>, mut body: impl FnMut(&mut Ui, &mut V)) -> Option<DialogResult<V>> {
|
||||
// A measuring run closes nothing.
|
||||
let finish = self.held.is_accepted() && !craft::ui::runtime::measure::active(ui.ctx());
|
||||
let refusal = self.held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone()));
|
||||
let reason = (self.check)(&self.values);
|
||||
let check = self.check;
|
||||
let mut dialog = FormDialog::new(title, Bind::bound(&mut self.values))
|
||||
.opening(self.opening.clone())
|
||||
.accept_stays_open(true)
|
||||
.ok_enabled(reason.is_none() && !self.held.is_waiting());
|
||||
if let Some(ok) = ok {
|
||||
dialog = dialog.ok_label(ok);
|
||||
}
|
||||
if let Some(reason) = reason {
|
||||
dialog = dialog.ok_reason(reason);
|
||||
}
|
||||
let shown = dialog.show(ui, |ui, form, values| {
|
||||
body(ui, values);
|
||||
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) {
|
||||
Text::new(reason.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
if finish {
|
||||
form.request_close_as(CloseReason::Activated);
|
||||
}
|
||||
check(values).is_none()
|
||||
});
|
||||
if self.held.refusal().is_some_and(|(_, refused)| *refused != self.values) {
|
||||
self.held.clear_refusal();
|
||||
}
|
||||
// A pass reports a press only in the pass that took the input, so a second pass of the frame files nothing.
|
||||
if shown.picked == Some(0) && !self.held.is_waiting() {
|
||||
self.held.file(self.values.clone());
|
||||
}
|
||||
if finish && shown.closed == Some(CloseReason::Activated) {
|
||||
return Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok));
|
||||
}
|
||||
shown.closed.map(|_| DialogResult::Cancel)
|
||||
}
|
||||
|
||||
/// OK as a command gives it: files the values, or answers them once the app accepted them. `None`
|
||||
/// while OK is off or the app has not answered.
|
||||
pub(crate) fn confirm(&mut self) -> Option<V> {
|
||||
if self.held.is_accepted() {
|
||||
return self.held.finish();
|
||||
}
|
||||
if self.held.is_waiting() || (self.check)(&self.values).is_some() {
|
||||
return None;
|
||||
}
|
||||
self.held.file(self.values.clone());
|
||||
None
|
||||
}
|
||||
|
||||
/// The values OK filed, once.
|
||||
pub(crate) fn take(&mut self) -> Option<V> {
|
||||
self.held.take()
|
||||
}
|
||||
|
||||
/// The app's answer to the filed values.
|
||||
pub(crate) fn answer(&mut self, answer: Result<(), Label>) {
|
||||
self.held.answer(answer);
|
||||
}
|
||||
|
||||
/// Where the held OK stands.
|
||||
pub(crate) fn held_state(&self) -> Option<HeldOk> {
|
||||
self.held.state()
|
||||
}
|
||||
|
||||
/// The values as JSON, by their serde names.
|
||||
pub(crate) fn json_fields(&self) -> Option<Value> {
|
||||
serde_fields(&self.values)
|
||||
}
|
||||
|
||||
/// Sets the value `field` names as the control would; a value of another type is refused.
|
||||
pub(crate) fn set_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
set_serde_field(&mut self.values, field, value)?;
|
||||
ctx.request_repaint();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// An index a dialog field holds: `null` for none, else a whole number.
|
||||
pub(crate) fn set_index(slot: &mut Option<usize>, field: &str, value: &Value) -> Result<(), String> {
|
||||
let index = match value {
|
||||
Value::Null => None,
|
||||
other => Some(other.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| FieldRefusal::Rejects(value).message(field))?),
|
||||
};
|
||||
*slot = index;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the entries of the object `extra` to the object `fields`.
|
||||
pub(crate) fn merged(mut fields: Value, extra: Value) -> Value {
|
||||
if let (Some(into), Value::Object(extra)) = (fields.as_object_mut(), extra) {
|
||||
into.extend(extra);
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
/// Where the new step of a step dialog goes: the action at (`set`, `action`) after step `step`, else
|
||||
/// at its end; without a place, into the recording in progress. It stays out of the form's values so
|
||||
/// Reset keeps it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
/// The index of the set.
|
||||
pub set: Option<usize>,
|
||||
/// The index of the action in the set.
|
||||
pub action: Option<usize>,
|
||||
/// The step the new one goes after.
|
||||
pub step: Option<usize>,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// The place `open` gets: `step` means nothing without an action.
|
||||
pub(crate) fn new(place: Option<(usize, usize)>, step: Option<usize>) -> Self {
|
||||
Target { set: place.map(|(set, _)| set), action: place.map(|(_, action)| action), step: place.and(step) }
|
||||
}
|
||||
|
||||
/// The place as JSON fields.
|
||||
pub(crate) fn json(self) -> Value {
|
||||
json!({"set": self.set, "action": self.action, "step": self.step})
|
||||
}
|
||||
|
||||
/// Sets the place field `field` names; `None` when `field` is not one.
|
||||
pub(crate) fn set_field(&mut self, field: &str, value: &Value) -> Option<Result<(), String>> {
|
||||
let slot = match field {
|
||||
"set" => &mut self.set,
|
||||
"action" => &mut self.action,
|
||||
"step" => &mut self.step,
|
||||
_ => return None,
|
||||
};
|
||||
Some(set_index(slot, field, value))
|
||||
}
|
||||
|
||||
/// Adds the keys the place has to the params of the insert command.
|
||||
pub(crate) fn add_to(self, params: &mut Value) {
|
||||
for (key, index) in [("set", self.set), ("action", self.action), ("step", self.step)] {
|
||||
if let Some(index) = index {
|
||||
params[key] = json!(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The function key, color and Align To choice of an action: what New Action and Action Options
|
||||
/// share.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActionOptions {
|
||||
/// 0 for none, 1 to 15 for F1 to F15.
|
||||
pub key: u8,
|
||||
/// Ctrl, Command on macOS.
|
||||
pub cmd: bool,
|
||||
/// Shift.
|
||||
pub shift: bool,
|
||||
/// The Button Mode color; its file name in JSON.
|
||||
pub color: ActionColor,
|
||||
/// Whether Align at playback takes its reference from the live selection.
|
||||
pub automatic_align_to: bool,
|
||||
}
|
||||
|
||||
/// The JSON names of the fields [`ActionOptions`] adds to a dialog's values.
|
||||
pub(crate) const OPTION_KEYS: [&str; 5] = ["key", "cmd", "shift", "color", "automaticAlignTo"];
|
||||
|
||||
/// Why OK is off for the function key chosen, when the system or the platform keeps it.
|
||||
pub(crate) fn key_reason(options: &ActionOptions) -> Option<Label> {
|
||||
if options.key == 0 {
|
||||
return None;
|
||||
}
|
||||
key_error(FunctionKey { key: options.key, cmd: options.cmd, shift: options.shift }).map(|message| Label::from(crate::i18n::msg(&message)))
|
||||
}
|
||||
|
||||
/// The Function Key row (the key, Ctrl or ⌘, Shift) and the Color row.
|
||||
pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) {
|
||||
let keys: Vec<Entry<u8>> =
|
||||
std::iter::once(Entry::new(0, label("None"))).chain((1..=FUNCTION_KEYS).map(|n| Entry::new(n, Label::from(format!("F{n}"))))).collect();
|
||||
let modifier = if crate::keymap::platform() == craft::keymap::Platform::Mac { "⌘" } else { "Ctrl" };
|
||||
Field::new(label("Function Key:")).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
if let Some(key) = Select::new(label("Function Key:"), Bind::given(options.key), &keys).show(ui).value().copied() {
|
||||
options.key = key;
|
||||
}
|
||||
Checkbox::new(Bind::bound(&mut options.cmd)).label(modifier).show(ui);
|
||||
Checkbox::new(Bind::bound(&mut options.shift)).label(label("Shift")).show(ui);
|
||||
});
|
||||
});
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ListWords>();
|
||||
let colors: Vec<Entry<ActionColor>> =
|
||||
ActionColor::ALL.into_iter().map(|color| Entry::new(color, label_color_label(color.label_color(), &words))).collect();
|
||||
Field::new(label("Color:")).show(ui, |ui, _| {
|
||||
if let Some(color) = Select::new(label("Color:"), Bind::given(options.color), &colors).show(ui).value().copied() {
|
||||
options.color = color;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The Align playback choice and what it does.
|
||||
pub(crate) fn automatic_align_options(ui: &mut Ui, options: &mut ActionOptions) {
|
||||
Checkbox::new(Bind::bound(&mut options.automatic_align_to)).label(label("Choose Align To at playback")).show(ui);
|
||||
for line in [
|
||||
"Align steps use the key object, key anchor or key guide when one is set.",
|
||||
"With one whole object selected and no key, they use the artboard.",
|
||||
"Otherwise they use the selection.",
|
||||
] {
|
||||
Text::new(label(line)).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// The function key, color and Align params `ui.action.new` and `ui.action.options` take.
|
||||
pub(crate) fn key_and_color_params(options: &ActionOptions) -> Value {
|
||||
json!({
|
||||
"key": options.key,
|
||||
"cmd": options.cmd,
|
||||
"shift": options.shift,
|
||||
"color": options.color,
|
||||
"automaticAlignTo": options.automatic_align_to,
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens `dialog` on the window's dialog host; `Err` when the app has no window to show it in.
|
||||
pub(crate) fn open<D: StackDialog>(app: &VectorcraftApp, dialog: D) -> Result<(), String> {
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
dialogs.with(|host| host.open(dialog));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`open`] for the openers that return nothing: a missing window is said in the status line.
|
||||
pub(crate) fn open_or_say<D: StackDialog>(app: &mut VectorcraftApp, dialog: D) {
|
||||
if let Err(message) = open(app, dialog) {
|
||||
app.status(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog of this area whose filed OK [`pump`] answers by running a command.
|
||||
pub(crate) trait ActionDialog: StackDialog + Sized {
|
||||
/// What OK files, with the place the dialog holds when it was filed.
|
||||
type Answer;
|
||||
|
||||
/// The answer OK filed, once.
|
||||
fn take_ok(&mut self) -> Option<Self::Answer>;
|
||||
|
||||
/// The app's answer: `Ok` closes the dialog, `Err` keeps it open with the reason.
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>);
|
||||
|
||||
/// Runs the command the answer stands for.
|
||||
fn run(app: &mut VectorcraftApp, answer: Self::Answer) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// Answers the filed OK of the open `D`, if there is one; whether it answered one. A finished
|
||||
/// dialog's result carries nothing the app needs, so it is taken to keep the host tidy.
|
||||
fn settle<D: ActionDialog>(app: &mut VectorcraftApp) -> bool {
|
||||
let Some(dialogs) = app.dialogs() else { return false };
|
||||
let filed = dialogs.with(|host| {
|
||||
let _ = host.take::<D>();
|
||||
host.get_mut::<D>().and_then(D::take_ok)
|
||||
});
|
||||
let Some(answer) = filed else { return false };
|
||||
// The host is not locked while the command runs: a command may follow or close dialogs.
|
||||
let outcome = D::run(app, answer).map_err(Label::from);
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<D>() {
|
||||
dialog.answer_ok(outcome);
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Gives the open dialogs the app data they show: the set names, the Batch warning, the Insert Menu
|
||||
/// Item rows.
|
||||
fn push_app_data(app: &VectorcraftApp) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let sets: Vec<String> = app.ui.actions.sets().into_iter().map(str::to_owned).collect();
|
||||
let batch = dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<NewActionDialog>() {
|
||||
dialog.set_sets(&sets);
|
||||
}
|
||||
host.get::<BatchDialog>().map(|dialog| (dialog.set, dialog.action, dialog.fields().clone()))
|
||||
});
|
||||
if let Some((set, action, fields)) = batch {
|
||||
let warn = super::action_batch::overwrites_one_file(app, set, action, &fields);
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<BatchDialog>() {
|
||||
dialog.warn = warn;
|
||||
}
|
||||
});
|
||||
}
|
||||
let key = InsertMenuItemDialog::rows_key(app);
|
||||
if dialogs.with(|host| host.get::<InsertMenuItemDialog>().is_some_and(|dialog| dialog.built_from() != Some(key))) {
|
||||
let rows = super::action_insert_menu_item::build(crate::i18n::current(), app.session.prefs.font_names_in_english);
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<InsertMenuItemDialog>() {
|
||||
dialog.set_rows(key, rows);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose
|
||||
/// answer is written into the dialog.
|
||||
fn ask_batch_folders(app: &mut VectorcraftApp) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let asked = dialogs.with(|host| host.get_mut::<BatchDialog>().map(BatchDialog::take_asked).unwrap_or_default());
|
||||
for which in asked {
|
||||
super::action_batch::ask_folder(app, which);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs once a frame after the shell pass: gives the open dialogs the app data they show, answers
|
||||
/// every OK the dialogs of the Actions panel filed, and takes the answer of a stop's message box.
|
||||
/// A pass answers only the OK filed in its own pass, so a second pass of the frame finds none.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
|
||||
push_app_data(app);
|
||||
ask_batch_folders(app);
|
||||
let mut answered = settle::<NewActionDialog>(app);
|
||||
answered |= settle::<SetOptionsDialog>(app);
|
||||
answered |= settle::<RecordStopDialog>(app);
|
||||
answered |= settle::<InsertMenuItemDialog>(app);
|
||||
answered |= settle::<SelectObjectDialog>(app);
|
||||
answered |= settle::<super::action_playback::PlaybackDialog>(app);
|
||||
answered |= settle::<BatchDialog>(app);
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
let proceed = dialogs.with(|host| matches!(host.take::<StopMessage>(), Some(DialogResult::Ok(answer)) if answer.choice == PromptChoice::Proceed));
|
||||
if proceed {
|
||||
if let Err(message) = app.run(CONTINUE_PLAYBACK, json!({})) {
|
||||
app.status(message);
|
||||
}
|
||||
answered = true;
|
||||
}
|
||||
}
|
||||
edits::take_answers(app);
|
||||
if answered {
|
||||
// The dialog that was answered closes (or shows its reason) in the next pass.
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user