Keep Apply SVG Filter in its original drawing

This commit is contained in:
dotCooCoo committed 2026-11-26 15:05:16 -08:00
1 parent c646504cec
commit 371fba1735
1 file changed
+86 -23
+86 -23
View File
@@ -16,6 +16,8 @@
//! `__list` (the filters listed, pushed by [`pump`]), and with an applied effect `__index`,
//! `__item` and `missing` (the name of a deleted filter the effect names).
use std::sync::Arc;
use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::host::{PickRequest, Picked};
use craft::ui::buttons::Button;
@@ -47,6 +49,19 @@ const LISTING: &str = "__list";
/// The rows the filter list shows before it scrolls.
const LIST_ROWS: u16 = 7;
struct Opening {
document: u64,
}
fn opening_id() -> egui::Id {
egui::Id::unique((KIND, "opening"))
}
fn opening(app: &VectorcraftApp) -> Option<Arc<Opening>> {
with_dialog(app, |_| ())?;
app.ui_ctx.as_ref()?.data(|d| d.get_temp(opening_id()))
}
/// The dialog's heading.
fn heading() -> String {
tl!("Apply SVG Filter…").trim_end_matches('…').to_string()
@@ -252,9 +267,7 @@ fn code_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p
/// the default's code or with nothing; when neither has its name, the name shown above the list if
/// the filter was deleted, or else its code open as a new filter.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if app.session.active().is_none() {
return Err("no document open".into());
}
let document = app.session.active().ok_or("no document open")?.uid;
let mut fields = json!({ "selected": "", "code": "", "editing": "", "__action": "" });
if let Some(k) = p.get("index").and_then(Value::as_u64) {
let mut q = json!({});
@@ -289,7 +302,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let pairs = fields.as_object().into_iter().flatten().map(|(k, v)| (k.clone(), field_value(v.clone())));
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build);
crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields)).ok_or("no window")?;
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to apply this SVG filter").into());
}
confirm(app, &result.fields)
})
.ok_or("no window")?;
ctx.data_mut(|d| d.insert_temp(opening_id(), Arc::new(Opening { document })));
Ok(Value::Null)
}
@@ -337,6 +357,15 @@ fn set(app: &mut VectorcraftApp, fields: &[(&str, Value)]) {
/// Each frame: pushes the listed filters into the dialog (the build closure has no app) and runs the
/// button pressed, once.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(source) = opening(app) else { return };
if app.session.active().is_none_or(|st| st.uid != source.document) {
let has_action = with_dialog(app, |d| !text(d.fields(), ACTION).is_empty()).unwrap_or_default();
if has_action {
set(app, &[(ACTION, json!(""))]);
app.status(tl!("Return to the original drawing to edit its SVG filters"));
}
return;
}
let listing = listing(app);
let taken = with_dialog(app, |d| {
if json_field(d.fields(), LISTING).as_ref() != Some(&listing) {
@@ -374,7 +403,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Ok(())
}
"import" => {
ask_import(app);
ask_import(app, Some(source));
Ok(())
}
_ => Ok(()),
@@ -407,7 +436,7 @@ pub(crate) fn menu_items(names: &[String]) -> Vec<Node> {
/// `ui.importSvgFilter {}`: add the filters of an SVG file the user picks to the active document.
/// The answer is `{pending: "fileDialog"}`; the continuation runs the import.
pub fn import_file(app: &mut VectorcraftApp) -> Result<Value, String> {
Ok(ask_import(app))
Ok(ask_import(app, None))
}
/// The extensions of the SVG files Import… reads.
@@ -420,24 +449,33 @@ pub(crate) fn pick() -> PickRequest {
/// Asks for an SVG file; once picked, its filters are added to the document and the first one
/// added is selected in the dialog when it is open.
fn ask_import(app: &mut VectorcraftApp) -> Value {
file_asks::ask(app, pick(), Owner::Document, |app, picked| {
let params = match picked {
// The browser answers with the file's contents, not a path.
Picked::Contents(files) => {
let (_, bytes) = files.first().ok_or("cancelled")?;
json!({ "svg": String::from_utf8_lossy(bytes) })
fn ask_import(app: &mut VectorcraftApp, source: Option<Arc<Opening>>) -> Value {
let dialog = source.clone().or_else(|| opening(app).filter(|opening| app.session.active().is_some_and(|st| st.uid == opening.document)));
file_asks::ask_while(
app,
pick(),
Owner::Document,
move |app| source.is_none_or(|source| opening(app).is_some_and(|current| Arc::ptr_eq(&current, &source))),
move |app, picked| {
let params = match picked {
// The browser answers with the file's contents, not a path.
Picked::Contents(files) => {
let (_, bytes) = files.first().ok_or("cancelled")?;
json!({ "svg": String::from_utf8_lossy(bytes) })
}
other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }),
};
let r = app.run("svgFilter.import", params)?;
let added = r["added"].as_array().map_or(0, Vec::len);
app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[]));
if let Some(first) = r["added"].get(0)
&& dialog.is_some_and(|dialog| opening(app).is_some_and(|current| Arc::ptr_eq(&current, &dialog)))
{
set(app, &[(SELECTED, first.clone())]);
}
other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }),
};
let r = app.run("svgFilter.import", params)?;
let added = r["added"].as_array().map_or(0, Vec::len);
app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[]));
if let Some(first) = r["added"].get(0) {
set(app, &[(SELECTED, first.clone())]);
}
Ok(r)
})
Ok(r)
},
)
}
#[cfg(test)]
@@ -493,6 +531,31 @@ mod tests {
assert!(open_dialogs(&app).is_empty());
}
#[test]
fn svg_filter_ok_leaves_the_other_drawings_artwork_alone() {
let mut app = self::app();
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
let id = rect(&mut app);
app.run("file.new", json!({"width": 120, "height": 120})).unwrap();
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
assert_eq!(rect(&mut app), id);
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
activate(&mut app, 0);
open(&mut app, &json!({})).unwrap();
activate(&mut app, 1);
let dialog = dialog_id(KIND);
answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true);
assert!(effects(&app, id).is_empty());
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(&app)[SELECTED], "Shift");
activate(&mut app, 0);
answer_dialog(&mut app, dialog, &[], true);
assert_eq!(effects(&app, id)[0].params["name"], "Shift");
}
#[test]
fn the_dialog_draws_its_filters_and_buttons() {
let mut app = app();